Class: ActiveRecord::Tenanted::Mutex::Ready
- Inherits:
-
Object
- Object
- ActiveRecord::Tenanted::Mutex::Ready
- Defined in:
- lib/active_record/tenanted/mutex.rb
Overview
This flock-based mutex is intended to hold a lock while the tenant database is in the
process of being created and migrated (i.e., "made ready").
The creation-and-migration time span is generally very short, and only happens once at the
beginning of the database file's existence. We can take advantage of these characteristics
to make sure the readiness check is cheap for the majority of the database's life.
1. The lock file is created and an advisory lock is acquired before the database file is
created.
2. Once the database migration has been completed and the database is ready, the lock is
released and the file is removed.
If the lock file exists, then a relatively expensive shared lock must be acquired to ensure
the database is ready to use. However, if the lock file does not exist (the majority of the
database's life!) then the readiness check is a cheap check for existing on the database
file.
Class Method Summary collapse
- .lock(database_path) ⇒ Object
- .lock_file_path(database_path) ⇒ Object
- .locked?(database_path) ⇒ Boolean
Class Method Details
.lock(database_path) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/active_record/tenanted/mutex.rb', line 26 def lock(database_path) path = lock_file_path(database_path) FileUtils.mkdir_p(File.dirname(path)) # mode "w" to create the file if it does not exist. File.open(path, "w") do |f| f.flock(File::LOCK_EX) # blocking! yield ensure File.unlink(path) end end |
.lock_file_path(database_path) ⇒ Object
59 60 61 |
# File 'lib/active_record/tenanted/mutex.rb', line 59 def lock_file_path(database_path) database_path.to_s + ".ready_lock" end |
.locked?(database_path) ⇒ Boolean
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/active_record/tenanted/mutex.rb', line 39 def locked?(database_path) path = lock_file_path(database_path) if File.exist?(path) result = nil begin # mode "r" to avoid creating the file if it does not exist. File.open(path, "r") do |f| result = f.flock(File::LOCK_SH | File::LOCK_NB) end result != 0 rescue Errno::ENOENT # the file was deleted between the existence check and the open false end else false end end |