class Flare::Util::Bwlimit

Description

Constants

Bit
Byte
DefaultBandwidth
Gi
Ki
Mi

Public Class Methods

bps(bw) click to toggle source
# File lib/flare/util/bwlimit.rb, line 102
def self.bps(bw)
  return 0 if bw.nil?
  case bw
  when /^(\d+)$/
    $1.to_i*Bit
  when /^(\d+)B$/
    $1.to_i*Byte
  when /^(\d+)k$/
    $1.to_i*Ki*Bit
  when /^(\d+)kB$/
    $1.to_i*Ki*Byte
  when /^(\d+)M$/
    $1.to_i*Mi*Bit
  when /^(\d+)MB$/
    $1.to_i*Mi*Byte
  when /^(\d+)G$/
    $1.to_i*Gi*Bit
  when /^(\d+)GB$/
    $1.to_i*Gi*Byte
  else
    bw.to_i
  end
end
new(bwlimit) click to toggle source
# File lib/flare/util/bwlimit.rb, line 23
def initialize(bwlimit)
  @limit = Bwlimit.bps(bwlimit)
  @basetime = @starttime = Time.now
  @duration = 1.0
  @history = []
  @minwait = 0.01
  @speed = 0
  @bytes = 0
  @totalbytes = 0
  @thresh = 1*Ki
end

Public Instance Methods

bps() click to toggle source
# File lib/flare/util/bwlimit.rb, line 43
def bps
  @limit
end
history() click to toggle source
# File lib/flare/util/bwlimit.rb, line 90
def history
  @history.dup
end
inc(bytes) click to toggle source
# File lib/flare/util/bwlimit.rb, line 51
def inc(bytes)
  @bytes += bytes
  @totalbytes += bytes
end
limit() click to toggle source
# File lib/flare/util/bwlimit.rb, line 39
def limit
  @limit
end
limit=(bwlimit) click to toggle source
# File lib/flare/util/bwlimit.rb, line 35
def limit=(bwlimit)
  @limit = Bwlimit.bps(bwlimit)
end
pasttime(now = Time.now) click to toggle source
# File lib/flare/util/bwlimit.rb, line 69
def pasttime(now = Time.now)
  now-@basetime
end
reset() click to toggle source
# File lib/flare/util/bwlimit.rb, line 47
def reset
  @basetime = @starttime = Time.now
end
speed() click to toggle source
# File lib/flare/util/bwlimit.rb, line 94
def speed
  @speed
end
time_to_wait(now = Time.now) click to toggle source
# File lib/flare/util/bwlimit.rb, line 56
def time_to_wait(now = Time.now)
  waitsec = 0
  limit = @limit/Byte
  allowed = (now-@basetime)*limit
  if @bytes > allowed
    waitsec = ((@bytes-allowed).to_f/limit)
  end
  unless waitsec > 0
    waitsec = @minwait if waitsec < @minwait
  end
  waitsec
end
totalbytes() click to toggle source
# File lib/flare/util/bwlimit.rb, line 98
def totalbytes
  @totalbytes
end
wait() click to toggle source
# File lib/flare/util/bwlimit.rb, line 73
def wait
  waitsec = 0
  if @limit > 0 && @bytes > @thresh
    now = Time.now
    sleep time_to_wait(now)
    diff = pasttime(now)
    if diff > @duration
      @speed = @bytes*Byte/diff
      debug "#{@speed} bps"
      @bytes = 0
      @basetime = now
      @history << {:time => now-@starttime, :speed => @speed}
    end
  end
  waitsec
end