robust_emulation.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2010-2012. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/interprocess for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. #ifndef BOOST_INTERPROCESS_ROBUST_EMULATION_HPP
  11. #define BOOST_INTERPROCESS_ROBUST_EMULATION_HPP
  12. #if defined(_MSC_VER)&&(_MSC_VER>=1200)
  13. #pragma once
  14. #endif
  15. #include <boost/interprocess/detail/config_begin.hpp>
  16. #include <boost/interprocess/detail/workaround.hpp>
  17. #include <boost/interprocess/sync/interprocess_mutex.hpp>
  18. #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
  19. #include <boost/interprocess/detail/atomic.hpp>
  20. #include <boost/interprocess/detail/os_file_functions.hpp>
  21. #include <boost/interprocess/detail/tmp_dir_helpers.hpp>
  22. #include <boost/interprocess/detail/intermodule_singleton.hpp>
  23. #include <boost/interprocess/exceptions.hpp>
  24. #include <string>
  25. namespace boost{
  26. namespace interprocess{
  27. namespace ipcdetail{
  28. namespace robust_emulation_helpers {
  29. template<class T>
  30. class mutex_traits
  31. {
  32. public:
  33. static void take_ownership(T &t)
  34. { t.take_ownership(); }
  35. };
  36. inline void remove_if_can_lock_file(const char *file_path)
  37. {
  38. file_handle_t fhnd = open_existing_file(file_path, read_write);
  39. if(fhnd != invalid_file()){
  40. bool acquired;
  41. if(try_acquire_file_lock(fhnd, acquired) && acquired){
  42. delete_file(file_path);
  43. }
  44. close_file(fhnd);
  45. }
  46. }
  47. inline const char *robust_lock_subdir_path()
  48. { return "robust"; }
  49. inline const char *robust_lock_prefix()
  50. { return "lck"; }
  51. inline void robust_lock_path(std::string &s)
  52. {
  53. tmp_folder(s);
  54. s += "/";
  55. s += robust_lock_subdir_path();
  56. }
  57. inline void create_and_get_robust_lock_file_path(std::string &s, OS_process_id_t pid)
  58. {
  59. intermodule_singleton_helpers::create_tmp_subdir_and_get_pid_based_filepath
  60. (robust_lock_subdir_path(), robust_lock_prefix(), pid, s);
  61. }
  62. //This class will be a intermodule_singleton. The constructor will create
  63. //a lock file, the destructor will erase it.
  64. //
  65. //We should take in care that another process might be erasing unlocked
  66. //files while creating this one, so there are some race conditions we must
  67. //take in care to guarantee some robustness.
  68. class robust_mutex_lock_file
  69. {
  70. file_handle_t fd;
  71. std::string fname;
  72. public:
  73. robust_mutex_lock_file()
  74. {
  75. permissions p;
  76. p.set_unrestricted();
  77. //Remove old lock files of other processes
  78. remove_old_robust_lock_files();
  79. //Create path and obtain lock file path for this process
  80. create_and_get_robust_lock_file_path(fname, get_current_process_id());
  81. //Now try to open or create the lock file
  82. fd = create_or_open_file(fname.c_str(), read_write, p);
  83. //If we can't open or create it, then something unrecoverable has happened
  84. if(fd == invalid_file()){
  85. throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: could not open or create file");
  86. }
  87. //Now we must take in care a race condition with another process
  88. //calling "remove_old_robust_lock_files()". No other threads from this
  89. //process will be creating the lock file because intermodule_singleton
  90. //guarantees this. So let's loop acquiring the lock and checking if we
  91. //can't exclusively create the file (if the file is erased by another process
  92. //then this exclusive open would fail). If the file can't be exclusively created
  93. //then we have correctly open/create and lock the file. If the file can
  94. //be exclusively created, then close previous locked file and try again.
  95. while(1){
  96. bool acquired;
  97. if(!try_acquire_file_lock(fd, acquired) || !acquired ){
  98. throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: try_acquire_file_lock");
  99. }
  100. //Creating exclusively must fail with already_exists_error
  101. //to make sure we've locked the file and no one has
  102. //deleted it between creation and locking
  103. file_handle_t fd2 = create_new_file(fname.c_str(), read_write, p);
  104. if(fd2 != invalid_file()){
  105. close_file(fd);
  106. fd = fd2;
  107. continue;
  108. }
  109. //If exclusive creation fails with expected error go ahead
  110. else if(error_info(system_error_code()).get_error_code() == already_exists_error){ //must already exist
  111. //Leak descriptor to mantain the file locked until the process dies
  112. break;
  113. }
  114. //If exclusive creation fails with unexpected error throw an unrecoverable error
  115. else{
  116. close_file(fd);
  117. throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: create_file filed with unexpected error");
  118. }
  119. }
  120. }
  121. ~robust_mutex_lock_file()
  122. {
  123. //The destructor is guaranteed by intermodule_singleton to be
  124. //executed serialized between all threads from current process,
  125. //so we just need to close and unlink the file.
  126. close_file(fd);
  127. //If some other process deletes the file before us after
  128. //closing it there should not be any problem.
  129. delete_file(fname.c_str());
  130. }
  131. private:
  132. //This functor is execute for all files in the lock file directory
  133. class other_process_lock_remover
  134. {
  135. public:
  136. void operator()(const char *filepath, const char *filename)
  137. {
  138. std::string pid_str;
  139. //If the lock file is not our own lock file, then try to do the cleanup
  140. if(!intermodule_singleton_helpers::check_if_filename_complies_with_pid
  141. (filename, robust_lock_prefix(), get_current_process_id(), pid_str)){
  142. remove_if_can_lock_file(filepath);
  143. }
  144. }
  145. };
  146. bool remove_old_robust_lock_files()
  147. {
  148. std::string refcstrRootDirectory;
  149. robust_lock_path(refcstrRootDirectory);
  150. return for_each_file_in_dir(refcstrRootDirectory.c_str(), other_process_lock_remover());
  151. }
  152. };
  153. } //namespace robust_emulation_helpers {
  154. //This is the mutex class. Mutex should follow mutex concept
  155. //with an additonal "take_ownership()" function to take ownership of the
  156. //mutex when robust_spin_mutex determines the previous owner was dead.
  157. template<class Mutex>
  158. class robust_spin_mutex
  159. {
  160. public:
  161. static const boost::uint32_t correct_state = 0;
  162. static const boost::uint32_t fixing_state = 1;
  163. static const boost::uint32_t broken_state = 2;
  164. typedef robust_emulation_helpers::mutex_traits<Mutex> mutex_traits_t;
  165. robust_spin_mutex();
  166. void lock();
  167. bool try_lock();
  168. bool timed_lock(const boost::posix_time::ptime &abs_time);
  169. void unlock();
  170. void consistent();
  171. bool previous_owner_dead();
  172. private:
  173. static const unsigned int spin_threshold = 100u;
  174. bool lock_own_unique_file();
  175. bool robust_check();
  176. bool check_if_owner_dead_and_take_ownership_atomically();
  177. bool is_owner_dead(boost::uint32_t owner);
  178. void owner_to_filename(boost::uint32_t owner, std::string &s);
  179. //The real mutex
  180. Mutex mtx;
  181. //The pid of the owner
  182. volatile boost::uint32_t owner;
  183. //The state of the mutex (correct, fixing, broken)
  184. volatile boost::uint32_t state;
  185. };
  186. template<class Mutex>
  187. inline robust_spin_mutex<Mutex>::robust_spin_mutex()
  188. : mtx(), owner(get_invalid_process_id()), state(correct_state)
  189. {}
  190. template<class Mutex>
  191. inline void robust_spin_mutex<Mutex>::lock()
  192. {
  193. //If the mutex is broken (recovery didn't call consistent()),
  194. //then throw an exception
  195. if(atomic_read32(&this->state) == broken_state){
  196. throw interprocess_exception(lock_error, "Broken id");
  197. }
  198. //This function provokes intermodule_singleton instantiation
  199. if(!this->lock_own_unique_file()){
  200. throw interprocess_exception(lock_error, "Broken id");
  201. }
  202. //Now the logic. Try to lock, if successful mark the owner
  203. //if it fails, start recovery logic
  204. unsigned int spin_count = 0;
  205. while(1){
  206. if (mtx.try_lock()){
  207. atomic_write32(&this->owner, get_current_process_id());
  208. break;
  209. }
  210. else{
  211. //Do the dead owner checking each spin_threshold lock tries
  212. ipcdetail::thread_yield();
  213. ++spin_count;
  214. if(spin_count > spin_threshold){
  215. //Check if owner dead and take ownership if possible
  216. if(!this->robust_check()){
  217. spin_count = 0;
  218. }
  219. else{
  220. break;
  221. }
  222. }
  223. }
  224. }
  225. }
  226. template<class Mutex>
  227. inline bool robust_spin_mutex<Mutex>::try_lock()
  228. {
  229. //Same as lock() but without spinning
  230. if(atomic_read32(&this->state) == broken_state){
  231. throw interprocess_exception(lock_error, "Broken id");
  232. }
  233. if(!this->lock_own_unique_file()){
  234. throw interprocess_exception(lock_error, "Broken id");
  235. }
  236. if (mtx.try_lock()){
  237. atomic_write32(&this->owner, get_current_process_id());
  238. return true;
  239. }
  240. else{
  241. if(!this->robust_check()){
  242. return false;
  243. }
  244. else{
  245. return true;
  246. }
  247. }
  248. }
  249. template<class Mutex>
  250. inline bool robust_spin_mutex<Mutex>::timed_lock
  251. (const boost::posix_time::ptime &abs_time)
  252. {
  253. //Same as lock() but with an additional timeout
  254. if(abs_time == boost::posix_time::pos_infin){
  255. this->lock();
  256. return true;
  257. }
  258. //Obtain current count and target time
  259. boost::posix_time::ptime now = microsec_clock::universal_time();
  260. if(now >= abs_time)
  261. return this->try_lock();
  262. do{
  263. if(this->try_lock()){
  264. break;
  265. }
  266. now = microsec_clock::universal_time();
  267. if(now >= abs_time){
  268. return this->try_lock();
  269. }
  270. // relinquish current time slice
  271. ipcdetail::thread_yield();
  272. }while (true);
  273. return true;
  274. }
  275. template<class Mutex>
  276. inline void robust_spin_mutex<Mutex>::owner_to_filename(boost::uint32_t owner, std::string &s)
  277. {
  278. robust_emulation_helpers::create_and_get_robust_lock_file_path(s, owner);
  279. }
  280. template<class Mutex>
  281. inline bool robust_spin_mutex<Mutex>::robust_check()
  282. {
  283. //If the old owner was dead, and we've acquired ownership, mark
  284. //the mutex as 'fixing'. This means that a "consistent()" is needed
  285. //to avoid marking the mutex as "broken" when the mutex is unlocked.
  286. if(!this->check_if_owner_dead_and_take_ownership_atomically()){
  287. return false;
  288. }
  289. atomic_write32(&this->state, fixing_state);
  290. return true;
  291. }
  292. template<class Mutex>
  293. inline bool robust_spin_mutex<Mutex>::check_if_owner_dead_and_take_ownership_atomically()
  294. {
  295. boost::uint32_t cur_owner = get_current_process_id();
  296. boost::uint32_t old_owner = atomic_read32(&this->owner), old_owner2;
  297. //The cas loop guarantees that only one thread from this or another process
  298. //will succeed taking ownership
  299. do{
  300. //Check if owner is dead
  301. if(!this->is_owner_dead(old_owner)){
  302. return false;
  303. }
  304. //If it's dead, try to mark this process as the owner in the owner field
  305. old_owner2 = old_owner;
  306. old_owner = atomic_cas32(&this->owner, cur_owner, old_owner);
  307. }while(old_owner2 != old_owner);
  308. //If success, we fix mutex internals to assure our ownership
  309. mutex_traits_t::take_ownership(mtx);
  310. return true;
  311. }
  312. template<class Mutex>
  313. inline bool robust_spin_mutex<Mutex>::is_owner_dead(boost::uint32_t owner)
  314. {
  315. //If owner is an invalid id, then it's clear it's dead
  316. if(owner == (boost::uint32_t)get_invalid_process_id()){
  317. return true;
  318. }
  319. //Obtain the lock filename of the owner field
  320. std::string file;
  321. this->owner_to_filename(owner, file);
  322. //Now the logic is to open and lock it
  323. file_handle_t fhnd = open_existing_file(file.c_str(), read_write);
  324. if(fhnd != invalid_file()){
  325. //If we can open the file, lock it.
  326. bool acquired;
  327. if(try_acquire_file_lock(fhnd, acquired) && acquired){
  328. //If locked, just delete the file
  329. delete_file(file.c_str());
  330. close_file(fhnd);
  331. return true;
  332. }
  333. //If not locked, the owner is suppossed to be still alive
  334. close_file(fhnd);
  335. }
  336. else{
  337. //If the lock file does not exist then the owner is dead (a previous cleanup)
  338. //function has deleted the file. If there is another reason, then this is
  339. //an unrecoverable error
  340. if(error_info(system_error_code()).get_error_code() == not_found_error){
  341. return true;
  342. }
  343. }
  344. return false;
  345. }
  346. template<class Mutex>
  347. inline void robust_spin_mutex<Mutex>::consistent()
  348. {
  349. //This function supposes the previous state was "fixing"
  350. //and the current process holds the mutex
  351. if(atomic_read32(&this->state) != fixing_state &&
  352. atomic_read32(&this->owner) != (boost::uint32_t)get_current_process_id()){
  353. throw interprocess_exception(lock_error, "Broken id");
  354. }
  355. //If that's the case, just update mutex state
  356. atomic_write32(&this->state, correct_state);
  357. }
  358. template<class Mutex>
  359. inline bool robust_spin_mutex<Mutex>::previous_owner_dead()
  360. {
  361. //Notifies if a owner recovery has been performed in the last lock()
  362. return atomic_read32(&this->state) == fixing_state;
  363. };
  364. template<class Mutex>
  365. inline void robust_spin_mutex<Mutex>::unlock()
  366. {
  367. //If in "fixing" state, unlock and mark the mutex as unrecoverable
  368. //so next locks will fail and all threads will be notified that the
  369. //data protected by the mutex was not recoverable.
  370. if(atomic_read32(&this->state) == fixing_state){
  371. atomic_write32(&this->state, broken_state);
  372. }
  373. //Write an invalid owner to minimize pid reuse possibility
  374. atomic_write32(&this->owner, get_invalid_process_id());
  375. mtx.unlock();
  376. }
  377. template<class Mutex>
  378. inline bool robust_spin_mutex<Mutex>::lock_own_unique_file()
  379. {
  380. //This function forces instantiation of the singleton
  381. robust_emulation_helpers::robust_mutex_lock_file* dummy =
  382. &ipcdetail::intermodule_singleton
  383. <robust_emulation_helpers::robust_mutex_lock_file>::get();
  384. return dummy != 0;
  385. }
  386. } //namespace ipcdetail{
  387. } //namespace interprocess{
  388. } //namespace boost{
  389. #include <boost/interprocess/detail/config_end.hpp>
  390. #endif