Class: Herdis::Shepherd

Inherits:
Object
  • Object
show all
Defined in:
lib/herdis/shepherd.rb

Defined Under Namespace

Classes: Shard

Constant Summary collapse

CHECK_SLAVE_TIMER =
(ENV["SHEPHERD_CHECK_SLAVE_TIMER"] || 10).to_f
CHECK_PREDECESSOR_TIMER =
(ENV["SHEPHERD_CHECK_PREDECESSOR_TIMER"] || 1).to_f

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Shepherd

Returns a new instance of Shepherd.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/herdis/shepherd.rb', line 137

def initialize(options = {})
  @dir = options.delete(:dir) || File.join(ENV["HOME"], ".herdis")
  @redis = options.delete(:redis) || "redis-server"
  @port = options.delete(:port) || 9000
  @logger = options.delete(:logger)
  @first_port = options.delete(:first_port) || 9080
  @inmemory = options.delete(:inmemory)
  @redundancy = options.delete(:redundancy) || 2
  @shepherd_id = options.delete(:shepherd_id) || rand(1 << 256).to_s(36)
  Dir.mkdir(dir) unless Dir.exists?(dir)

  @shepherds = {}
  @slaves = {}
  @masters = {}

  at_exit do
    shutdown
  end

  if connect_to = options.delete(:connect_to)
    join_cluster(connect_to)
  else
    Herdis::Common::SHARDS.times do |shard_id|
      create_master_shard(shard_id)
    end
    @shepherds[shepherd_id] = shepherd_status
  end
end

Instance Attribute Details

#dirObject (readonly)

Returns the value of attribute dir.



124
125
126
# File 'lib/herdis/shepherd.rb', line 124

def dir
  @dir
end

#first_portObject (readonly)

Returns the value of attribute first_port.



126
127
128
# File 'lib/herdis/shepherd.rb', line 126

def first_port
  @first_port
end

#inmemoryObject (readonly)

Returns the value of attribute inmemory.



127
128
129
# File 'lib/herdis/shepherd.rb', line 127

def inmemory
  @inmemory
end

#loggerObject (readonly)

Returns the value of attribute logger.



131
132
133
# File 'lib/herdis/shepherd.rb', line 131

def logger
  @logger
end

#mastersObject (readonly)

Returns the value of attribute masters.



133
134
135
# File 'lib/herdis/shepherd.rb', line 133

def masters
  @masters
end

#portObject (readonly)

Returns the value of attribute port.



130
131
132
# File 'lib/herdis/shepherd.rb', line 130

def port
  @port
end

#redisObject (readonly)

Returns the value of attribute redis.



125
126
127
# File 'lib/herdis/shepherd.rb', line 125

def redis
  @redis
end

#redundancyObject (readonly)

Returns the value of attribute redundancy.



129
130
131
# File 'lib/herdis/shepherd.rb', line 129

def redundancy
  @redundancy
end

#shepherd_idObject (readonly)

Returns the value of attribute shepherd_id.



128
129
130
# File 'lib/herdis/shepherd.rb', line 128

def shepherd_id
  @shepherd_id
end

#shepherdsObject (readonly)

Returns the value of attribute shepherds.



135
136
137
# File 'lib/herdis/shepherd.rb', line 135

def shepherds
  @shepherds
end

#slavesObject (readonly)

Returns the value of attribute slaves.



134
135
136
# File 'lib/herdis/shepherd.rb', line 134

def slaves
  @slaves
end

Instance Method Details

#add_shards(shepherd_id, shard_ids, check = true) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/herdis/shepherd.rb', line 222

def add_shards(shepherd_id, shard_ids, check = true)
  if shepherd_state = shepherds[shepherd_id]
    shard_id_set = Set.new(shard_ids)
    current_shard_id_set = Set.new(shepherd_state["masters"])
    unless current_shard_id_set.superset?(shard_id_set)
      shepherd_state["masters"] = (current_shard_id_set | shard_id_set).to_a
      to_each_sibling(:apost,
                      :path => "/#{shepherd_id}/shards",
                      :body => Yajl::Encoder.encode(:shard_ids => shard_ids.to_a)) do
        check_shards if check
      end
    end
  end
