env_test.cc 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #ifndef OS_WIN
  10. #include <sys/ioctl.h>
  11. #endif
  12. #include <sys/types.h>
  13. #include <iostream>
  14. #include <unordered_set>
  15. #include <atomic>
  16. #include <list>
  17. #ifdef OS_LINUX
  18. #include <fcntl.h>
  19. #include <linux/fs.h>
  20. #include <stdlib.h>
  21. #include <sys/stat.h>
  22. #include <unistd.h>
  23. #endif
  24. #ifdef ROCKSDB_FALLOCATE_PRESENT
  25. #include <errno.h>
  26. #endif
  27. #include "env/env_chroot.h"
  28. #include "logging/log_buffer.h"
  29. #include "port/malloc.h"
  30. #include "port/port.h"
  31. #include "rocksdb/env.h"
  32. #include "test_util/sync_point.h"
  33. #include "test_util/testharness.h"
  34. #include "test_util/testutil.h"
  35. #include "util/coding.h"
  36. #include "util/mutexlock.h"
  37. #include "util/string_util.h"
  38. namespace ROCKSDB_NAMESPACE {
  39. using port::kPageSize;
  40. static const int kDelayMicros = 100000;
  41. struct Deleter {
  42. explicit Deleter(void (*fn)(void*)) : fn_(fn) {}
  43. void operator()(void* ptr) {
  44. assert(fn_);
  45. assert(ptr);
  46. (*fn_)(ptr);
  47. }
  48. void (*fn_)(void*);
  49. };
  50. std::unique_ptr<char, Deleter> NewAligned(const size_t size, const char ch) {
  51. char* ptr = nullptr;
  52. #ifdef OS_WIN
  53. if (nullptr == (ptr = reinterpret_cast<char*>(_aligned_malloc(size, kPageSize)))) {
  54. return std::unique_ptr<char, Deleter>(nullptr, Deleter(_aligned_free));
  55. }
  56. std::unique_ptr<char, Deleter> uptr(ptr, Deleter(_aligned_free));
  57. #else
  58. if (posix_memalign(reinterpret_cast<void**>(&ptr), kPageSize, size) != 0) {
  59. return std::unique_ptr<char, Deleter>(nullptr, Deleter(free));
  60. }
  61. std::unique_ptr<char, Deleter> uptr(ptr, Deleter(free));
  62. #endif
  63. memset(uptr.get(), ch, size);
  64. return uptr;
  65. }
  66. class EnvPosixTest : public testing::Test {
  67. private:
  68. port::Mutex mu_;
  69. std::string events_;
  70. public:
  71. Env* env_;
  72. bool direct_io_;
  73. EnvPosixTest() : env_(Env::Default()), direct_io_(false) {}
  74. };
  75. class EnvPosixTestWithParam
  76. : public EnvPosixTest,
  77. public ::testing::WithParamInterface<std::pair<Env*, bool>> {
  78. public:
  79. EnvPosixTestWithParam() {
  80. std::pair<Env*, bool> param_pair = GetParam();
  81. env_ = param_pair.first;
  82. direct_io_ = param_pair.second;
  83. }
  84. void WaitThreadPoolsEmpty() {
  85. // Wait until the thread pools are empty.
  86. while (env_->GetThreadPoolQueueLen(Env::Priority::LOW) != 0) {
  87. Env::Default()->SleepForMicroseconds(kDelayMicros);
  88. }
  89. while (env_->GetThreadPoolQueueLen(Env::Priority::HIGH) != 0) {
  90. Env::Default()->SleepForMicroseconds(kDelayMicros);
  91. }
  92. }
  93. ~EnvPosixTestWithParam() override { WaitThreadPoolsEmpty(); }
  94. };
  95. static void SetBool(void* ptr) {
  96. reinterpret_cast<std::atomic<bool>*>(ptr)->store(true);
  97. }
  98. TEST_F(EnvPosixTest, DISABLED_RunImmediately) {
  99. for (int pri = Env::BOTTOM; pri < Env::TOTAL; ++pri) {
  100. std::atomic<bool> called(false);
  101. env_->SetBackgroundThreads(1, static_cast<Env::Priority>(pri));
  102. env_->Schedule(&SetBool, &called, static_cast<Env::Priority>(pri));
  103. Env::Default()->SleepForMicroseconds(kDelayMicros);
  104. ASSERT_TRUE(called.load());
  105. }
  106. }
  107. TEST_F(EnvPosixTest, RunEventually) {
  108. std::atomic<bool> called(false);
  109. env_->StartThread(&SetBool, &called);
  110. env_->WaitForJoin();
  111. ASSERT_TRUE(called.load());
  112. }
  113. #ifdef OS_WIN
  114. TEST_F(EnvPosixTest, AreFilesSame) {
  115. {
  116. bool tmp;
  117. if (env_->AreFilesSame("", "", &tmp).IsNotSupported()) {
  118. fprintf(stderr,
  119. "skipping EnvBasicTestWithParam.AreFilesSame due to "
  120. "unsupported Env::AreFilesSame\n");
  121. return;
  122. }
  123. }
  124. const EnvOptions soptions;
  125. auto* env = Env::Default();
  126. std::string same_file_name = test::PerThreadDBPath(env, "same_file");
  127. std::string same_file_link_name = same_file_name + "_link";
  128. std::unique_ptr<WritableFile> same_file;
  129. ASSERT_OK(env->NewWritableFile(same_file_name,
  130. &same_file, soptions));
  131. same_file->Append("random_data");
  132. ASSERT_OK(same_file->Flush());
  133. same_file.reset();
  134. ASSERT_OK(env->LinkFile(same_file_name, same_file_link_name));
  135. bool result = false;
  136. ASSERT_OK(env->AreFilesSame(same_file_name, same_file_link_name, &result));
  137. ASSERT_TRUE(result);
  138. }
  139. #endif
  140. #ifdef OS_LINUX
  141. TEST_F(EnvPosixTest, DISABLED_FilePermission) {
  142. // Only works for Linux environment
  143. if (env_ == Env::Default()) {
  144. EnvOptions soptions;
  145. std::vector<std::string> fileNames{
  146. test::PerThreadDBPath(env_, "testfile"),
  147. test::PerThreadDBPath(env_, "testfile1")};
  148. std::unique_ptr<WritableFile> wfile;
  149. ASSERT_OK(env_->NewWritableFile(fileNames[0], &wfile, soptions));
  150. ASSERT_OK(env_->NewWritableFile(fileNames[1], &wfile, soptions));
  151. wfile.reset();
  152. std::unique_ptr<RandomRWFile> rwfile;
  153. ASSERT_OK(env_->NewRandomRWFile(fileNames[1], &rwfile, soptions));
  154. struct stat sb;
  155. for (const auto& filename : fileNames) {
  156. if (::stat(filename.c_str(), &sb) == 0) {
  157. ASSERT_EQ(sb.st_mode & 0777, 0644);
  158. }
  159. env_->DeleteFile(filename);
  160. }
  161. env_->SetAllowNonOwnerAccess(false);
  162. ASSERT_OK(env_->NewWritableFile(fileNames[0], &wfile, soptions));
  163. ASSERT_OK(env_->NewWritableFile(fileNames[1], &wfile, soptions));
  164. wfile.reset();
  165. ASSERT_OK(env_->NewRandomRWFile(fileNames[1], &rwfile, soptions));
  166. for (const auto& filename : fileNames) {
  167. if (::stat(filename.c_str(), &sb) == 0) {
  168. ASSERT_EQ(sb.st_mode & 0777, 0600);
  169. }
  170. env_->DeleteFile(filename);
  171. }
  172. }
  173. }
  174. #endif
  175. TEST_F(EnvPosixTest, MemoryMappedFileBuffer) {
  176. const int kFileBytes = 1 << 15; // 32 KB
  177. std::string expected_data;
  178. std::string fname = test::PerThreadDBPath(env_, "testfile");
  179. {
  180. std::unique_ptr<WritableFile> wfile;
  181. const EnvOptions soptions;
  182. ASSERT_OK(env_->NewWritableFile(fname, &wfile, soptions));
  183. Random rnd(301);
  184. test::RandomString(&rnd, kFileBytes, &expected_data);
  185. ASSERT_OK(wfile->Append(expected_data));
  186. }
  187. std::unique_ptr<MemoryMappedFileBuffer> mmap_buffer;
  188. Status status = env_->NewMemoryMappedFileBuffer(fname, &mmap_buffer);
  189. // it should be supported at least on linux
  190. #if !defined(OS_LINUX)
  191. if (status.IsNotSupported()) {
  192. fprintf(stderr,
  193. "skipping EnvPosixTest.MemoryMappedFileBuffer due to "
  194. "unsupported Env::NewMemoryMappedFileBuffer\n");
  195. return;
  196. }
  197. #endif // !defined(OS_LINUX)
  198. ASSERT_OK(status);
  199. ASSERT_NE(nullptr, mmap_buffer.get());
  200. ASSERT_NE(nullptr, mmap_buffer->GetBase());
  201. ASSERT_EQ(kFileBytes, mmap_buffer->GetLen());
  202. std::string actual_data(reinterpret_cast<const char*>(mmap_buffer->GetBase()),
  203. mmap_buffer->GetLen());
  204. ASSERT_EQ(expected_data, actual_data);
  205. }
  206. #ifndef ROCKSDB_NO_DYNAMIC_EXTENSION
  207. TEST_F(EnvPosixTest, LoadRocksDBLibrary) {
  208. std::shared_ptr<DynamicLibrary> library;
  209. std::function<void*(void*, const char*)> function;
  210. Status status = env_->LoadLibrary("no-such-library", "", &library);
  211. ASSERT_NOK(status);
  212. ASSERT_EQ(nullptr, library.get());
  213. status = env_->LoadLibrary("rocksdb", "", &library);
  214. if (status.ok()) { // If we have can find a rocksdb shared library
  215. ASSERT_NE(nullptr, library.get());
  216. ASSERT_OK(library->LoadFunction("rocksdb_create_default_env",
  217. &function)); // from C definition
  218. ASSERT_NE(nullptr, function);
  219. ASSERT_NOK(library->LoadFunction("no-such-method", &function));
  220. ASSERT_EQ(nullptr, function);
  221. ASSERT_OK(env_->LoadLibrary(library->Name(), "", &library));
  222. } else {
  223. ASSERT_EQ(nullptr, library.get());
  224. }
  225. }
  226. #endif // !ROCKSDB_NO_DYNAMIC_EXTENSION
  227. #if !defined(OS_WIN) && !defined(ROCKSDB_NO_DYNAMIC_EXTENSION)
  228. TEST_F(EnvPosixTest, LoadRocksDBLibraryWithSearchPath) {
  229. std::shared_ptr<DynamicLibrary> library;
  230. std::function<void*(void*, const char*)> function;
  231. ASSERT_NOK(env_->LoadLibrary("no-such-library", "/tmp", &library));
  232. ASSERT_EQ(nullptr, library.get());
  233. ASSERT_NOK(env_->LoadLibrary("dl", "/tmp", &library));
  234. ASSERT_EQ(nullptr, library.get());
  235. Status status = env_->LoadLibrary("rocksdb", "/tmp:./", &library);
  236. if (status.ok()) {
  237. ASSERT_NE(nullptr, library.get());
  238. ASSERT_OK(env_->LoadLibrary(library->Name(), "", &library));
  239. }
  240. char buff[1024];
  241. std::string cwd = getcwd(buff, sizeof(buff));
  242. status = env_->LoadLibrary("rocksdb", "/tmp:" + cwd, &library);
  243. if (status.ok()) {
  244. ASSERT_NE(nullptr, library.get());
  245. ASSERT_OK(env_->LoadLibrary(library->Name(), "", &library));
  246. }
  247. }
  248. #endif // !OS_WIN && !ROCKSDB_NO_DYNAMIC_EXTENSION
  249. TEST_P(EnvPosixTestWithParam, UnSchedule) {
  250. std::atomic<bool> called(false);
  251. env_->SetBackgroundThreads(1, Env::LOW);
  252. /* Block the low priority queue */
  253. test::SleepingBackgroundTask sleeping_task, sleeping_task1;
  254. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task,
  255. Env::Priority::LOW);
  256. /* Schedule another task */
  257. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task1,
  258. Env::Priority::LOW, &sleeping_task1);
  259. /* Remove it with a different tag */
  260. ASSERT_EQ(0, env_->UnSchedule(&called, Env::Priority::LOW));
  261. /* Remove it from the queue with the right tag */
  262. ASSERT_EQ(1, env_->UnSchedule(&sleeping_task1, Env::Priority::LOW));
  263. // Unblock background thread
  264. sleeping_task.WakeUp();
  265. /* Schedule another task */
  266. env_->Schedule(&SetBool, &called);
  267. for (int i = 0; i < kDelayMicros; i++) {
  268. if (called.load()) {
  269. break;
  270. }
  271. Env::Default()->SleepForMicroseconds(1);
  272. }
  273. ASSERT_TRUE(called.load());
  274. ASSERT_TRUE(!sleeping_task.IsSleeping() && !sleeping_task1.IsSleeping());
  275. WaitThreadPoolsEmpty();
  276. }
  277. // This tests assumes that the last scheduled
  278. // task will run last. In fact, in the allotted
  279. // sleeping time nothing may actually run or they may
  280. // run in any order. The purpose of the test is unclear.
  281. #ifndef OS_WIN
  282. TEST_P(EnvPosixTestWithParam, RunMany) {
  283. std::atomic<int> last_id(0);
  284. struct CB {
  285. std::atomic<int>* last_id_ptr; // Pointer to shared slot
  286. int id; // Order# for the execution of this callback
  287. CB(std::atomic<int>* p, int i) : last_id_ptr(p), id(i) {}
  288. static void Run(void* v) {
  289. CB* cb = reinterpret_cast<CB*>(v);
  290. int cur = cb->last_id_ptr->load();
  291. ASSERT_EQ(cb->id - 1, cur);
  292. cb->last_id_ptr->store(cb->id);
  293. }
  294. };
  295. // Schedule in different order than start time
  296. CB cb1(&last_id, 1);
  297. CB cb2(&last_id, 2);
  298. CB cb3(&last_id, 3);
  299. CB cb4(&last_id, 4);
  300. env_->Schedule(&CB::Run, &cb1);
  301. env_->Schedule(&CB::Run, &cb2);
  302. env_->Schedule(&CB::Run, &cb3);
  303. env_->Schedule(&CB::Run, &cb4);
  304. Env::Default()->SleepForMicroseconds(kDelayMicros);
  305. int cur = last_id.load(std::memory_order_acquire);
  306. ASSERT_EQ(4, cur);
  307. WaitThreadPoolsEmpty();
  308. }
  309. #endif
  310. struct State {
  311. port::Mutex mu;
  312. int val;
  313. int num_running;
  314. };
  315. static void ThreadBody(void* arg) {
  316. State* s = reinterpret_cast<State*>(arg);
  317. s->mu.Lock();
  318. s->val += 1;
  319. s->num_running -= 1;
  320. s->mu.Unlock();
  321. }
  322. TEST_P(EnvPosixTestWithParam, StartThread) {
  323. State state;
  324. state.val = 0;
  325. state.num_running = 3;
  326. for (int i = 0; i < 3; i++) {
  327. env_->StartThread(&ThreadBody, &state);
  328. }
  329. while (true) {
  330. state.mu.Lock();
  331. int num = state.num_running;
  332. state.mu.Unlock();
  333. if (num == 0) {
  334. break;
  335. }
  336. Env::Default()->SleepForMicroseconds(kDelayMicros);
  337. }
  338. ASSERT_EQ(state.val, 3);
  339. WaitThreadPoolsEmpty();
  340. }
  341. TEST_P(EnvPosixTestWithParam, TwoPools) {
  342. // Data structures to signal tasks to run.
  343. port::Mutex mutex;
  344. port::CondVar cv(&mutex);
  345. bool should_start = false;
  346. class CB {
  347. public:
  348. CB(const std::string& pool_name, int pool_size, port::Mutex* trigger_mu,
  349. port::CondVar* trigger_cv, bool* _should_start)
  350. : mu_(),
  351. num_running_(0),
  352. num_finished_(0),
  353. pool_size_(pool_size),
  354. pool_name_(pool_name),
  355. trigger_mu_(trigger_mu),
  356. trigger_cv_(trigger_cv),
  357. should_start_(_should_start) {}
  358. static void Run(void* v) {
  359. CB* cb = reinterpret_cast<CB*>(v);
  360. cb->Run();
  361. }
  362. void Run() {
  363. {
  364. MutexLock l(&mu_);
  365. num_running_++;
  366. // make sure we don't have more than pool_size_ jobs running.
  367. ASSERT_LE(num_running_, pool_size_.load());
  368. }
  369. {
  370. MutexLock l(trigger_mu_);
  371. while (!(*should_start_)) {
  372. trigger_cv_->Wait();
  373. }
  374. }
  375. {
  376. MutexLock l(&mu_);
  377. num_running_--;
  378. num_finished_++;
  379. }
  380. }
  381. int NumFinished() {
  382. MutexLock l(&mu_);
  383. return num_finished_;
  384. }
  385. void Reset(int pool_size) {
  386. pool_size_.store(pool_size);
  387. num_finished_ = 0;
  388. }
  389. private:
  390. port::Mutex mu_;
  391. int num_running_;
  392. int num_finished_;
  393. std::atomic<int> pool_size_;
  394. std::string pool_name_;
  395. port::Mutex* trigger_mu_;
  396. port::CondVar* trigger_cv_;
  397. bool* should_start_;
  398. };
  399. const int kLowPoolSize = 2;
  400. const int kHighPoolSize = 4;
  401. const int kJobs = 8;
  402. CB low_pool_job("low", kLowPoolSize, &mutex, &cv, &should_start);
  403. CB high_pool_job("high", kHighPoolSize, &mutex, &cv, &should_start);
  404. env_->SetBackgroundThreads(kLowPoolSize);
  405. env_->SetBackgroundThreads(kHighPoolSize, Env::Priority::HIGH);
  406. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::LOW));
  407. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  408. // schedule same number of jobs in each pool
  409. for (int i = 0; i < kJobs; i++) {
  410. env_->Schedule(&CB::Run, &low_pool_job);
  411. env_->Schedule(&CB::Run, &high_pool_job, Env::Priority::HIGH);
  412. }
  413. // Wait a short while for the jobs to be dispatched.
  414. int sleep_count = 0;
  415. while ((unsigned int)(kJobs - kLowPoolSize) !=
  416. env_->GetThreadPoolQueueLen(Env::Priority::LOW) ||
  417. (unsigned int)(kJobs - kHighPoolSize) !=
  418. env_->GetThreadPoolQueueLen(Env::Priority::HIGH)) {
  419. env_->SleepForMicroseconds(kDelayMicros);
  420. if (++sleep_count > 100) {
  421. break;
  422. }
  423. }
  424. ASSERT_EQ((unsigned int)(kJobs - kLowPoolSize),
  425. env_->GetThreadPoolQueueLen());
  426. ASSERT_EQ((unsigned int)(kJobs - kLowPoolSize),
  427. env_->GetThreadPoolQueueLen(Env::Priority::LOW));
  428. ASSERT_EQ((unsigned int)(kJobs - kHighPoolSize),
  429. env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  430. // Trigger jobs to run.
  431. {
  432. MutexLock l(&mutex);
  433. should_start = true;
  434. cv.SignalAll();
  435. }
  436. // wait for all jobs to finish
  437. while (low_pool_job.NumFinished() < kJobs ||
  438. high_pool_job.NumFinished() < kJobs) {
  439. env_->SleepForMicroseconds(kDelayMicros);
  440. }
  441. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::LOW));
  442. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  443. // Hold jobs to schedule;
  444. should_start = false;
  445. // call IncBackgroundThreadsIfNeeded to two pools. One increasing and
  446. // the other decreasing
  447. env_->IncBackgroundThreadsIfNeeded(kLowPoolSize - 1, Env::Priority::LOW);
  448. env_->IncBackgroundThreadsIfNeeded(kHighPoolSize + 1, Env::Priority::HIGH);
  449. high_pool_job.Reset(kHighPoolSize + 1);
  450. low_pool_job.Reset(kLowPoolSize);
  451. // schedule same number of jobs in each pool
  452. for (int i = 0; i < kJobs; i++) {
  453. env_->Schedule(&CB::Run, &low_pool_job);
  454. env_->Schedule(&CB::Run, &high_pool_job, Env::Priority::HIGH);
  455. }
  456. // Wait a short while for the jobs to be dispatched.
  457. sleep_count = 0;
  458. while ((unsigned int)(kJobs - kLowPoolSize) !=
  459. env_->GetThreadPoolQueueLen(Env::Priority::LOW) ||
  460. (unsigned int)(kJobs - (kHighPoolSize + 1)) !=
  461. env_->GetThreadPoolQueueLen(Env::Priority::HIGH)) {
  462. env_->SleepForMicroseconds(kDelayMicros);
  463. if (++sleep_count > 100) {
  464. break;
  465. }
  466. }
  467. ASSERT_EQ((unsigned int)(kJobs - kLowPoolSize),
  468. env_->GetThreadPoolQueueLen());
  469. ASSERT_EQ((unsigned int)(kJobs - kLowPoolSize),
  470. env_->GetThreadPoolQueueLen(Env::Priority::LOW));
  471. ASSERT_EQ((unsigned int)(kJobs - (kHighPoolSize + 1)),
  472. env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  473. // Trigger jobs to run.
  474. {
  475. MutexLock l(&mutex);
  476. should_start = true;
  477. cv.SignalAll();
  478. }
  479. // wait for all jobs to finish
  480. while (low_pool_job.NumFinished() < kJobs ||
  481. high_pool_job.NumFinished() < kJobs) {
  482. env_->SleepForMicroseconds(kDelayMicros);
  483. }
  484. env_->SetBackgroundThreads(kHighPoolSize, Env::Priority::HIGH);
  485. WaitThreadPoolsEmpty();
  486. }
  487. TEST_P(EnvPosixTestWithParam, DecreaseNumBgThreads) {
  488. constexpr int kWaitMicros = 60000000; // 1min
  489. std::vector<test::SleepingBackgroundTask> tasks(10);
  490. // Set number of thread to 1 first.
  491. env_->SetBackgroundThreads(1, Env::Priority::HIGH);
  492. // Schedule 3 tasks. 0 running; Task 1, 2 waiting.
  493. for (size_t i = 0; i < 3; i++) {
  494. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &tasks[i],
  495. Env::Priority::HIGH);
  496. }
  497. ASSERT_FALSE(tasks[0].TimedWaitUntilSleeping(kWaitMicros));
  498. ASSERT_EQ(2U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  499. ASSERT_TRUE(tasks[0].IsSleeping());
  500. ASSERT_TRUE(!tasks[1].IsSleeping());
  501. ASSERT_TRUE(!tasks[2].IsSleeping());
  502. // Increase to 2 threads. Task 0, 1 running; 2 waiting
  503. env_->SetBackgroundThreads(2, Env::Priority::HIGH);
  504. ASSERT_FALSE(tasks[1].TimedWaitUntilSleeping(kWaitMicros));
  505. ASSERT_EQ(1U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  506. ASSERT_TRUE(tasks[0].IsSleeping());
  507. ASSERT_TRUE(tasks[1].IsSleeping());
  508. ASSERT_TRUE(!tasks[2].IsSleeping());
  509. // Shrink back to 1 thread. Still task 0, 1 running, 2 waiting
  510. env_->SetBackgroundThreads(1, Env::Priority::HIGH);
  511. Env::Default()->SleepForMicroseconds(kDelayMicros);
  512. ASSERT_EQ(1U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  513. ASSERT_TRUE(tasks[0].IsSleeping());
  514. ASSERT_TRUE(tasks[1].IsSleeping());
  515. ASSERT_TRUE(!tasks[2].IsSleeping());
  516. // The last task finishes. Task 0 running, 2 waiting.
  517. tasks[1].WakeUp();
  518. ASSERT_FALSE(tasks[1].TimedWaitUntilDone(kWaitMicros));
  519. ASSERT_EQ(1U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  520. ASSERT_TRUE(tasks[0].IsSleeping());
  521. ASSERT_TRUE(!tasks[1].IsSleeping());
  522. ASSERT_TRUE(!tasks[2].IsSleeping());
  523. // Increase to 5 threads. Task 0 and 2 running.
  524. env_->SetBackgroundThreads(5, Env::Priority::HIGH);
  525. ASSERT_FALSE(tasks[2].TimedWaitUntilSleeping(kWaitMicros));
  526. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  527. ASSERT_TRUE(tasks[0].IsSleeping());
  528. ASSERT_TRUE(!tasks[1].IsSleeping());
  529. ASSERT_TRUE(tasks[2].IsSleeping());
  530. // Change number of threads a couple of times while there is no sufficient
  531. // tasks.
  532. env_->SetBackgroundThreads(7, Env::Priority::HIGH);
  533. tasks[2].WakeUp();
  534. ASSERT_FALSE(tasks[2].TimedWaitUntilDone(kWaitMicros));
  535. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  536. env_->SetBackgroundThreads(3, Env::Priority::HIGH);
  537. Env::Default()->SleepForMicroseconds(kDelayMicros);
  538. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  539. env_->SetBackgroundThreads(4, Env::Priority::HIGH);
  540. Env::Default()->SleepForMicroseconds(kDelayMicros);
  541. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  542. env_->SetBackgroundThreads(5, Env::Priority::HIGH);
  543. Env::Default()->SleepForMicroseconds(kDelayMicros);
  544. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  545. env_->SetBackgroundThreads(4, Env::Priority::HIGH);
  546. Env::Default()->SleepForMicroseconds(kDelayMicros);
  547. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  548. Env::Default()->SleepForMicroseconds(kDelayMicros * 50);
  549. // Enqueue 5 more tasks. Thread pool size now is 4.
  550. // Task 0, 3, 4, 5 running;6, 7 waiting.
  551. for (size_t i = 3; i < 8; i++) {
  552. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &tasks[i],
  553. Env::Priority::HIGH);
  554. }
  555. for (size_t i = 3; i <= 5; i++) {
  556. ASSERT_FALSE(tasks[i].TimedWaitUntilSleeping(kWaitMicros));
  557. }
  558. ASSERT_EQ(2U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  559. ASSERT_TRUE(tasks[0].IsSleeping());
  560. ASSERT_TRUE(!tasks[1].IsSleeping());
  561. ASSERT_TRUE(!tasks[2].IsSleeping());
  562. ASSERT_TRUE(tasks[3].IsSleeping());
  563. ASSERT_TRUE(tasks[4].IsSleeping());
  564. ASSERT_TRUE(tasks[5].IsSleeping());
  565. ASSERT_TRUE(!tasks[6].IsSleeping());
  566. ASSERT_TRUE(!tasks[7].IsSleeping());
  567. // Wake up task 0, 3 and 4. Task 5, 6, 7 running.
  568. tasks[0].WakeUp();
  569. tasks[3].WakeUp();
  570. tasks[4].WakeUp();
  571. for (size_t i = 5; i < 8; i++) {
  572. ASSERT_FALSE(tasks[i].TimedWaitUntilSleeping(kWaitMicros));
  573. }
  574. ASSERT_EQ(0U, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  575. for (size_t i = 5; i < 8; i++) {
  576. ASSERT_TRUE(tasks[i].IsSleeping());
  577. }
  578. // Shrink back to 1 thread. Still task 5, 6, 7 running
  579. env_->SetBackgroundThreads(1, Env::Priority::HIGH);
  580. Env::Default()->SleepForMicroseconds(kDelayMicros);
  581. ASSERT_TRUE(tasks[5].IsSleeping());
  582. ASSERT_TRUE(tasks[6].IsSleeping());
  583. ASSERT_TRUE(tasks[7].IsSleeping());
  584. // Wake up task 6. Task 5, 7 running
  585. tasks[6].WakeUp();
  586. ASSERT_FALSE(tasks[6].TimedWaitUntilDone(kWaitMicros));
  587. ASSERT_TRUE(tasks[5].IsSleeping());
  588. ASSERT_TRUE(!tasks[6].IsSleeping());
  589. ASSERT_TRUE(tasks[7].IsSleeping());
  590. // Wake up threads 7. Task 5 running
  591. tasks[7].WakeUp();
  592. ASSERT_FALSE(tasks[7].TimedWaitUntilDone(kWaitMicros));
  593. ASSERT_TRUE(!tasks[7].IsSleeping());
  594. // Enqueue thread 8 and 9. Task 5 running; one of 8, 9 might be running.
  595. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &tasks[8],
  596. Env::Priority::HIGH);
  597. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &tasks[9],
  598. Env::Priority::HIGH);
  599. Env::Default()->SleepForMicroseconds(kDelayMicros);
  600. ASSERT_GT(env_->GetThreadPoolQueueLen(Env::Priority::HIGH), (unsigned int)0);
  601. ASSERT_TRUE(!tasks[8].IsSleeping() || !tasks[9].IsSleeping());
  602. // Increase to 4 threads. Task 5, 8, 9 running.
  603. env_->SetBackgroundThreads(4, Env::Priority::HIGH);
  604. Env::Default()->SleepForMicroseconds(kDelayMicros);
  605. ASSERT_EQ((unsigned int)0, env_->GetThreadPoolQueueLen(Env::Priority::HIGH));
  606. ASSERT_TRUE(tasks[8].IsSleeping());
  607. ASSERT_TRUE(tasks[9].IsSleeping());
  608. // Shrink to 1 thread
  609. env_->SetBackgroundThreads(1, Env::Priority::HIGH);
  610. // Wake up thread 9.
  611. tasks[9].WakeUp();
  612. ASSERT_FALSE(tasks[9].TimedWaitUntilDone(kWaitMicros));
  613. ASSERT_TRUE(!tasks[9].IsSleeping());
  614. ASSERT_TRUE(tasks[8].IsSleeping());
  615. // Wake up thread 8
  616. tasks[8].WakeUp();
  617. ASSERT_FALSE(tasks[8].TimedWaitUntilDone(kWaitMicros));
  618. ASSERT_TRUE(!tasks[8].IsSleeping());
  619. // Wake up the last thread
  620. tasks[5].WakeUp();
  621. ASSERT_FALSE(tasks[5].TimedWaitUntilDone(kWaitMicros));
  622. WaitThreadPoolsEmpty();
  623. }
  624. #if (defined OS_LINUX || defined OS_WIN)
  625. // Travis doesn't support fallocate or getting unique ID from files for whatever
  626. // reason.
  627. #ifndef TRAVIS
  628. namespace {
  629. bool IsSingleVarint(const std::string& s) {
  630. Slice slice(s);
  631. uint64_t v;
  632. if (!GetVarint64(&slice, &v)) {
  633. return false;
  634. }
  635. return slice.size() == 0;
  636. }
  637. bool IsUniqueIDValid(const std::string& s) {
  638. return !s.empty() && !IsSingleVarint(s);
  639. }
  640. const size_t MAX_ID_SIZE = 100;
  641. char temp_id[MAX_ID_SIZE];
  642. } // namespace
  643. // Determine whether we can use the FS_IOC_GETVERSION ioctl
  644. // on a file in directory DIR. Create a temporary file therein,
  645. // try to apply the ioctl (save that result), cleanup and
  646. // return the result. Return true if it is supported, and
  647. // false if anything fails.
  648. // Note that this function "knows" that dir has just been created
  649. // and is empty, so we create a simply-named test file: "f".
  650. bool ioctl_support__FS_IOC_GETVERSION(const std::string& dir) {
  651. #ifdef OS_WIN
  652. return true;
  653. #else
  654. const std::string file = dir + "/f";
  655. int fd;
  656. do {
  657. fd = open(file.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0644);
  658. } while (fd < 0 && errno == EINTR);
  659. long int version;
  660. bool ok = (fd >= 0 && ioctl(fd, FS_IOC_GETVERSION, &version) >= 0);
  661. close(fd);
  662. unlink(file.c_str());
  663. return ok;
  664. #endif
  665. }
  666. // To ensure that Env::GetUniqueId-related tests work correctly, the files
  667. // should be stored in regular storage like "hard disk" or "flash device",
  668. // and not on a tmpfs file system (like /dev/shm and /tmp on some systems).
  669. // Otherwise we cannot get the correct id.
  670. //
  671. // This function serves as the replacement for test::TmpDir(), which may be
  672. // customized to be on a file system that doesn't work with GetUniqueId().
  673. class IoctlFriendlyTmpdir {
  674. public:
  675. explicit IoctlFriendlyTmpdir() {
  676. char dir_buf[100];
  677. const char *fmt = "%s/rocksdb.XXXXXX";
  678. const char *tmp = getenv("TEST_IOCTL_FRIENDLY_TMPDIR");
  679. #ifdef OS_WIN
  680. #define rmdir _rmdir
  681. if(tmp == nullptr) {
  682. tmp = getenv("TMP");
  683. }
  684. snprintf(dir_buf, sizeof dir_buf, fmt, tmp);
  685. auto result = _mktemp(dir_buf);
  686. assert(result != nullptr);
  687. BOOL ret = CreateDirectory(dir_buf, NULL);
  688. assert(ret == TRUE);
  689. dir_ = dir_buf;
  690. #else
  691. std::list<std::string> candidate_dir_list = {"/var/tmp", "/tmp"};
  692. // If $TEST_IOCTL_FRIENDLY_TMPDIR/rocksdb.XXXXXX fits, use
  693. // $TEST_IOCTL_FRIENDLY_TMPDIR; subtract 2 for the "%s", and
  694. // add 1 for the trailing NUL byte.
  695. if (tmp && strlen(tmp) + strlen(fmt) - 2 + 1 <= sizeof dir_buf) {
  696. // use $TEST_IOCTL_FRIENDLY_TMPDIR value
  697. candidate_dir_list.push_front(tmp);
  698. }
  699. for (const std::string& d : candidate_dir_list) {
  700. snprintf(dir_buf, sizeof dir_buf, fmt, d.c_str());
  701. if (mkdtemp(dir_buf)) {
  702. if (ioctl_support__FS_IOC_GETVERSION(dir_buf)) {
  703. dir_ = dir_buf;
  704. return;
  705. } else {
  706. // Diagnose ioctl-related failure only if this is the
  707. // directory specified via that envvar.
  708. if (tmp && tmp == d) {
  709. fprintf(stderr, "TEST_IOCTL_FRIENDLY_TMPDIR-specified directory is "
  710. "not suitable: %s\n", d.c_str());
  711. }
  712. rmdir(dir_buf); // ignore failure
  713. }
  714. } else {
  715. // mkdtemp failed: diagnose it, but don't give up.
  716. fprintf(stderr, "mkdtemp(%s/...) failed: %s\n", d.c_str(),
  717. strerror(errno));
  718. }
  719. }
  720. fprintf(stderr, "failed to find an ioctl-friendly temporary directory;"
  721. " specify one via the TEST_IOCTL_FRIENDLY_TMPDIR envvar\n");
  722. std::abort();
  723. #endif
  724. }
  725. ~IoctlFriendlyTmpdir() {
  726. rmdir(dir_.c_str());
  727. }
  728. const std::string& name() const {
  729. return dir_;
  730. }
  731. private:
  732. std::string dir_;
  733. };
  734. #ifndef ROCKSDB_LITE
  735. TEST_F(EnvPosixTest, PositionedAppend) {
  736. std::unique_ptr<WritableFile> writable_file;
  737. EnvOptions options;
  738. options.use_direct_writes = true;
  739. options.use_mmap_writes = false;
  740. IoctlFriendlyTmpdir ift;
  741. ASSERT_OK(env_->NewWritableFile(ift.name() + "/f", &writable_file, options));
  742. const size_t kBlockSize = 4096;
  743. const size_t kDataSize = kPageSize;
  744. // Write a page worth of 'a'
  745. auto data_ptr = NewAligned(kDataSize, 'a');
  746. Slice data_a(data_ptr.get(), kDataSize);
  747. ASSERT_OK(writable_file->PositionedAppend(data_a, 0U));
  748. // Write a page worth of 'b' right after the first sector
  749. data_ptr = NewAligned(kDataSize, 'b');
  750. Slice data_b(data_ptr.get(), kDataSize);
  751. ASSERT_OK(writable_file->PositionedAppend(data_b, kBlockSize));
  752. ASSERT_OK(writable_file->Close());
  753. // The file now has 1 sector worth of a followed by a page worth of b
  754. // Verify the above
  755. std::unique_ptr<SequentialFile> seq_file;
  756. ASSERT_OK(env_->NewSequentialFile(ift.name() + "/f", &seq_file, options));
  757. size_t scratch_len = kPageSize * 2;
  758. std::unique_ptr<char[]> scratch(new char[scratch_len]);
  759. Slice result;
  760. ASSERT_OK(seq_file->Read(scratch_len, &result, scratch.get()));
  761. ASSERT_EQ(kPageSize + kBlockSize, result.size());
  762. ASSERT_EQ('a', result[kBlockSize - 1]);
  763. ASSERT_EQ('b', result[kBlockSize]);
  764. }
  765. #endif // !ROCKSDB_LITE
  766. // `GetUniqueId()` temporarily returns zero on Windows. `BlockBasedTable` can
  767. // handle a return value of zero but this test case cannot.
  768. #ifndef OS_WIN
  769. TEST_P(EnvPosixTestWithParam, RandomAccessUniqueID) {
  770. // Create file.
  771. if (env_ == Env::Default()) {
  772. EnvOptions soptions;
  773. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  774. IoctlFriendlyTmpdir ift;
  775. std::string fname = ift.name() + "/testfile";
  776. std::unique_ptr<WritableFile> wfile;
  777. ASSERT_OK(env_->NewWritableFile(fname, &wfile, soptions));
  778. std::unique_ptr<RandomAccessFile> file;
  779. // Get Unique ID
  780. ASSERT_OK(env_->NewRandomAccessFile(fname, &file, soptions));
  781. size_t id_size = file->GetUniqueId(temp_id, MAX_ID_SIZE);
  782. ASSERT_TRUE(id_size > 0);
  783. std::string unique_id1(temp_id, id_size);
  784. ASSERT_TRUE(IsUniqueIDValid(unique_id1));
  785. // Get Unique ID again
  786. ASSERT_OK(env_->NewRandomAccessFile(fname, &file, soptions));
  787. id_size = file->GetUniqueId(temp_id, MAX_ID_SIZE);
  788. ASSERT_TRUE(id_size > 0);
  789. std::string unique_id2(temp_id, id_size);
  790. ASSERT_TRUE(IsUniqueIDValid(unique_id2));
  791. // Get Unique ID again after waiting some time.
  792. env_->SleepForMicroseconds(1000000);
  793. ASSERT_OK(env_->NewRandomAccessFile(fname, &file, soptions));
  794. id_size = file->GetUniqueId(temp_id, MAX_ID_SIZE);
  795. ASSERT_TRUE(id_size > 0);
  796. std::string unique_id3(temp_id, id_size);
  797. ASSERT_TRUE(IsUniqueIDValid(unique_id3));
  798. // Check IDs are the same.
  799. ASSERT_EQ(unique_id1, unique_id2);
  800. ASSERT_EQ(unique_id2, unique_id3);
  801. // Delete the file
  802. env_->DeleteFile(fname);
  803. }
  804. }
  805. #endif // !defined(OS_WIN)
  806. // only works in linux platforms
  807. #ifdef ROCKSDB_FALLOCATE_PRESENT
  808. TEST_P(EnvPosixTestWithParam, AllocateTest) {
  809. if (env_ == Env::Default()) {
  810. IoctlFriendlyTmpdir ift;
  811. std::string fname = ift.name() + "/preallocate_testfile";
  812. // Try fallocate in a file to see whether the target file system supports
  813. // it.
  814. // Skip the test if fallocate is not supported.
  815. std::string fname_test_fallocate = ift.name() + "/preallocate_testfile_2";
  816. int fd = -1;
  817. do {
  818. fd = open(fname_test_fallocate.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0644);
  819. } while (fd < 0 && errno == EINTR);
  820. ASSERT_GT(fd, 0);
  821. int alloc_status = fallocate(fd, 0, 0, 1);
  822. int err_number = 0;
  823. if (alloc_status != 0) {
  824. err_number = errno;
  825. fprintf(stderr, "Warning: fallocate() fails, %s\n", strerror(err_number));
  826. }
  827. close(fd);
  828. ASSERT_OK(env_->DeleteFile(fname_test_fallocate));
  829. if (alloc_status != 0 && err_number == EOPNOTSUPP) {
  830. // The filesystem containing the file does not support fallocate
  831. return;
  832. }
  833. EnvOptions soptions;
  834. soptions.use_mmap_writes = false;
  835. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  836. std::unique_ptr<WritableFile> wfile;
  837. ASSERT_OK(env_->NewWritableFile(fname, &wfile, soptions));
  838. // allocate 100 MB
  839. size_t kPreallocateSize = 100 * 1024 * 1024;
  840. size_t kBlockSize = 512;
  841. size_t kDataSize = 1024 * 1024;
  842. auto data_ptr = NewAligned(kDataSize, 'A');
  843. Slice data(data_ptr.get(), kDataSize);
  844. wfile->SetPreallocationBlockSize(kPreallocateSize);
  845. wfile->PrepareWrite(wfile->GetFileSize(), kDataSize);
  846. ASSERT_OK(wfile->Append(data));
  847. ASSERT_OK(wfile->Flush());
  848. struct stat f_stat;
  849. ASSERT_EQ(stat(fname.c_str(), &f_stat), 0);
  850. ASSERT_EQ((unsigned int)kDataSize, f_stat.st_size);
  851. // verify that blocks are preallocated
  852. // Note here that we don't check the exact number of blocks preallocated --
  853. // we only require that number of allocated blocks is at least what we
  854. // expect.
  855. // It looks like some FS give us more blocks that we asked for. That's fine.
  856. // It might be worth investigating further.
  857. ASSERT_LE((unsigned int)(kPreallocateSize / kBlockSize), f_stat.st_blocks);
  858. // close the file, should deallocate the blocks
  859. wfile.reset();
  860. stat(fname.c_str(), &f_stat);
  861. ASSERT_EQ((unsigned int)kDataSize, f_stat.st_size);
  862. // verify that preallocated blocks were deallocated on file close
  863. // Because the FS might give us more blocks, we add a full page to the size
  864. // and expect the number of blocks to be less or equal to that.
  865. ASSERT_GE((f_stat.st_size + kPageSize + kBlockSize - 1) / kBlockSize,
  866. (unsigned int)f_stat.st_blocks);
  867. }
  868. }
  869. #endif // ROCKSDB_FALLOCATE_PRESENT
  870. // Returns true if any of the strings in ss are the prefix of another string.
  871. bool HasPrefix(const std::unordered_set<std::string>& ss) {
  872. for (const std::string& s: ss) {
  873. if (s.empty()) {
  874. return true;
  875. }
  876. for (size_t i = 1; i < s.size(); ++i) {
  877. if (ss.count(s.substr(0, i)) != 0) {
  878. return true;
  879. }
  880. }
  881. }
  882. return false;
  883. }
  884. // `GetUniqueId()` temporarily returns zero on Windows. `BlockBasedTable` can
  885. // handle a return value of zero but this test case cannot.
  886. #ifndef OS_WIN
  887. TEST_P(EnvPosixTestWithParam, RandomAccessUniqueIDConcurrent) {
  888. if (env_ == Env::Default()) {
  889. // Check whether a bunch of concurrently existing files have unique IDs.
  890. EnvOptions soptions;
  891. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  892. // Create the files
  893. IoctlFriendlyTmpdir ift;
  894. std::vector<std::string> fnames;
  895. for (int i = 0; i < 1000; ++i) {
  896. fnames.push_back(ift.name() + "/" + "testfile" + ToString(i));
  897. // Create file.
  898. std::unique_ptr<WritableFile> wfile;
  899. ASSERT_OK(env_->NewWritableFile(fnames[i], &wfile, soptions));
  900. }
  901. // Collect and check whether the IDs are unique.
  902. std::unordered_set<std::string> ids;
  903. for (const std::string fname : fnames) {
  904. std::unique_ptr<RandomAccessFile> file;
  905. std::string unique_id;
  906. ASSERT_OK(env_->NewRandomAccessFile(fname, &file, soptions));
  907. size_t id_size = file->GetUniqueId(temp_id, MAX_ID_SIZE);
  908. ASSERT_TRUE(id_size > 0);
  909. unique_id = std::string(temp_id, id_size);
  910. ASSERT_TRUE(IsUniqueIDValid(unique_id));
  911. ASSERT_TRUE(ids.count(unique_id) == 0);
  912. ids.insert(unique_id);
  913. }
  914. // Delete the files
  915. for (const std::string fname : fnames) {
  916. ASSERT_OK(env_->DeleteFile(fname));
  917. }
  918. ASSERT_TRUE(!HasPrefix(ids));
  919. }
  920. }
  921. TEST_P(EnvPosixTestWithParam, RandomAccessUniqueIDDeletes) {
  922. if (env_ == Env::Default()) {
  923. EnvOptions soptions;
  924. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  925. IoctlFriendlyTmpdir ift;
  926. std::string fname = ift.name() + "/" + "testfile";
  927. // Check that after file is deleted we don't get same ID again in a new
  928. // file.
  929. std::unordered_set<std::string> ids;
  930. for (int i = 0; i < 1000; ++i) {
  931. // Create file.
  932. {
  933. std::unique_ptr<WritableFile> wfile;
  934. ASSERT_OK(env_->NewWritableFile(fname, &wfile, soptions));
  935. }
  936. // Get Unique ID
  937. std::string unique_id;
  938. {
  939. std::unique_ptr<RandomAccessFile> file;
  940. ASSERT_OK(env_->NewRandomAccessFile(fname, &file, soptions));
  941. size_t id_size = file->GetUniqueId(temp_id, MAX_ID_SIZE);
  942. ASSERT_TRUE(id_size > 0);
  943. unique_id = std::string(temp_id, id_size);
  944. }
  945. ASSERT_TRUE(IsUniqueIDValid(unique_id));
  946. ASSERT_TRUE(ids.count(unique_id) == 0);
  947. ids.insert(unique_id);
  948. // Delete the file
  949. ASSERT_OK(env_->DeleteFile(fname));
  950. }
  951. ASSERT_TRUE(!HasPrefix(ids));
  952. }
  953. }
  954. #endif // !defined(OS_WIN)
  955. TEST_P(EnvPosixTestWithParam, MultiRead) {
  956. EnvOptions soptions;
  957. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  958. std::string fname = test::PerThreadDBPath(env_, "testfile");
  959. const size_t kSectorSize = 4096;
  960. const size_t kNumSectors = 8;
  961. // Create file.
  962. {
  963. std::unique_ptr<WritableFile> wfile;
  964. #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && \
  965. !defined(OS_AIX)
  966. if (soptions.use_direct_writes) {
  967. soptions.use_direct_writes = false;
  968. }
  969. #endif
  970. ASSERT_OK(env_->NewWritableFile(fname, &wfile, soptions));
  971. for (size_t i = 0; i < kNumSectors; ++i) {
  972. auto data = NewAligned(kSectorSize * 8, static_cast<char>(i + 1));
  973. Slice slice(data.get(), kSectorSize);
  974. ASSERT_OK(wfile->Append(slice));
  975. }
  976. ASSERT_OK(wfile->Close());
  977. }
  978. // More attempts to simulate more partial result sequences.
  979. for (uint32_t attempt = 0; attempt < 20; attempt++) {
  980. // Random Read
  981. Random rnd(301 + attempt);
  982. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  983. "PosixRandomAccessFile::MultiRead:io_uring_result", [&](void* arg) {
  984. if (attempt > 0) {
  985. // No failure in the first attempt.
  986. size_t& bytes_read = *static_cast<size_t*>(arg);
  987. if (rnd.OneIn(4)) {
  988. bytes_read = 0;
  989. } else if (rnd.OneIn(3)) {
  990. bytes_read = static_cast<size_t>(
  991. rnd.Uniform(static_cast<int>(bytes_read)));
  992. }
  993. }
  994. });
  995. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  996. std::unique_ptr<RandomAccessFile> file;
  997. std::vector<ReadRequest> reqs(3);
  998. std::vector<std::unique_ptr<char, Deleter>> data;
  999. uint64_t offset = 0;
  1000. for (size_t i = 0; i < reqs.size(); ++i) {
  1001. reqs[i].offset = offset;
  1002. offset += 2 * kSectorSize;
  1003. reqs[i].len = kSectorSize;
  1004. data.emplace_back(NewAligned(kSectorSize, 0));
  1005. reqs[i].scratch = data.back().get();
  1006. }
  1007. #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && \
  1008. !defined(OS_AIX)
  1009. if (soptions.use_direct_reads) {
  1010. soptions.use_direct_reads = false;
  1011. }
  1012. #endif
  1013. ASSERT_OK(env_->NewRandomAccessFile(fname, &file, soptions));
  1014. ASSERT_OK(file->MultiRead(reqs.data(), reqs.size()));
  1015. for (size_t i = 0; i < reqs.size(); ++i) {
  1016. auto buf = NewAligned(kSectorSize * 8, static_cast<char>(i * 2 + 1));
  1017. ASSERT_OK(reqs[i].status);
  1018. ASSERT_EQ(memcmp(reqs[i].scratch, buf.get(), kSectorSize), 0);
  1019. }
  1020. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1021. }
  1022. }
  1023. // Only works in linux platforms
  1024. #ifdef OS_WIN
  1025. TEST_P(EnvPosixTestWithParam, DISABLED_InvalidateCache) {
  1026. #else
  1027. TEST_P(EnvPosixTestWithParam, InvalidateCache) {
  1028. #endif
  1029. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1030. EnvOptions soptions;
  1031. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  1032. std::string fname = test::PerThreadDBPath(env_, "testfile");
  1033. const size_t kSectorSize = 512;
  1034. auto data = NewAligned(kSectorSize, 0);
  1035. Slice slice(data.get(), kSectorSize);
  1036. // Create file.
  1037. {
  1038. std::unique_ptr<WritableFile> wfile;
  1039. #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && !defined(OS_AIX)
  1040. if (soptions.use_direct_writes) {
  1041. soptions.use_direct_writes = false;
  1042. }
  1043. #endif
  1044. ASSERT_OK(env_->NewWritableFile(fname, &wfile, soptions));
  1045. ASSERT_OK(wfile->Append(slice));
  1046. ASSERT_OK(wfile->InvalidateCache(0, 0));
  1047. ASSERT_OK(wfile->Close());
  1048. }
  1049. // Random Read
  1050. {
  1051. std::unique_ptr<RandomAccessFile> file;
  1052. auto scratch = NewAligned(kSectorSize, 0);
  1053. Slice result;
  1054. #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && !defined(OS_AIX)
  1055. if (soptions.use_direct_reads) {
  1056. soptions.use_direct_reads = false;
  1057. }
  1058. #endif
  1059. ASSERT_OK(env_->NewRandomAccessFile(fname, &file, soptions));
  1060. ASSERT_OK(file->Read(0, kSectorSize, &result, scratch.get()));
  1061. ASSERT_EQ(memcmp(scratch.get(), data.get(), kSectorSize), 0);
  1062. ASSERT_OK(file->InvalidateCache(0, 11));
  1063. ASSERT_OK(file->InvalidateCache(0, 0));
  1064. }
  1065. // Sequential Read
  1066. {
  1067. std::unique_ptr<SequentialFile> file;
  1068. auto scratch = NewAligned(kSectorSize, 0);
  1069. Slice result;
  1070. #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && !defined(OS_AIX)
  1071. if (soptions.use_direct_reads) {
  1072. soptions.use_direct_reads = false;
  1073. }
  1074. #endif
  1075. ASSERT_OK(env_->NewSequentialFile(fname, &file, soptions));
  1076. if (file->use_direct_io()) {
  1077. ASSERT_OK(file->PositionedRead(0, kSectorSize, &result, scratch.get()));
  1078. } else {
  1079. ASSERT_OK(file->Read(kSectorSize, &result, scratch.get()));
  1080. }
  1081. ASSERT_EQ(memcmp(scratch.get(), data.get(), kSectorSize), 0);
  1082. ASSERT_OK(file->InvalidateCache(0, 11));
  1083. ASSERT_OK(file->InvalidateCache(0, 0));
  1084. }
  1085. // Delete the file
  1086. ASSERT_OK(env_->DeleteFile(fname));
  1087. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
  1088. }
  1089. #endif // not TRAVIS
  1090. #endif // OS_LINUX || OS_WIN
  1091. class TestLogger : public Logger {
  1092. public:
  1093. using Logger::Logv;
  1094. void Logv(const char* format, va_list ap) override {
  1095. log_count++;
  1096. char new_format[550];
  1097. std::fill_n(new_format, sizeof(new_format), '2');
  1098. {
  1099. va_list backup_ap;
  1100. va_copy(backup_ap, ap);
  1101. int n = vsnprintf(new_format, sizeof(new_format) - 1, format, backup_ap);
  1102. // 48 bytes for extra information + bytes allocated
  1103. // When we have n == -1 there is not a terminating zero expected
  1104. #ifdef OS_WIN
  1105. if (n < 0) {
  1106. char_0_count++;
  1107. }
  1108. #endif
  1109. if (new_format[0] == '[') {
  1110. // "[DEBUG] "
  1111. ASSERT_TRUE(n <= 56 + (512 - static_cast<int>(sizeof(struct timeval))));
  1112. } else {
  1113. ASSERT_TRUE(n <= 48 + (512 - static_cast<int>(sizeof(struct timeval))));
  1114. }
  1115. va_end(backup_ap);
  1116. }
  1117. for (size_t i = 0; i < sizeof(new_format); i++) {
  1118. if (new_format[i] == 'x') {
  1119. char_x_count++;
  1120. } else if (new_format[i] == '\0') {
  1121. char_0_count++;
  1122. }
  1123. }
  1124. }
  1125. int log_count;
  1126. int char_x_count;
  1127. int char_0_count;
  1128. };
  1129. TEST_P(EnvPosixTestWithParam, LogBufferTest) {
  1130. TestLogger test_logger;
  1131. test_logger.SetInfoLogLevel(InfoLogLevel::INFO_LEVEL);
  1132. test_logger.log_count = 0;
  1133. test_logger.char_x_count = 0;
  1134. test_logger.char_0_count = 0;
  1135. LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL, &test_logger);
  1136. LogBuffer log_buffer_debug(DEBUG_LEVEL, &test_logger);
  1137. char bytes200[200];
  1138. std::fill_n(bytes200, sizeof(bytes200), '1');
  1139. bytes200[sizeof(bytes200) - 1] = '\0';
  1140. char bytes600[600];
  1141. std::fill_n(bytes600, sizeof(bytes600), '1');
  1142. bytes600[sizeof(bytes600) - 1] = '\0';
  1143. char bytes9000[9000];
  1144. std::fill_n(bytes9000, sizeof(bytes9000), '1');
  1145. bytes9000[sizeof(bytes9000) - 1] = '\0';
  1146. ROCKS_LOG_BUFFER(&log_buffer, "x%sx", bytes200);
  1147. ROCKS_LOG_BUFFER(&log_buffer, "x%sx", bytes600);
  1148. ROCKS_LOG_BUFFER(&log_buffer, "x%sx%sx%sx", bytes200, bytes200, bytes200);
  1149. ROCKS_LOG_BUFFER(&log_buffer, "x%sx%sx", bytes200, bytes600);
  1150. ROCKS_LOG_BUFFER(&log_buffer, "x%sx%sx", bytes600, bytes9000);
  1151. ROCKS_LOG_BUFFER(&log_buffer_debug, "x%sx", bytes200);
  1152. test_logger.SetInfoLogLevel(DEBUG_LEVEL);
  1153. ROCKS_LOG_BUFFER(&log_buffer_debug, "x%sx%sx%sx", bytes600, bytes9000,
  1154. bytes200);
  1155. ASSERT_EQ(0, test_logger.log_count);
  1156. log_buffer.FlushBufferToLog();
  1157. log_buffer_debug.FlushBufferToLog();
  1158. ASSERT_EQ(6, test_logger.log_count);
  1159. ASSERT_EQ(6, test_logger.char_0_count);
  1160. ASSERT_EQ(10, test_logger.char_x_count);
  1161. }
  1162. class TestLogger2 : public Logger {
  1163. public:
  1164. explicit TestLogger2(size_t max_log_size) : max_log_size_(max_log_size) {}
  1165. using Logger::Logv;
  1166. void Logv(const char* format, va_list ap) override {
  1167. char new_format[2000];
  1168. std::fill_n(new_format, sizeof(new_format), '2');
  1169. {
  1170. va_list backup_ap;
  1171. va_copy(backup_ap, ap);
  1172. int n = vsnprintf(new_format, sizeof(new_format) - 1, format, backup_ap);
  1173. // 48 bytes for extra information + bytes allocated
  1174. ASSERT_TRUE(
  1175. n <= 48 + static_cast<int>(max_log_size_ - sizeof(struct timeval)));
  1176. ASSERT_TRUE(n > static_cast<int>(max_log_size_ - sizeof(struct timeval)));
  1177. va_end(backup_ap);
  1178. }
  1179. }
  1180. size_t max_log_size_;
  1181. };
  1182. TEST_P(EnvPosixTestWithParam, LogBufferMaxSizeTest) {
  1183. char bytes9000[9000];
  1184. std::fill_n(bytes9000, sizeof(bytes9000), '1');
  1185. bytes9000[sizeof(bytes9000) - 1] = '\0';
  1186. for (size_t max_log_size = 256; max_log_size <= 1024;
  1187. max_log_size += 1024 - 256) {
  1188. TestLogger2 test_logger(max_log_size);
  1189. test_logger.SetInfoLogLevel(InfoLogLevel::INFO_LEVEL);
  1190. LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL, &test_logger);
  1191. ROCKS_LOG_BUFFER_MAX_SZ(&log_buffer, max_log_size, "%s", bytes9000);
  1192. log_buffer.FlushBufferToLog();
  1193. }
  1194. }
  1195. TEST_P(EnvPosixTestWithParam, Preallocation) {
  1196. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1197. const std::string src = test::PerThreadDBPath(env_, "testfile");
  1198. std::unique_ptr<WritableFile> srcfile;
  1199. EnvOptions soptions;
  1200. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  1201. #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && !defined(OS_AIX) && !defined(OS_OPENBSD) && !defined(OS_FREEBSD)
  1202. if (soptions.use_direct_writes) {
  1203. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1204. "NewWritableFile:O_DIRECT", [&](void* arg) {
  1205. int* val = static_cast<int*>(arg);
  1206. *val &= ~O_DIRECT;
  1207. });
  1208. }
  1209. #endif
  1210. ASSERT_OK(env_->NewWritableFile(src, &srcfile, soptions));
  1211. srcfile->SetPreallocationBlockSize(1024 * 1024);
  1212. // No writes should mean no preallocation
  1213. size_t block_size, last_allocated_block;
  1214. srcfile->GetPreallocationStatus(&block_size, &last_allocated_block);
  1215. ASSERT_EQ(last_allocated_block, 0UL);
  1216. // Small write should preallocate one block
  1217. size_t kStrSize = 4096;
  1218. auto data = NewAligned(kStrSize, 'A');
  1219. Slice str(data.get(), kStrSize);
  1220. srcfile->PrepareWrite(srcfile->GetFileSize(), kStrSize);
  1221. srcfile->Append(str);
  1222. srcfile->GetPreallocationStatus(&block_size, &last_allocated_block);
  1223. ASSERT_EQ(last_allocated_block, 1UL);
  1224. // Write an entire preallocation block, make sure we increased by two.
  1225. {
  1226. auto buf_ptr = NewAligned(block_size, ' ');
  1227. Slice buf(buf_ptr.get(), block_size);
  1228. srcfile->PrepareWrite(srcfile->GetFileSize(), block_size);
  1229. srcfile->Append(buf);
  1230. srcfile->GetPreallocationStatus(&block_size, &last_allocated_block);
  1231. ASSERT_EQ(last_allocated_block, 2UL);
  1232. }
  1233. // Write five more blocks at once, ensure we're where we need to be.
  1234. {
  1235. auto buf_ptr = NewAligned(block_size * 5, ' ');
  1236. Slice buf = Slice(buf_ptr.get(), block_size * 5);
  1237. srcfile->PrepareWrite(srcfile->GetFileSize(), buf.size());
  1238. srcfile->Append(buf);
  1239. srcfile->GetPreallocationStatus(&block_size, &last_allocated_block);
  1240. ASSERT_EQ(last_allocated_block, 7UL);
  1241. }
  1242. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
  1243. }
  1244. // Test that the two ways to get children file attributes (in bulk or
  1245. // individually) behave consistently.
  1246. TEST_P(EnvPosixTestWithParam, ConsistentChildrenAttributes) {
  1247. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1248. EnvOptions soptions;
  1249. soptions.use_direct_reads = soptions.use_direct_writes = direct_io_;
  1250. const int kNumChildren = 10;
  1251. std::string data;
  1252. for (int i = 0; i < kNumChildren; ++i) {
  1253. const std::string path =
  1254. test::TmpDir(env_) + "/" + "testfile_" + std::to_string(i);
  1255. std::unique_ptr<WritableFile> file;
  1256. #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_SOLARIS) && !defined(OS_AIX) && !defined(OS_OPENBSD) && !defined(OS_FREEBSD)
  1257. if (soptions.use_direct_writes) {
  1258. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1259. "NewWritableFile:O_DIRECT", [&](void* arg) {
  1260. int* val = static_cast<int*>(arg);
  1261. *val &= ~O_DIRECT;
  1262. });
  1263. }
  1264. #endif
  1265. ASSERT_OK(env_->NewWritableFile(path, &file, soptions));
  1266. auto buf_ptr = NewAligned(data.size(), 'T');
  1267. Slice buf(buf_ptr.get(), data.size());
  1268. file->Append(buf);
  1269. data.append(std::string(4096, 'T'));
  1270. }
  1271. std::vector<Env::FileAttributes> file_attrs;
  1272. ASSERT_OK(env_->GetChildrenFileAttributes(test::TmpDir(env_), &file_attrs));
  1273. for (int i = 0; i < kNumChildren; ++i) {
  1274. const std::string name = "testfile_" + std::to_string(i);
  1275. const std::string path = test::TmpDir(env_) + "/" + name;
  1276. auto file_attrs_iter = std::find_if(
  1277. file_attrs.begin(), file_attrs.end(),
  1278. [&name](const Env::FileAttributes& fm) { return fm.name == name; });
  1279. ASSERT_TRUE(file_attrs_iter != file_attrs.end());
  1280. uint64_t size;
  1281. ASSERT_OK(env_->GetFileSize(path, &size));
  1282. ASSERT_EQ(size, 4096 * i);
  1283. ASSERT_EQ(size, file_attrs_iter->size_bytes);
  1284. }
  1285. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
  1286. }
  1287. // Test that all WritableFileWrapper forwards all calls to WritableFile.
  1288. TEST_P(EnvPosixTestWithParam, WritableFileWrapper) {
  1289. class Base : public WritableFile {
  1290. public:
  1291. mutable int *step_;
  1292. void inc(int x) const {
  1293. EXPECT_EQ(x, (*step_)++);
  1294. }
  1295. explicit Base(int* step) : step_(step) {
  1296. inc(0);
  1297. }
  1298. Status Append(const Slice& /*data*/) override {
  1299. inc(1);
  1300. return Status::OK();
  1301. }
  1302. Status PositionedAppend(const Slice& /*data*/,
  1303. uint64_t /*offset*/) override {
  1304. inc(2);
  1305. return Status::OK();
  1306. }
  1307. Status Truncate(uint64_t /*size*/) override {
  1308. inc(3);
  1309. return Status::OK();
  1310. }
  1311. Status Close() override {
  1312. inc(4);
  1313. return Status::OK();
  1314. }
  1315. Status Flush() override {
  1316. inc(5);
  1317. return Status::OK();
  1318. }
  1319. Status Sync() override {
  1320. inc(6);
  1321. return Status::OK();
  1322. }
  1323. Status Fsync() override {
  1324. inc(7);
  1325. return Status::OK();
  1326. }
  1327. bool IsSyncThreadSafe() const override {
  1328. inc(8);
  1329. return true;
  1330. }
  1331. bool use_direct_io() const override {
  1332. inc(9);
  1333. return true;
  1334. }
  1335. size_t GetRequiredBufferAlignment() const override {
  1336. inc(10);
  1337. return 0;
  1338. }
  1339. void SetIOPriority(Env::IOPriority /*pri*/) override { inc(11); }
  1340. Env::IOPriority GetIOPriority() override {
  1341. inc(12);
  1342. return Env::IOPriority::IO_LOW;
  1343. }
  1344. void SetWriteLifeTimeHint(Env::WriteLifeTimeHint /*hint*/) override {
  1345. inc(13);
  1346. }
  1347. Env::WriteLifeTimeHint GetWriteLifeTimeHint() override {
  1348. inc(14);
  1349. return Env::WriteLifeTimeHint::WLTH_NOT_SET;
  1350. }
  1351. uint64_t GetFileSize() override {
  1352. inc(15);
  1353. return 0;
  1354. }
  1355. void SetPreallocationBlockSize(size_t /*size*/) override { inc(16); }
  1356. void GetPreallocationStatus(size_t* /*block_size*/,
  1357. size_t* /*last_allocated_block*/) override {
  1358. inc(17);
  1359. }
  1360. size_t GetUniqueId(char* /*id*/, size_t /*max_size*/) const override {
  1361. inc(18);
  1362. return 0;
  1363. }
  1364. Status InvalidateCache(size_t /*offset*/, size_t /*length*/) override {
  1365. inc(19);
  1366. return Status::OK();
  1367. }
  1368. Status RangeSync(uint64_t /*offset*/, uint64_t /*nbytes*/) override {
  1369. inc(20);
  1370. return Status::OK();
  1371. }
  1372. void PrepareWrite(size_t /*offset*/, size_t /*len*/) override { inc(21); }
  1373. Status Allocate(uint64_t /*offset*/, uint64_t /*len*/) override {
  1374. inc(22);
  1375. return Status::OK();
  1376. }
  1377. public:
  1378. ~Base() override { inc(23); }
  1379. };
  1380. class Wrapper : public WritableFileWrapper {
  1381. public:
  1382. explicit Wrapper(WritableFile* target) : WritableFileWrapper(target) {}
  1383. };
  1384. int step = 0;
  1385. {
  1386. Base b(&step);
  1387. Wrapper w(&b);
  1388. w.Append(Slice());
  1389. w.PositionedAppend(Slice(), 0);
  1390. w.Truncate(0);
  1391. w.Close();
  1392. w.Flush();
  1393. w.Sync();
  1394. w.Fsync();
  1395. w.IsSyncThreadSafe();
  1396. w.use_direct_io();
  1397. w.GetRequiredBufferAlignment();
  1398. w.SetIOPriority(Env::IOPriority::IO_HIGH);
  1399. w.GetIOPriority();
  1400. w.SetWriteLifeTimeHint(Env::WriteLifeTimeHint::WLTH_NOT_SET);
  1401. w.GetWriteLifeTimeHint();
  1402. w.GetFileSize();
  1403. w.SetPreallocationBlockSize(0);
  1404. w.GetPreallocationStatus(nullptr, nullptr);
  1405. w.GetUniqueId(nullptr, 0);
  1406. w.InvalidateCache(0, 0);
  1407. w.RangeSync(0, 0);
  1408. w.PrepareWrite(0, 0);
  1409. w.Allocate(0, 0);
  1410. }
  1411. EXPECT_EQ(24, step);
  1412. }
  1413. TEST_P(EnvPosixTestWithParam, PosixRandomRWFile) {
  1414. const std::string path = test::PerThreadDBPath(env_, "random_rw_file");
  1415. env_->DeleteFile(path);
  1416. std::unique_ptr<RandomRWFile> file;
  1417. // Cannot open non-existing file.
  1418. ASSERT_NOK(env_->NewRandomRWFile(path, &file, EnvOptions()));
  1419. // Create the file using WriteableFile
  1420. {
  1421. std::unique_ptr<WritableFile> wf;
  1422. ASSERT_OK(env_->NewWritableFile(path, &wf, EnvOptions()));
  1423. }
  1424. ASSERT_OK(env_->NewRandomRWFile(path, &file, EnvOptions()));
  1425. char buf[10000];
  1426. Slice read_res;
  1427. ASSERT_OK(file->Write(0, "ABCD"));
  1428. ASSERT_OK(file->Read(0, 10, &read_res, buf));
  1429. ASSERT_EQ(read_res.ToString(), "ABCD");
  1430. ASSERT_OK(file->Write(2, "XXXX"));
  1431. ASSERT_OK(file->Read(0, 10, &read_res, buf));
  1432. ASSERT_EQ(read_res.ToString(), "ABXXXX");
  1433. ASSERT_OK(file->Write(10, "ZZZ"));
  1434. ASSERT_OK(file->Read(10, 10, &read_res, buf));
  1435. ASSERT_EQ(read_res.ToString(), "ZZZ");
  1436. ASSERT_OK(file->Write(11, "Y"));
  1437. ASSERT_OK(file->Read(10, 10, &read_res, buf));
  1438. ASSERT_EQ(read_res.ToString(), "ZYZ");
  1439. ASSERT_OK(file->Write(200, "FFFFF"));
  1440. ASSERT_OK(file->Read(200, 10, &read_res, buf));
  1441. ASSERT_EQ(read_res.ToString(), "FFFFF");
  1442. ASSERT_OK(file->Write(205, "XXXX"));
  1443. ASSERT_OK(file->Read(200, 10, &read_res, buf));
  1444. ASSERT_EQ(read_res.ToString(), "FFFFFXXXX");
  1445. ASSERT_OK(file->Write(5, "QQQQ"));
  1446. ASSERT_OK(file->Read(0, 9, &read_res, buf));
  1447. ASSERT_EQ(read_res.ToString(), "ABXXXQQQQ");
  1448. ASSERT_OK(file->Read(2, 4, &read_res, buf));
  1449. ASSERT_EQ(read_res.ToString(), "XXXQ");
  1450. // Close file and reopen it
  1451. file->Close();
  1452. ASSERT_OK(env_->NewRandomRWFile(path, &file, EnvOptions()));
  1453. ASSERT_OK(file->Read(0, 9, &read_res, buf));
  1454. ASSERT_EQ(read_res.ToString(), "ABXXXQQQQ");
  1455. ASSERT_OK(file->Read(10, 3, &read_res, buf));
  1456. ASSERT_EQ(read_res.ToString(), "ZYZ");
  1457. ASSERT_OK(file->Read(200, 9, &read_res, buf));
  1458. ASSERT_EQ(read_res.ToString(), "FFFFFXXXX");
  1459. ASSERT_OK(file->Write(4, "TTTTTTTTTTTTTTTT"));
  1460. ASSERT_OK(file->Read(0, 10, &read_res, buf));
  1461. ASSERT_EQ(read_res.ToString(), "ABXXTTTTTT");
  1462. // Clean up
  1463. env_->DeleteFile(path);
  1464. }
  1465. class RandomRWFileWithMirrorString {
  1466. public:
  1467. explicit RandomRWFileWithMirrorString(RandomRWFile* _file) : file_(_file) {}
  1468. void Write(size_t offset, const std::string& data) {
  1469. // Write to mirror string
  1470. StringWrite(offset, data);
  1471. // Write to file
  1472. Status s = file_->Write(offset, data);
  1473. ASSERT_OK(s) << s.ToString();
  1474. }
  1475. void Read(size_t offset = 0, size_t n = 1000000) {
  1476. Slice str_res(nullptr, 0);
  1477. if (offset < file_mirror_.size()) {
  1478. size_t str_res_sz = std::min(file_mirror_.size() - offset, n);
  1479. str_res = Slice(file_mirror_.data() + offset, str_res_sz);
  1480. StopSliceAtNull(&str_res);
  1481. }
  1482. Slice file_res;
  1483. Status s = file_->Read(offset, n, &file_res, buf_);
  1484. ASSERT_OK(s) << s.ToString();
  1485. StopSliceAtNull(&file_res);
  1486. ASSERT_EQ(str_res.ToString(), file_res.ToString()) << offset << " " << n;
  1487. }
  1488. void SetFile(RandomRWFile* _file) { file_ = _file; }
  1489. private:
  1490. void StringWrite(size_t offset, const std::string& src) {
  1491. if (offset + src.size() > file_mirror_.size()) {
  1492. file_mirror_.resize(offset + src.size(), '\0');
  1493. }
  1494. char* pos = const_cast<char*>(file_mirror_.data() + offset);
  1495. memcpy(pos, src.data(), src.size());
  1496. }
  1497. void StopSliceAtNull(Slice* slc) {
  1498. for (size_t i = 0; i < slc->size(); i++) {
  1499. if ((*slc)[i] == '\0') {
  1500. *slc = Slice(slc->data(), i);
  1501. break;
  1502. }
  1503. }
  1504. }
  1505. char buf_[10000];
  1506. RandomRWFile* file_;
  1507. std::string file_mirror_;
  1508. };
  1509. TEST_P(EnvPosixTestWithParam, PosixRandomRWFileRandomized) {
  1510. const std::string path = test::PerThreadDBPath(env_, "random_rw_file_rand");
  1511. env_->DeleteFile(path);
  1512. std::unique_ptr<RandomRWFile> file;
  1513. #ifdef OS_LINUX
  1514. // Cannot open non-existing file.
  1515. ASSERT_NOK(env_->NewRandomRWFile(path, &file, EnvOptions()));
  1516. #endif
  1517. // Create the file using WriteableFile
  1518. {
  1519. std::unique_ptr<WritableFile> wf;
  1520. ASSERT_OK(env_->NewWritableFile(path, &wf, EnvOptions()));
  1521. }
  1522. ASSERT_OK(env_->NewRandomRWFile(path, &file, EnvOptions()));
  1523. RandomRWFileWithMirrorString file_with_mirror(file.get());
  1524. Random rnd(301);
  1525. std::string buf;
  1526. for (int i = 0; i < 10000; i++) {
  1527. // Genrate random data
  1528. test::RandomString(&rnd, 10, &buf);
  1529. // Pick random offset for write
  1530. size_t write_off = rnd.Next() % 1000;
  1531. file_with_mirror.Write(write_off, buf);
  1532. // Pick random offset for read
  1533. size_t read_off = rnd.Next() % 1000;
  1534. size_t read_sz = rnd.Next() % 20;
  1535. file_with_mirror.Read(read_off, read_sz);
  1536. if (i % 500 == 0) {
  1537. // Reopen the file every 500 iters
  1538. ASSERT_OK(env_->NewRandomRWFile(path, &file, EnvOptions()));
  1539. file_with_mirror.SetFile(file.get());
  1540. }
  1541. }
  1542. // clean up
  1543. env_->DeleteFile(path);
  1544. }
  1545. class TestEnv : public EnvWrapper {
  1546. public:
  1547. explicit TestEnv() : EnvWrapper(Env::Default()),
  1548. close_count(0) { }
  1549. class TestLogger : public Logger {
  1550. public:
  1551. using Logger::Logv;
  1552. TestLogger(TestEnv* env_ptr) : Logger() { env = env_ptr; }
  1553. ~TestLogger() override {
  1554. if (!closed_) {
  1555. CloseHelper();
  1556. }
  1557. }
  1558. void Logv(const char* /*format*/, va_list /*ap*/) override{};
  1559. protected:
  1560. Status CloseImpl() override { return CloseHelper(); }
  1561. private:
  1562. Status CloseHelper() {
  1563. env->CloseCountInc();;
  1564. return Status::OK();
  1565. }
  1566. TestEnv* env;
  1567. };
  1568. void CloseCountInc() { close_count++; }
  1569. int GetCloseCount() { return close_count; }
  1570. Status NewLogger(const std::string& /*fname*/,
  1571. std::shared_ptr<Logger>* result) override {
  1572. result->reset(new TestLogger(this));
  1573. return Status::OK();
  1574. }
  1575. private:
  1576. int close_count;
  1577. };
  1578. class EnvTest : public testing::Test {};
  1579. TEST_F(EnvTest, Close) {
  1580. TestEnv* env = new TestEnv();
  1581. std::shared_ptr<Logger> logger;
  1582. Status s;
  1583. s = env->NewLogger("", &logger);
  1584. ASSERT_EQ(s, Status::OK());
  1585. logger.get()->Close();
  1586. ASSERT_EQ(env->GetCloseCount(), 1);
  1587. // Call Close() again. CloseHelper() should not be called again
  1588. logger.get()->Close();
  1589. ASSERT_EQ(env->GetCloseCount(), 1);
  1590. logger.reset();
  1591. ASSERT_EQ(env->GetCloseCount(), 1);
  1592. s = env->NewLogger("", &logger);
  1593. ASSERT_EQ(s, Status::OK());
  1594. logger.reset();
  1595. ASSERT_EQ(env->GetCloseCount(), 2);
  1596. delete env;
  1597. }
  1598. INSTANTIATE_TEST_CASE_P(DefaultEnvWithoutDirectIO, EnvPosixTestWithParam,
  1599. ::testing::Values(std::pair<Env*, bool>(Env::Default(),
  1600. false)));
  1601. #if !defined(ROCKSDB_LITE)
  1602. INSTANTIATE_TEST_CASE_P(DefaultEnvWithDirectIO, EnvPosixTestWithParam,
  1603. ::testing::Values(std::pair<Env*, bool>(Env::Default(),
  1604. true)));
  1605. #endif // !defined(ROCKSDB_LITE)
  1606. #if !defined(ROCKSDB_LITE) && !defined(OS_WIN)
  1607. static std::unique_ptr<Env> chroot_env(
  1608. NewChrootEnv(Env::Default(), test::TmpDir(Env::Default())));
  1609. INSTANTIATE_TEST_CASE_P(
  1610. ChrootEnvWithoutDirectIO, EnvPosixTestWithParam,
  1611. ::testing::Values(std::pair<Env*, bool>(chroot_env.get(), false)));
  1612. INSTANTIATE_TEST_CASE_P(
  1613. ChrootEnvWithDirectIO, EnvPosixTestWithParam,
  1614. ::testing::Values(std::pair<Env*, bool>(chroot_env.get(), true)));
  1615. #endif // !defined(ROCKSDB_LITE) && !defined(OS_WIN)
  1616. } // namespace ROCKSDB_NAMESPACE
  1617. int main(int argc, char** argv) {
  1618. ::testing::InitGoogleTest(&argc, argv);
  1619. return RUN_ALL_TESTS();
  1620. }