Class: Herdis::Shepherd

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

Defined Under Namespace

Classes: MockLogger, 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.



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/herdis/shepherd.rb', line 157

def initialize(options = {})
  @shutdown = false
  @dir = options.delete(:dir) || File.join(ENV["HOME"], ".herdis")
  Dir.mkdir(dir) unless Dir.exists?(dir)
  @host = options.delete(:host) || "localhost"
  @redis = options.delete(:redis) || "redis-server"
  @port = options.delete(:port) || 9000
  @logger = options.delete(:logger) || MockLogger.new
  @first_port = options.delete(:first_port) || 9080
  @inmemory = options.delete(:inmemory)
  @redundancy = options.delete(:redundancy) || 2
  
  restart = options.delete(:restart) || false
  if restart && File.exists?(config_file)
    old_config = open(config_file) do |input|
      Yajl::Parser.parse(input.read)
    end
    @shepherd_id = old_config["shepherd_id"]
    @shepherds = old_config["shepherds"]
    logger.info("#{shepherd_id} *** restoring old config")
    logger.info("#{shepherd_id} *** siblings: #{shepherds.keys}")
    logger.info("#{shepherd_id} *** masters: #{old_config["masters"]}")
    logger.info("#{shepherd_id} *** slaves: #{old_config["slaves"].keys}")
    @slaves = {}
    @masters = {}
    @ready_check_timer = EM.add_periodic_timer(CHECK_PREDECESSOR_TIMER) do
      Fiber.new do
        check_ready(old_config)
      end.resume
    end
  else
    @shepherd_id = options.delete(:shepherd_id) || rand(1 << 256).to_s(36)
    @shepherds = {}
    @slaves = {}
    @masters = {}
    
    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
  
  at_exit do
    shutdown
  end
  
end

Instance Attribute Details

#dirObject (readonly)

Returns the value of attribute dir.



142
143
144
# File 'lib/herdis/shepherd.rb', line 142

def dir
  @dir
end

#first_portObject (readonly)

Returns the value of attribute first_port.



144
145
146
# File 'lib/herdis/shepherd.rb', line 144

def first_port
  @first_port
end

#hostObject (readonly)

Returns the value of attribute host.



150
151
152
# File 'lib/herdis/shepherd.rb', line 150

def host
  @host
end

#inmemoryObject (readonly)

Returns the value of attribute inmemory.



145
146
147
# File 'lib/herdis/shepherd.rb', line 145

def inmemory
  @inmemory
end

#loggerObject (readonly)

Returns the value of attribute logger.



149
150
151
# File 'lib/herdis/shepherd.rb', line 149

def logger
  @logger
end

#mastersObject (readonly)

Returns the value of attribute masters.



153
154
155
# File 'lib/herdis/shepherd.rb', line 153

def masters
  @masters
end

#portObject (readonly)

Returns the value of attribute port.



148
149
150
# File 'lib/herdis/shepherd.rb', line 148

def port
  @port
end

#redisObject (readonly)

Returns the value of attribute redis.



143
144
145
# File 'lib/herdis/shepherd.rb', line 143

def redis
  @redis
end

#redundancyObject (readonly)

Returns the value of attribute redundancy.



147
148
149
# File 'lib/herdis/shepherd.rb', line 147

def redundancy
  @redundancy
end

#shepherd_idObject (readonly)

Returns the value of attribute shepherd_id.



146
147
148
# File 'lib/herdis/shepherd.rb', line 146

def shepherd_id
  @shepherd_id
end

#shepherdsObject (readonly)

Returns the value of attribute shepherds.



155
156
157
# File 'lib/herdis/shepherd.rb', line 155

def shepherds
  @shepherds
end

#shutdownObject (readonly)

Returns the value of attribute shutdown.



151
152
153
# File 'lib/herdis/shepherd.rb', line 151

def shutdown
  @shutdown
end

#slavesObject (readonly)

Returns the value of attribute slaves.



154
155
156
# File 'lib/herdis/shepherd.rb', line 154

def slaves
  @slaves
end

Instance Method Details

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



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

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



291
292
293
294
295
296
297
298
299
300
301
# File 'lib/herdis/shepherd.rb', line 291

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

#backup_ordinalsObject



582
583
584
585
586
587
588
589
590
# File 'lib/herdis/shepherd.rb', line 582

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



592
593
594
595
596
597
598
# File 'lib/herdis/shepherd.rb', line 592

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

#check_predecessorObject



623
624
625
626
627
628
629
630
631
632
633
# File 'lib/herdis/shepherd.rb', line 623

def check_predecessor
  pre = predecessor
  if pre && pre["id"] != shepherd_id
    Fiber.new do
      if EM::HttpRequest.new(pre["url"]).head(:connect_timeout => 10, :inactivity_timeout => 20).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_ready(old_config) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/herdis/shepherd.rb', line 228

def check_ready(old_config)
  shepherds.each do |shepherd_id, shepherd|
    if EM::HttpRequest.new(shepherd["url"]).head.response_header.status != 204
      logger.info("#{self.shepherd_id} *** still waiting for #{shepherd_id}")
      return
    end
  end
  @ready_check_timer.cancel
  old_config["slaves"].each do |shard_id, external_uri|
    create_slave_shard(shard_id.to_s, URI.parse(external_uri))
  end
  old_config["masters"].each do |shard_id|
    create_master_shard(shard_id.to_s)
  end
  logger.info("#{shepherd_id} *** running again")
  logger.info("#{shepherd_id} *** siblings: #{shepherds.keys}")
  logger.info("#{shepherd_id} *** masters: #{masters.keys}")
  logger.info("#{shepherd_id} *** slaves: #{slaves.keys}")
  ensure_slave_check
  ensure_predecessor_check
