Module: Agent::Lock::Store

Defined in:
lib/agent/lock/store.rb,
lib/agent/lock/store/redis_index.rb,
lib/agent/lock/store/redis_store.rb,
lib/agent/lock/store/backend_name.rb,
lib/agent/lock/store/file_system_store.rb

Overview

Where locks are kept. One tree, one store, chosen on purpose.

A caller that names a backend (alock --locking-strategy) wins, then AGENT_LOCK_BACKEND when set. A caller that names the Redis itself (alock --redis-url, or AGENT_LOCK_REDIS_URL) has asked for Redis, and for that one alone: no REDIS_URL, no local default. Otherwise a tree that already has a marker keeps using it. A virgin tree defaults to Redis when one answers on REDIS_URL or, failing that, on the local default; file when neither does.

A name that is no backend is refused before any of that, by BackendName, so it never reaches the marker.

That default is still never a runtime auto-switch: once a marker exists, every later process in that tree is bound to it regardless of what Redis is doing, because an agent that quietly moved to a different store than the agent beside it would give the two of them two stores in which neither can see the other's locks, a lock that is worse than no lock, because it reports success.

The one moment that default is decided is also the one moment two processes could race: both find a virgin tree, both probe Redis, and a flaky answer could hand them different defaults before either writes the marker. So the marker is claimed atomically (the first hard link wins) and every process builds from whatever ends up on disk, never from its own guess, so a race can pick either backend but never a split.

Defined Under Namespace

Modules: BackendName Classes: FileSystemStore, Mismatch, RedisIndex, RedisStore, Unreachable

Constant Summary collapse

MARKER =

The file in a tree's store directory that records its backend.

"backend"
REDIS_URL_ENV =

The environment's --redis-url: the one Redis to use, set by a dispatcher for the agents it starts. Its own name, because REDIS_URL may belong to the project the agent is working on.

"AGENT_LOCK_REDIS_URL"
BACKENDS =

The names a backend marker can hold.

%w[file redis].freeze

Class Method Summary collapse

Class Method Details

.agreed(established, requested) ⇒ String

Returns established.

Parameters:

  • established (String) —

    the backend the tree's marker records

  • requested (String, nil) —

    the backend this process asked for

Returns:

  • (String) —

    established

Raises:



110
111
112
113
114
115
116
117
# File 'lib/agent/lock/store.rb', line 110

def agreed(established, requested)
  return established if requested.nil? || requested == established

  # `.for` passes on a real backend or none, but this is callable on
  # its own. Only a real backend goes into a command somebody will paste.
  raise Mismatch.new("this tree's locks live in #{established}, not #{requested}",
                     command: ("switch-backend #{requested}" if BACKENDS.include?(requested)))
end

.build(name, tree, redis_url: nil) ⇒ Store::FileSystemStore, Store::RedisStore

Parameters:

  • name (String) —

    "file" or "redis"

  • tree (Tree)
  • redis_url (String, nil) (defaults to: nil) —

    see for

Returns:

Raises:



162
163
164
165
166
167
168
# File 'lib/agent/lock/store.rb', line 162

def build(name, tree, redis_url: nil)
  case name
  when "redis" then redis_url ? RedisStore.at(tree, redis_url) : RedisStore.found(tree)
  when "file" then FileSystemStore.new(tree)
  else raise Mismatch, "unknown backend #{name.inspect}, expected file or redis"
  end
end

.claim(tree, name) ⇒ String

Atomically claims the marker for a virgin tree with name, or, when a concurrent process already claimed it first, reads back whatever that process wrote instead. Either way, every caller ends up building the same backend for this tree.

The marker is written to a temp file and hard-linked into place, so it never exists empty. Created with O_EXCL and written afterwards, a loser of the race could read it in between, take "" for the winner's backend, and refuse a tree that was about to agree with it.

Parameters:

  • tree (Tree)
  • name (String) —

    this process's proposed backend