end

#add_shepherd(shepherd_status) ⇒ Object



201
202
203
204
205
206
207
208
209
210
# File 'lib/herdis/shepherd.rb', line 201

def add_shepherd(shepherd_status)
  unless shepherd_status == shepherds[shepherd_status["id"]]
    shepherds[shepherd_status["id"]] = shepherd_status
    to_each_sibling(:aput,
                    :path => "/#{shepherd_status["id"]}",
                    :body => Yajl::Encoder.encode(shepherd_status)) do
      check_shards
    end
  end
end

#backup_ordinalsObject



467
468
469
470
471
472
473
474
475
# File 'lib/herdis/shepherd.rb', line 467

def backup_ordinals
  rval = Set.new
  ordered_keys = ordered_shepherd_keys
  my_index = ordered_keys.index(shepherd_id)
  [redundancy, ordered_keys.size - 1].min.times do |n|
    rval << (my_index - n - 1) % ordered_keys.size
  end
  rval
end

#backup_shardsObject



477
478
479
480
481
482
483
# File 'lib/herdis/shepherd.rb', line 477

def backup_shards
  rval = Set.new
  backup_ordinals.each do |ordinal|
    rval += shards_owned_by(ordinal)
  end
  rval
end

#check_predecessorObject



508
509
510
511
512
513
514
515
516
517
518
# File 'lib/herdis/shepherd.rb', line 508

def check_predecessor
  pre = predecessor
  if pre && pre["id"] != shepherd_id
    Fiber.new do
      if EM::HttpRequest.new(pre["url"]).head.response_header.status != 204
        logger.warn("#{shepherd_id} *** dropping #{pre["id"]} due to failure to respond to ping")
        remove_shepherd(pre["id"])
      end
    end.resume
  end
end

#check_shardsObject



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/herdis/shepherd.rb', line 372

def check_shards
  should_be_owned = owned_shards
  should_be_backed_up = backup_shards
  master_ids = Set.new(masters.keys)
  slave_ids = Set.new(slaves.keys)
  external_shards = create_external_shards(should_be_owned)
  externally_running = Set.new(external_shards.keys)

  needs_to_be_liberated = slave_ids - externally_running
  needs_to_be_enslaved = (master_ids & externally_running & should_be_backed_up) - should_be_owned
  needs_to_be_directed = slave_ids & externally_running & (should_be_backed_up | should_be_owned)
  slaves_needing_to_be_shut_down = (slave_ids & externally_running) - (should_be_backed_up | should_be_owned)
  masters_needing_to_be_shut_down = (master_ids & externally_running) - (should_be_backed_up | should_be_owned)
  new_slaves_needed = ((should_be_backed_up | should_be_owned) & externally_running) - (slave_ids | master_ids)

  handled = Set.new

  logger.debug "#{shepherd_id} *** liberating #{needs_to_be_liberated.inspect}" unless needs_to_be_liberated.empty?
  needs_to_be_liberated.each do |shard_id|
    handled.add(shard_id.to_s)
    slaves[shard_id.to_s].liberate!
  end
  add_shards(shepherd_id, needs_to_be_liberated, false)

  logger.debug "#{shepherd_id} *** enslaving #{needs_to_be_enslaved.inspect}" unless needs_to_be_enslaved.empty?
  needs_to_be_enslaved.each do |shard_id|
    raise "Already liberated #{shard_id}!" if handled.include?(shard_id.to_s)
    handled.add(shard_id.to_s)
    masters[shard_id.to_s].enslave!(external_shards[shard_id.to_s])
  end
  remove_shards(shepherd_id, needs_to_be_enslaved, false)

  logger.debug "#{shepherd_id} *** redirecting #{needs_to_be_directed.inspect}" unless needs_to_be_directed.empty?
  needs_to_be_directed.each do |shard_id|
    raise "Already liberated or enslaved #{shard_id}!" if handled.include?(shard_id.to_s)
    handled.add(shard_id.to_s)
    slaves[shard_id.to_s].enslave!(external_shards[shard_id.to_s])
  end

  logger.debug "#{shepherd_id} *** killing masters #{masters_needing_to_be_shut_down.inspect}" unless masters_needing_to_be_shut_down.empty?
  masters_needing_to_be_shut_down.each do |shard_id|
    raise "Already liberated, enslaved or directed #{shard_id}!" if handled.include?(shard_id.to_s)
    handled.add(shard_id.to_s)
    shutdown_shard(shard_id)
  end
  remove_shards(shepherd_id, masters_needing_to_be_shut_down, false)
  
  logger.debug "#{shepherd_id} *** killing slaves #{slaves_needing_to_be_shut_down.inspect}" unless slaves_needing_to_be_shut_down.empty?
  slaves_needing_to_be_shut_down.each do |shard_id|
    raise "Already liberated, enslaved, directed or shut down #{shard_id}!" if handled.include?(shard_id.to_s)
    handled.add(shard_id.to_s)
    shutdown_slave(shard_id)
  end

  logger.debug "#{shepherd_id} *** creating slaves #{new_slaves_needed.inspect}" unless new_slaves_needed.empty?
  new_slaves_needed.each do |shard_id|
    raise "Already liberated, enslaved, directed or shut down #{shard_id}!" if handled.include?(shard_id.to_s)
    handled.add(shard_id.to_s)
    create_slave_shard(shard_id.to_s, external_shards[shard_id.to_s])
  end
  
  ensure_slave_check
  ensure_predecessor_check