end

#check_shardsObject



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/herdis/shepherd.rb', line 476

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

  unless masters_needing_to_be_shut_down.empty?
    logger.debug "#{shepherd_id} *** killing masters #{masters_needing_to_be_shut_down.inspect}" 
    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
    save_config!
    remove_shards(shepherd_id, masters_needing_to_be_shut_down, false)
  end      

  unless slaves_needing_to_be_shut_down.empty?
    logger.debug "#{shepherd_id} *** killing slaves #{slaves_needing_to_be_shut_down.inspect}" 
    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
    save_config!
  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



547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/herdis/shepherd.rb', line 547

def check_slaves
  revolution = Set.new
  (owned_shards & slaves.keys).each do |shard_id|
    begin
      shard = slaves[shard_id.to_s]
      if shard.connection.info["master_sync_in_progress"] == "0"
        revolution << shard_id.to_s
      end
    rescue RuntimeError => e
      raise e if e.message != "LOADING Redis is loading the dataset in memory"
    end
  end
  unless revolution.empty?
    logger.debug "#{shepherd_id} *** revolting #{revolution.inspect}"
    add_shards(shepherd_id, revolution.to_a)
  end
end

#cluster_infoObject



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

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",
    "shards" => "#{url}/shards"
  }
end

#cluster_statusObject



421
422
423
# File 'lib/herdis/shepherd.rb', line 421

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

#config_fileObject



224
225
226
# File 'lib/herdis/shepherd.rb', line 224

def config_file
  File.join(dir, "shepherd.json")
end

#create_external_shards(should_be_owned) ⇒ Object



462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/herdis/shepherd.rb', line 462

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



565
566
567
568
# File 'lib/herdis/shepherd.rb', line 565

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

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



640
641
642
643
# File 'lib/herdis/shepherd.rb', line 640

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

#create_slave_shard(shard_id, external_uri) ⇒ Object



635
636
637
638
# File 'lib/herdis/shepherd.rb', line 635

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

#ensure_predecessor_checkObject



258
259
260
261
262
263
264
# File 'lib/herdis/shepherd.rb', line 258

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

#ensure_slave_checkObject



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

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

#join_cluster(url) ⇒ Object



282
283
284
285
286
287
288
289
# File 'lib/herdis/shepherd.rb', line 282

def join_cluster(url)
  shutdown
  @shutdown = false
  logger.info("#{shepherd_id} *** joining #{url}")
  @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



574
575
576
# File 'lib/herdis/shepherd.rb', line 574

def ordered_shepherd_keys
  shepherds.keys.sort
end

#ordinalObject



578
579
580
# File 'lib/herdis/shepherd.rb', line 578

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

#owned_shardsObject



609
610
611
# File 'lib/herdis/shepherd.rb', line 609

def owned_shards
  shards_owned_by(ordinal)
end

#predecessorObject



613
614
615
616
617
618
619
620
621
# File 'lib/herdis/shepherd.rb', line 613

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



329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/herdis/shepherd.rb', line 329

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



303
304
305
306
307
308
309
310
311
312
# File 'lib/herdis/shepherd.rb', line 303

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

#sanityObject



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
# File 'lib/herdis/shepherd.rb', line 374

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

#save_config!Object



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

def save_config!
  tmpfile = "#{config_file}.new"
  open(tmpfile, "w") do |output|
    output.write(Yajl::Encoder.encode({
                                        :shepherd_id => shepherd_id,
                                        :shepherds => shepherds,
                                        :masters => masters.keys,
                                        :slaves => slaves.inject({}) do |sum, id_and_slave| 
                                          sum.merge(id_and_slave.first => id_and_slave.last.master) 
                                        end
                                      }, :pretty => true))
  end
  File.rename(tmpfile, config_file)
end

#shard_statusObject



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/herdis/shepherd.rb', line 405

def shard_status
  rval = []
  cluster_status.each do |shepherd_id, shepherd_status|
    shepherd_url = URI.parse(shepherd_status["url"])
    shepherd_host = shepherd_url.host
    shepherd_status["masters"].each do |shard_id|
      if rval[shard_id.to_i].nil?
        rval[shard_id.to_i] = "redis://#{shepherd_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



600
601
602
603
604
605
606
607
# File 'lib/herdis/shepherd.rb', line 600

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



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

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

#shutdown_clusterObject



439
440
441
442
443
444
# File 'lib/herdis/shepherd.rb', line 439

def shutdown_cluster
  shutdown
  logger.info("#{shepherd_id} *** shutting down cluster")
  to_each_sibling(:adelete,
                  :path => "/cluster")
end

#shutdown_shard(shard_id) ⇒ Object



425
426
427
428
429
430
# File 'lib/herdis/shepherd.rb', line 425

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



432
433
434
435
436
437
# File 'lib/herdis/shepherd.rb', line 432

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

#statusObject



570
571
572
# File 'lib/herdis/shepherd.rb', line 570

def status
  204
end

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



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/herdis/shepherd.rb', line 266

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 if block_given?
  Fiber.new do
    multi.perform while !multi.finished?
  end.resume
end

#urlObject



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

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