Returns:

  • (String) —

    the backend actually recorded, which may not be name



201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/agent/lock/store.rb', line 201

def claim(tree, name)
  path = marker_path(tree)
  FileUtils.mkdir_p(File.dirname(path))
  publish(path, name)
  name
rescue Errno::EEXIST
  # Falling back to `name` here would let every caller keep its own
  # guess about a marker that stays empty: a silent split.
  settled(tree) || raise(Mismatch, "#{marker_path(tree)} exists but is empty; " \
                                   "write file or redis into it, or delete it")
rescue SystemCallError
  name
end

.default_backend ⇒ String

Returns "redis" when one answers on REDIS_URL or, failing that, on RedisStore::LOCAL_URL; "file" when neither does.

Returns:

  • (String) —

    "redis" when one answers on REDIS_URL or, failing that, on RedisStore::LOCAL_URL; "file" when neither does



256
257
258
# File 'lib/agent/lock/store.rb', line 256

def default_backend
  local_redis_available? ? "redis" : "file"
end

.establish(tree, requested, redis_url) ⇒ Store::FileSystemStore, Store::RedisStore

Claims a virgin tree. A Redis that was asked for is connected to before the marker is written: a tree bound to a Redis that never answered would refuse every later command. What claim hands back is checked too, since another process may have claimed the tree for the other backend in between.

Parameters:

  • tree (Tree)
  • requested (String, nil)
  • redis_url (String, nil)

Returns:

Raises:

  • (Unreachable) —

    when Redis was asked for and does not answer

  • (Mismatch) —

    when another process claimed the tree for the other backend



150
151
152
153
154
# File 'lib/agent/lock/store.rb', line 150

def establish(tree, requested, redis_url)
  store = build("redis", tree, redis_url:) if requested == "redis"
  claimed = agreed(claim(tree, requested || default_backend), requested)
  store || build(claimed, tree, redis_url:)
end

.for(tree, backend: nil, redis_url: nil) ⇒ Store::FileSystemStore, Store::RedisStore

Parameters:

  • tree (Tree)
  • backend (String, nil) (defaults to: nil) —

    "file" or "redis", named by the caller; nil leaves it to AGENT_LOCK_BACKEND, the marker and the default

  • redis_url (String, nil) (defaults to: nil) —

    the one Redis to use, with no search and no fallback; nil reads REDIS_URL_ENV, and without that searches as Agent::Lock::Store::RedisStore.candidate_urls says

Returns:

Raises:

  • (Mismatch) —

    when the tree's locks live in the other backend, or a Redis is named beside the file backend

  • (Unreachable) —

    when the named Redis does not answer



73
74
75
76
77
78
79
80
# File 'lib/agent/lock/store.rb', line 73

def for(tree, backend: nil, redis_url: nil)
  url = redis_url || named_redis_url
  requested = requested_backend(backend, redis_url, url)
  established = BackendName.marked(recorded(tree), marker_path(tree), offer: requested)
  return build(agreed(established, requested), tree, redis_url: url) if established

  establish(tree, requested, url)
end

.local_redis_available? ⇒ Boolean

Returns whether a Redis client connected without error.

Returns:

  • (Boolean) —

    whether a Redis client connected without error



261
262
263
264
# File 'lib/agent/lock/store.rb', line 261

def local_redis_available?
  client, error = RedisStore.create_client
  !client.nil? && error.nil?
end

.marker_path(tree) ⇒ String

Returns where the tree's backend marker lives.

Parameters:

Returns:

  • (String) —

    where the tree's backend marker lives



252
# File 'lib/agent/lock/store.rb', line 252

def marker_path(tree) = File.join(tree.store_dir, MARKER)

.named_redis_url ⇒ String?

Returns REDIS_URL_ENV, when it is set to something.

Returns:



83
84
85
86
# File 'lib/agent/lock/store.rb', line 83

def named_redis_url
  url = ENV.fetch(REDIS_URL_ENV, "").strip
  url.empty? ? nil : url