end

#check_slavesObject



437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/herdis/shepherd.rb', line 437

def check_slaves
  revolution = Set.new
  (owned_shards & slaves.keys).each do |shard_id|
    shard = slaves[shard_id.to_s]
    if shard.connection.info["master_sync_in_progress"] == "0"
      revolution << shard_id.to_s
    end
  end
  unless revolution.empty?
    logger.debug "#{shepherd_id} *** revolting #{revolution.inspect}"
    add_shards(shepherd_id, revolution.to_a)
  end
end

#cluster_infoObject



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/herdis/shepherd.rb', line 270

def cluster_info
  {
    "shepherd_id" => shepherd_id,
    "ordinal" => ordinal,
    "slaves" => slaves.keys,
    "masters" => masters.keys,
    "redundancy" => redundancy,
    "siblings" => shepherds.keys.sort,
    "inmemory" => inmemory,
    "check_slave_timer" => CHECK_SLAVE_TIMER,
    "check_predecessor_timer" => CHECK_PREDECESSOR_TIMER,
    "sanity" => "#{url}/sanity",
    "cluster" => "#{url}/cluster"
  }
end

#cluster_statusObject



331
332
333
# File 'lib/herdis/shepherd.rb', line 331

def cluster_status
  shepherds.merge(shepherd_id => shepherd_status)
end

#create_external_shards(should_be_owned) ⇒ Object



358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/herdis/shepherd.rb', line 358

def create_external_shards(should_be_owned)
  shepherds.values.inject({}) do |sum, shepherd_status|
    if shepherd_status["id"] == shepherd_id
      sum
    else
      shepherd_url = URI.parse(shepherd_status["url"])
      sum.merge(shepherd_status["masters"].inject({}) do |sum, shard_id|
                  shepherd_url = URI.parse(shepherd_status["url"])
                  sum.merge(shard_id.to_s => URI.parse("redis://#{shepherd_url.host}:#{shepherd_status["first_port"].to_i + shard_id.to_i}/"))
                end)
    end    
  end
end

#create_master_shard(shard_id) ⇒ Object



451
452
453
# File 'lib/herdis/shepherd.rb', line 451

def create_master_shard(shard_id)
  masters[shard_id.to_s] = create_shard(shard_id)
