Class: OsCtl::Lib::NetifStats

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNetifStats

Returns a new instance of NetifStats.



3
4
5
# File 'lib/libosctl/netif_stats.rb', line 3

def initialize
  @cache = {}
end

Instance Attribute Details

#cacheObject (readonly, protected)

Returns the value of attribute cache.



56
57
58
# File 'lib/libosctl/netif_stats.rb', line 56

def cache
  @cache
end

Instance Method Details

#[](netif) ⇒ Object

Read cached stats

Parameters:

  • netif (String)


50
51
52
# File 'lib/libosctl/netif_stats.rb', line 50

def [](netif)
  @cache[netif]
end

#cache_stats_for_interfaces(netifs) ⇒ Object

Parameters:

  • netifs (Array<String>)


36
37
38
39
40
# File 'lib/libosctl/netif_stats.rb', line 36

def cache_stats_for_interfaces(netifs)
  netifs.each do |netif|
    get_stats_for(netif)
  end
end

#get_stats_for(netif) ⇒ Object

Parameters:

  • netif (String)


12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/libosctl/netif_stats.rb', line 12

def get_stats_for(netif)
  @cache[netif] ||= {
    tx: {
      bytes: read_stat(netif, :tx, :bytes),
      packets: read_stat(netif, :tx, :packets)
    },
    rx: {
      bytes: read_stat(netif, :rx, :bytes),
      packets: read_stat(netif, :rx, :packets)
    }
  }
end

#get_stats_for_allObject



25
26
27
28
29
30
31
32
33
# File 'lib/libosctl/netif_stats.rb', line 25

def get_stats_for_all
  ret = {}

  list_netifs.each do |netif|
    ret[netif] = get_stats_for(netif)
  end

  ret
end

#list_netifsObject



42
43
44
45
46
# File 'lib/libosctl/netif_stats.rb', line 42

def list_netifs
  Dir.entries('/sys/class/net').select do |v|
    v != '.' && v != '..' && /^(lo|bond\d+|face|.+\.\d+)$/ !~ v
  end
end

#read_stat(netif, dir, type) ⇒ Object (protected)



58
59
60
61
62
63
# File 'lib/libosctl/netif_stats.rb', line 58

def read_stat(netif, dir, type)
  ret = File.read("/sys/class/net/#{netif}/statistics/#{dir}_#{type}")
  ret.strip.to_i
rescue SystemCallError
  0
end

#resetObject



7
8
9
# File 'lib/libosctl/netif_stats.rb', line 7

def reset
  cache.clear
end