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.



53
54
55
# File 'lib/libosctl/netif_stats.rb', line 53

def cache
  @cache
end

Instance Method Details

#[](netif) ⇒ Object

Read cached stats

Parameters:

  • netif (String)


48
49
50
# File 'lib/libosctl/netif_stats.rb', line 48

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
# File 'lib/libosctl/netif_stats.rb', line 42

def list_netifs
  Dir.entries('/sys/class/net') - %w(. ..)
end

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



55
56
57
58
59
60
61
# File 'lib/libosctl/netif_stats.rb', line 55

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