end

.publish(path, name) ⇒ void

This method returns an undefined value.

Parameters:

  • path (String) —

    the marker

  • name (String)

Raises:

  • (Errno::EEXIST) —

    when another process claimed the tree first



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/agent/lock/store.rb', line 219

def publish(path, name)
  temp = "#{path}.#{Process.pid}.#{SecureRandom.hex(6)}.tmp"
  File.write(temp, "#{name}\n")
  begin
    File.link(temp, path)
  rescue Errno::EEXIST
    raise
  rescue SystemCallError
    # Any filesystem that cannot hard-link falls back to the exclusive
    # create, whose create-then-write window `settled` covers.
    File.write(path, "#{name}\n", mode: File::WRONLY | File::CREAT | File::EXCL)
  end
ensure
  FileUtils.rm_f(temp) if temp
end

.rebind(tree, name) ⇒ String

Points the tree at another backend, for switch-backend and nothing else. Written beside the marker and renamed over it, so a reader sees the old name or the new one, never an empty file. The caller is the one who made sure the old store holds nothing that still counts.

Parameters:

  • tree (Tree)
  • name (String) —

    "file" or "redis"

Returns:

  • (String) —

    name



127
128
129
130
131
132
133
134
135
136
# File 'lib/agent/lock/store.rb', line 127

def rebind(tree, name)
  path = marker_path(tree)
  FileUtils.mkdir_p(File.dirname(path))
  temp = "#{path}.#{Process.pid}.#{SecureRandom.hex(6)}.tmp"
  File.write(temp, "#{name}\n")
  File.rename(temp, path)
  name
ensure
  FileUtils.rm_f(temp) if temp
end

.recorded(tree) ⇒ String?

A marker that is missing, or still empty, is none. One that exists but cannot be read is an error, named as such: taken for none, it ended up reported as "exists but is empty", or, before that, let a caller pick its own backend.

Parameters:

Returns:

  • (String, nil) —

    the backend this tree already uses

Raises:

  • (Mismatch) —

    when the marker exists but cannot be read



178
179
180
181
182
183
184
185
186
# File 'lib/agent/lock/store.rb', line 178

def recorded(tree)
  path = marker_path(tree)
  value = File.read(path).strip
  value.empty? ? nil : value
rescue Errno::ENOENT, Errno::ENOTDIR
  nil
rescue SystemCallError => e
  raise Mismatch, "cannot read #{path}: #{e.message}; fix its permissions or delete it"
end

.requested_backend(backend, redis_url, url) ⇒ String?

A backend the caller passed wins over a URL the caller passed, which wins over the environment. A Redis named beside the file backend is refused, never quietly dropped: one of the two is a mistake, and guessing which puts this process in a store nobody else reads.

Parameters:

  • backend (String, nil) —

    the caller's

  • redis_url (String, nil) —

    the caller's

  • url (String, nil) —

    the Redis named by the caller or the environment

Returns:

  • (String, nil) —

    "file", "redis", or nil for the tree's own choice

Raises:

  • (Mismatch) —

    also for a name that is not a backend



98
99
100
101
102
103
104
# File 'lib/agent/lock/store.rb', line 98

def requested_backend(backend, redis_url, url)
  requested = BackendName.canonical(backend) || ("redis" if redis_url) || BackendName.from_environment
  return requested unless url
  return "redis" unless requested == "file"

  raise Mismatch, "a Redis URL (#{RedisStore.safe(url)}) does not go with the file backend"
end

.settled(tree) ⇒ String?

Waits briefly for a marker that exists but is still empty: an older alock creates it first and writes its name a moment later.

Parameters:

Returns:

  • (String, nil) —

    the recorded backend, or nil if none appeared



240
241
242
243
244
245
246
247
248
# File 'lib/agent/lock/store.rb', line 240

def settled(tree)
  50.times do
    value = recorded(tree)
    return value if value

    sleep 0.01
  end
  nil
end