Class: LS4::BasicHADB

Inherits:
Object
  • Object
show all
Defined in:
lib/ls4/service/mds_ha.rb

Overview

single node:

host1:port1

master-slave:

host1:port1,host2:port2

master-slave with read weight:

host1:port1,host2:port2;0,1

dual-master:

host1:port1--host2:port2

Constant Summary collapse

DEFAULT_WEIGHT =
10

Instance Method Summary collapse

Constructor Details

#initialize(expr) ⇒ BasicHADB

Returns a new instance of BasicHADB.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/ls4/service/mds_ha.rb', line 37

def initialize(expr)
  @dbmap = {}    # {Address => DB}
  @writers = []   # [Address]
  @readers = []   # [Address]
  @readers_rr = 0

  expr.split('--').each {|line|
    nodes, weights = line.strip.split(';',2)

    addrs = nodes.strip.split(',').map {|addr|
      parse_addr(addr)
    }

    weights = (weights||"").strip.split(',').map {|x| x.to_i }

    @writers << addrs.first

    addrs.each_with_index {|addr,i|
      weight = weights[i] ||= DEFAULT_WEIGHT
      weight.times {
        @readers << addr
      }
      @dbmap[addr] = nil
    }

    $log.info "MDS -- #{addrs.join(',')};#{weights.join(',')}"
  }

  if @dbmap.empty?
    raise "empty expression"
  end

  if @dbmap.size == 1
    # single node
    @readers = [@readers[0]]
  else
    @readers = @readers.sort_by {|addr| rand }
  end

  # open remote database
  @dbmap.keys.each {|addr|
    @dbmap[addr] = open_db(addr)
  }

rescue
  @dbmap.each_pair {|addr,db|
    if db
      close_db(db) rescue nil
    end
  }
  $log.error $!
  $log.error_backtrace $!.backtrace
  raise "MDS: invlaid address expression: #{$!}"
end

Instance Method Details

#closeObject



111
112
113
114
115
# File 'lib/ls4/service/mds_ha.rb', line 111

def close
  @dbmap.each_pair {|addr,db|
    close_db(db) rescue nil
  }
end

#read(shard_key, &block) ⇒ Object



103
104
105
106
107
108
109
# File 'lib/ls4/service/mds_ha.rb', line 103

def read(shard_key, &block)
  @readers_rr += 1
  @readers_rr = 0 if @readers_rr >= @readers.size
  ha_call(@readers, @readers_rr) {|db|
    block.call(db)
  }
end

#write(shard_key, &block) ⇒ Object



92
93
94
95
96
97
98
99
100
101
# File 'lib/ls4/service/mds_ha.rb', line 92

def write(shard_key, &block)
  if @writers.size == 1
    n = 0
  else
    n = hash_key(shard_key) % @writers.size
  end
  ha_call(@writers, n) {|db|
    block.call(db)
  }
end