end

#create_shard(shard_id, options = {}) ⇒ Object



524
525
526
527
# File 'lib/herdis/shepherd.rb', line 524

def create_shard(shard_id, options = {})
  Shard.new(options.merge(:shepherd => self,
                          :id => shard_id))
end

#create_slave_shard(shard_id, external_uri) ⇒ Object



520
521
522
# File 'lib/herdis/shepherd.rb', line 520

def create_slave_shard(shard_id, external_uri)
  slaves[shard_id.to_s] = create_shard(shard_id, :master => external_uri)
end

#ensure_predecessor_checkObject



172
173
174
175
176
# File 'lib/herdis/shepherd.rb', line 172

def ensure_predecessor_check
  @check_predecessor_timer ||= EM.add_periodic_timer(CHECK_PREDECESSOR_TIMER) do
    check_predecessor
  end
end

#ensure_slave_checkObject



166
167
168
169
170
# File 'lib/herdis/shepherd.rb', line 166

def ensure_slave_check
  @check_slave_timer ||= EM.add_periodic_timer(CHECK_SLAVE_TIMER) do
    check_slaves
  end
end

#hostObject



252
253
254
255
# File 'lib/herdis/shepherd.rb', line 252

def host
  @host = Fiber.current.host if Fiber.current.respond_to?(:host)
  @host || "localhost"
end

#join_cluster(url) ⇒ Object



194
195
196
197
198
199
# File 'lib/herdis/shepherd.rb', line 194

def join_cluster(url)
  shutdown
  @shepherds = Yajl::Parser.parse(EM::HttpRequest.new(url).get(:path => "/cluster",
                                                               :head => {"Content-Type" => "application/json"}).response)
  add_shepherd(shepherd_status)
end

#ordered_shepherd_keysObject



459
460
461
# File 'lib/herdis/shepherd.rb', line 459

def ordered_shepherd_keys
  shepherds.keys.sort
end

#ordinalObject



463
464
465
# File 'lib/herdis/shepherd.rb', line 463

def ordinal
  shepherds.keys.sort.index(shepherd_id)
end

#owned_shardsObject



494
495
496
# File 'lib/herdis/shepherd.rb', line 494

def owned_shards
  shards_owned_by(ordinal)
end

#predecessorObject



498
499
500
501
502
503
504
505
506
# File 'lib/herdis/shepherd.rb', line 498

def predecessor
  ordered_keys = ordered_shepherd_keys
  my_index = ordered_keys.index(shepherd_id)
  if my_index == 0
    shepherds[ordered_keys.last]
  else
    shepherds[ordered_keys[my_index - 1]]
  end
end

#remove_shards(shepherd_id, shard_ids, check = true) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/herdis/shepherd.rb', line 237

def remove_shards(shepherd_id, shard_ids, check = true)
  if shepherd_state = shepherds[shepherd_id]
    shard_id_set = Set.new(shard_ids)
    current_shard_id_set = Set.new(shepherd_state["masters"])
    unless (shard_id_set & current_shard_id_set).empty?
      shepherd_state["masters"] = (current_shard_id_set - shard_id_set).to_a
      to_each_sibling(:adelete,
                      :path => "/#{shepherd_id}/shards",
                      :body => Yajl::Encoder.encode(:shard_ids => shard_ids.to_a)) do
        check_shards if check
      end
    end
  end
end

#remove_shepherd(shepherd_id) ⇒ Object



212
213
214
215
216
217
218
219
220
# File 'lib/herdis/shepherd.rb', line 212

def remove_shepherd(shepherd_id)
  if shepherds.include?(shepherd_id)
    shepherds.delete(shepherd_id)
    to_each_sibling(:adelete,
                    :path => "/#{shepherd_id}") do
      check_shards
    end
  end
end

#sanityObject



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/herdis/shepherd.rb', line 286

