]>
git.proxmox.com Git - ceph.git/blob - ceph/src/rocksdb/util/filelock_test.cc
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).
6 #include "rocksdb/status.h"
7 #include "rocksdb/env.h"
11 #include "util/coding.h"
12 #include "util/testharness.h"
16 class LockTest
: public testing::Test
{
18 static LockTest
* current_
;
23 : file_(test::PerThreadDBPath("db_testlock_file")),
24 env_(rocksdb::Env::Default()) {
28 ~LockTest() override
{}
30 Status
LockFile(FileLock
** db_lock
) {
31 return env_
->LockFile(file_
, db_lock
);
34 Status
UnlockFile(FileLock
* db_lock
) {
35 return env_
->UnlockFile(db_lock
);
38 bool AssertFileIsLocked(){
39 return CheckFileLock( /* lock_expected = */ true);
42 bool AssertFileIsNotLocked(){
43 return CheckFileLock( /* lock_expected = */ false);
46 bool CheckFileLock(bool lock_expected
){
47 // We need to fork to check the fcntl lock as we need
48 // to open and close the file from a different process
49 // to avoid either releasing the lock on close, or not
50 // contending for it when requesting a lock.
54 // WaitForSingleObject and GetExitCodeProcess can do what waitpid does.
55 // TODO - implement on Windows
63 int exit_val
= EXIT_FAILURE
;
64 int fd
= open(file_
.c_str(), O_RDWR
| O_CREAT
, 0644);
66 // could not open file, could not check if it was locked
67 fprintf( stderr
, "Open on on file %s failed.\n",file_
.c_str());
72 memset(&f
, 0, sizeof(f
));
74 f
.l_whence
= SEEK_SET
;
76 f
.l_len
= 0; // Lock/unlock entire file
77 int value
= fcntl(fd
, F_SETLK
, &f
);
80 exit_val
= EXIT_SUCCESS
;
83 if( ! lock_expected
){
84 exit_val
= EXIT_SUCCESS
;
87 close(fd
); // lock is released for child process
92 while (-1 == waitpid(pid
, &status
, 0));
93 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
94 // child process exited with non success status
100 fprintf( stderr
, "Fork failed\n" );
110 LockTest
* LockTest::current_
;
112 TEST_F(LockTest
, LockBySameThread
) {
116 // acquire a lock on a file
117 ASSERT_OK(LockFile(&lock1
));
119 // check the file is locked
120 ASSERT_TRUE( AssertFileIsLocked() );
122 // re-acquire the lock on the same file. This should fail.
123 ASSERT_TRUE(LockFile(&lock2
).IsIOError());
125 // check the file is locked
126 ASSERT_TRUE( AssertFileIsLocked() );
129 ASSERT_OK(UnlockFile(lock1
));
131 // check the file is not locked
132 ASSERT_TRUE( AssertFileIsNotLocked() );
136 } // namespace rocksdb
138 int main(int argc
, char** argv
) {
139 ::testing::InitGoogleTest(&argc
, argv
);
140 return RUN_ALL_TESTS();