Class: Emptyd::Connection

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

Constant Summary collapse

EXPIRE_INTERVAL =

10min

600
MAX_CONNECTIONS =
500
HAPPY_RATIO =
0.5
@@connections =
{}
@@count =
{}
@@dns =
nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, logger) ⇒ Connection

Returns a new instance of Connection.

Raises:

  • (IOError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/emptyd.rb', line 25

def initialize(key, logger)
  raise IOError, "already registered" if @@connections[key]
  @key = key
  @logger = logger
  @sessions = []
  @user, @host = key.split('@', 2)
  @user, @host = "root", @user if @host.nil?
  @@connections[key] = self
  @run_queue = []
  self.start
  @timer = EM::PeriodicTimer.new(rand(5..15)) do
    start
    destroy if old? and free?
  end
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



13
14
15
# File 'lib/emptyd.rb', line 13

def error
  @error
end

#failed_atObject (readonly)

Returns the value of attribute failed_at.



13
14
15
# File 'lib/emptyd.rb', line 13

def failed_at
  @failed_at
end

#keyObject (readonly)

Returns the value of attribute key.



13
14
15
# File 'lib/emptyd.rb', line 13

def key
  @key
end

#updated_atObject (readonly)

Returns the value of attribute updated_at.



13
14
15
# File 'lib/emptyd.rb', line 13

def updated_at
  @updated_at
end

Class Method Details

.[](key, logger) ⇒ Object



21
22
23
# File 'lib/emptyd.rb', line 21

def self.[](key, logger)
  @@connections[key] or Connection.new(key, logger)
end

Instance Method Details

#bind(session) ⇒ Object

Raises:

  • (IOError)


195
196
197
198
# File 'lib/emptyd.rb', line 195

def bind(session)
  raise IOError, "already bound" if @sessions.include? session
  @sessions << session
end

#connecting?Boolean

Returns:

  • (Boolean)


274
275
276
# File 'lib/emptyd.rb', line 274

def connecting?
  @connecting
end

#dead?Boolean

Returns:

  • (Boolean)


278
279
280
# File 'lib/emptyd.rb', line 278

def dead?
  @failed_at
end

#destroyObject

Raises:

  • (IOError)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/emptyd.rb', line 41

def destroy
  raise IOError, "sessions are still alive" unless @sessions.empty?
  @timer.cancel
  @start_timer.cancel if @start_timer
  @@connections.delete @key
  if @conn
    @@count.delete self.key
    conn = @conn
    @conn = nil
    Fiber.new do
      conn.close
    end.resume
  end
  @logger.debug "Destroying connection #{@key}"
end

#errback(err) ⇒ Object



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

def errback err
  @@count.delete self.key
  had_valid_conn = !!@conn
  @conn = nil
  @logger.warn "Connection to #{@key} is broken: #{err}"
  @error = err
  @failed_at = Time.now
  @connecting = false
  if had_valid_conn
    @sessions.each do |session|
      session.queue.push [self, :error, @error]
    end
  else
    @run_queue.each do |cmd,session,callback|
      callback.call self, :error, @error
    end
  end
end

#free?Boolean

Returns:

  • (Boolean)


270
271
272
# File 'lib/emptyd.rb', line 270

def free?
  @sessions.empty?
end

#old?Boolean

Returns:

  • (Boolean)


266
267
268
# File 'lib/emptyd.rb', line 266

def old?
  @updated_at and Time.now - @updated_at > EXPIRE_INTERVAL
end

#run(cmd, session, &callback) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/emptyd.rb', line 206

def run cmd, session, &callback
  unless @conn
    @run_queue << [cmd, session, callback]
    return
  end

  setup = proc do |ch|
    callback.call self, :init, ch

    ch.on_data do |c, data|
      EM.next_tick do
        @updated_at = Time.now
        session.queue.push [@key,nil,data]
      end
    end

    ch.on_extended_data do |c, type, data|
      EM.next_tick do
        @updated_at = Time.now
        session.queue.push [@key,type,data]
        @logger.debug [type,data]
      end
    end

    ch.on_request "exit-status" do |ch, data|
      EM.next_tick do
        @updated_at = Time.now
        session.queue.push [@key,:exit,data.read_long]
      end
    end

    ch.on_close do
      @updated_at = Time.now
      callback.call self, :close
    end

    ch.on_open_failed do |ch, code, desc|
      EM.next_tick do
        callback.call self, :error, desc
      end
    end
  end

  @conn.open_channel do |ch|
    if session.interactive?
      ch.request_pty do |ch, success|
        ch.exec cmd do |ch, success|
          @logger.warn "exec failed: #{cmd}" unless success
          setup[ch]
        end
      end
    else
      ch.exec cmd do |ch, success|
        @logger.warn "exec failed: #{cmd}" unless success
        setup[ch]
      end
    end
  end
end

#startObject



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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
165
166
167
168
169
170
171
172
173
174
# File 'lib/emptyd.rb', line 57

def start
  return if @conn or @connecting
  @connecting = true

  unless @@dns
    @@dns = EM::Udns::Resolver.new
    EM::Udns.run @@dns
  end

  pressure = proc do
    if @@count.size >= MAX_CONNECTIONS # pressure
      c = @@count.select{|k,c| c.free?}.values.sample
      if c
        c.destroy
      else
        @logger.debug "pressure: no free connections: #{@@count.keys}"
      end
    end
  end

  starter = proc do
    begin
      pressure[]
      if @@count.size >= MAX_CONNECTIONS
        @logger.debug "Quota exceeded by #{@key}: #{@@count.size}"
        @start_timer = EM::PeriodicTimer.new(rand(1..10)) do
          pressure[]
          if @@count.size < MAX_CONNECTIONS
            @start_timer.cancel
            EM.next_tick starter
          else
            @logger.debug "No more connection quota, deferring #{@key}..."
          end
        end
      else
        @@count[self.key] = self
        @logger.debug "Created new conn: #{key}, quota = #{@@count.size}"
        options = { :user_known_hosts_file => [], :number_of_password_prompts => 0 }
        options[:password] = $PASSWORD if $PASSWORD
        options[:forward_agent] = true if $FORWARD_AGENT
        EM::Ssh.start(@ip, @user, options) do |conn|
          conn.errback { |err| errback err }
          conn.on(:closed) { errback "closed" }
          conn.callback do |ssh|
            @conn = ssh
            @error = nil
            @failed_at = nil
            @updated_at = Time.now
            @connecting = false
            @run_queue.each do |cmd,session,callback|
              if session.dead?
                @logger.debug "Dropping pending run request from a dead session"
                @error = "session is dead"
              else
                EM.next_tick { run cmd, session, &callback }
              end
            end
            @run_queue.clear
            if @error
              ssh.close
              @@count.delete self.key
            end
          end
        end
      end
    rescue EventMachine::ConnectionError => e
      @@count.delete self.key
      @conn = nil
      @error = e
      @failed_at = Time.now
      @connecting = false
      @run_queue.each do |cmd,session,callback|
        callback.call self, :error
      end
    end
  end

  resolver = nil

  resfail = proc do |err|
    @error = err
    @logger.error "DNS Error: #{err}: #{@key}"
    @failed_at = Time.now
    EM::Timer.new(rand(1..10)) do
      EM.next_tick resolver
    end
  end

  if @host =~ /^[0-9a-f:.]+$/i
    p @host
    resolver = proc do
      @ip = @host
      starter[]
    end
  else
    resolver = proc do
      query = @@dns.submit_AAAA @host
      query.callback do |result|
        @ip = result.sample
        starter[]
      end
      query.errback do |err|
        if err == :dns_error_nodata
          query = @@dns.submit_A @host
          query.callback do |result|
            @ip = result.sample
            starter[]
          end
          query.errback { |err| resfail[err] }
        else
          resfail[err]
        end
      end
    end
  end

  EM.next_tick resolver
end

#unbind(session) ⇒ Object

Raises:

  • (IOError)


200
201
202
203
204
# File 'lib/emptyd.rb', line 200

def unbind(session)
  raise IOError, "not bound" unless @sessions.include? session
  @run_queue.delete_if{|cmd,sess,cb| sess == session}
  @sessions.delete session
end