def sanity
  creators = Set.new
  min_created_at = nil
  max_created_at = nil
  masters = 0
  slaves = 0
  consistent = true
  urls = []
  shard_status.each do |shard_url|
    urls << shard_url
    url = URI.parse(shard_url)
    shard_connection = Redis.new(:host => url.host, :port => url.port)
    info = shard_connection.info
    masters += 1 if info["role"] == "master"
    slaves += 1 if info["role"] == "slave"
    created_at = shard_connection.get("#{Herdis::Shepherd::Shard.name}.created_at").to_i
    min_created_at = created_at if min_created_at.nil? || created_at < min_created_at
    max_created_at = created_at if max_created_at.nil? || created_at > max_created_at
    creators << shard_connection.get("#{Herdis::Shepherd::Shard.name}.created_by")
  end
  {
    :creators => creators.to_a,
    :consistent => creators.size == 1 && masters == Herdis::Common::SHARDS && slaves == 0,
    :min_created_at => Time.at(min_created_at).to_s,
    :max_created_at => Time.at(max_created_at).to_s,
    :masters => masters,
    :slaves => slaves,
    :shards => urls
  }
end

#shard_statusObject



317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/herdis/shepherd.rb', line 317

def shard_status
  rval = []
  cluster_status.each do |shepherd_id, shepherd_status|
    shepherd_status["masters"].each do |shard_id|
      if rval[shard_id.to_i].nil?
        rval[shard_id.to_i] = "redis://#{host}:#{shard_id.to_i + shepherd_status["first_port"].to_i}/"
      else
        raise Goliath::Validation::InternalServerError.new("Duplicate masters: #{shard_id}")
      end
    end
  end
  rval
end

#shards_owned_by(ordinal) ⇒ Object



485
486
487
488
489
490
491
492
# File 'lib/herdis/shepherd.rb', line 485

def shards_owned_by(ordinal)
  rval = Set.new
  while ordinal < Herdis::Common::SHARDS
    rval << ordinal.to_s
    ordinal += shepherds.size
  end
  rval
end

#shepherd_statusObject



261
262
263
264
265
266
267
268
# File 'lib/herdis/shepherd.rb', line 261

def shepherd_status
  {
    "url" => url,
    "id" => shepherd_id,
    "first_port" => first_port,
    "masters" => masters.keys
  }
end

#shutdownObject



349
350
351
352
353
354
355
356
# File 'lib/herdis/shepherd.rb', line 349

def shutdown
  masters.keys.each do |shard_id|
    shutdown_shard(shard_id)
  end
  slaves.keys.each do |shard_id|
    shutdown_slave(shard_id)
  end
end

#shutdown_shard(shard_id) ⇒ Object



335
336
337
338
339
340
# File 'lib/herdis/shepherd.rb', line 335

def shutdown_shard(shard_id)
  if shard = masters[shard_id.to_s]
    shard.connection.shutdown
    masters.delete(shard_id.to_s)
  end
end

#shutdown_slave(shard_id) ⇒ Object



342
343
344
345
346
347
# File 'lib/herdis/shepherd.rb', line 342

def shutdown_slave(shard_id)
  if shard = slaves[shard_id.to_s]
    shard.connection.shutdown
    slaves.delete(shard_id.to_s)
  end
end

#statusObject



455
456
457
# File 'lib/herdis/shepherd.rb', line 455

def status
  204
end

#to_each_sibling(method, options, &block) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/herdis/shepherd.rb', line 178

def to_each_sibling(method, options, &block)
  default_options = {:head => {"Content-Type" => "application/json"}}
  multi = EM::Synchrony::Multi.new
  shepherds.each do |shepherd_id, shepherd|
    unless shepherd_id == self.shepherd_id
      multi.add(shepherd_id, 
                EM::HttpRequest.new(shepherd["url"]).send(method, 
                                                          default_options.rmerge(options)))
    end
  end
  yield
  Fiber.new do
    multi.perform while !multi.finished?
  end.resume
end

#urlObject



257
258
259
# File 'lib/herdis/shepherd.rb', line 257

def url
  "http://#{host}:#{port}"
end