Class: CadvisorInput

Inherits:
Fluent::Input
  • Object
show all
Defined in:
lib/fluent/plugin/in_cadvisor.rb

Defined Under Namespace

Classes: TimerWatcher

Instance Method Summary collapse

Constructor Details

#initializeCadvisorInput

Returns a new instance of CadvisorInput.



28
29
30
31
32
33
# File 'lib/fluent/plugin/in_cadvisor.rb', line 28

def initialize
  super
  require 'socket'
  @hostname = Socket.gethostname
  @dict     = {}
end

Instance Method Details

#configure(conf) ⇒ Object



35
36
37
# File 'lib/fluent/plugin/in_cadvisor.rb', line 35

def configure(conf)
  super
end

#emit_container_info(obj) ⇒ Object



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
# File 'lib/fluent/plugin/in_cadvisor.rb', line 102

def emit_container_info(obj)
  id = obj[:id]
  response = RestClient.get(@cadvisorEP + "/containers/docker/" + id)
  res = JSON.parse(response.body)

  # Set max memory
  memory_limit = @machine['memory_capacity'] < res['spec']['memory']['limit'] ? @machine['memory_capacity'] : res['spec']['memory']['limit']

  latest_timestamp = @dict[id] ||= 0

  # Remove already sent elements
  res['stats'].reject! do | stats |
    Time.parse(stats['timestamp']).to_i <= latest_timestamp
  end

  res['stats'].each_with_index do | stats, index |
    timestamp = Time.parse(stats['timestamp']).to_i
    # Break on last element
    # We need 2 elements to create the percentage, in this case the prev will be
    # out of the array
    if index == (res['stats'].count - 1)
      @dict[id] = timestamp
      break
    end

    num_cores = stats['cpu']['usage']['per_cpu_usage'].count

    # CPU percentage variables
    prev           = res['stats'][index + 1];
    raw_usage      = stats['cpu']['usage']['total'] - prev['cpu']['usage']['total']
    interval_in_ns = get_interval(stats['timestamp'], prev['timestamp'])

    record = {
      'container_id'       => id,
      'image'              => obj[:name],
      'memory_current'     => stats['memory']['usage'],
      'memory_limit'       => memory_limit,
      'cpu_usage'          => raw_usage,
      'cpu_usage_pct'      => (((raw_usage / interval_in_ns ) / num_cores ) * 100).round(2),
      'cpu_num_cores'      => num_cores,
      'network_rx_bytes'   => stats['network']['rx_bytes'],
      'network_rx_packets' => stats['network']['rx_packets'],
      'network_rx_errors'  => stats['network']['rx_errors'],
      'network_rx_dropped' => stats['network']['rx_dropped'],
      'network_tx_bytes'   => stats['network']['tx_bytes'],
      'network_tx_packets' => stats['network']['tx_packets'],
      'network_tx_errors'  => stats['network']['tx_errors'],
      'network_tx_dropped' => stats['network']['tx_dropped'],
    }

    Fluent::Engine.emit("stats", timestamp, record)
  end
end

#get_interval(current, previous) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/fluent/plugin/in_cadvisor.rb', line 56

def get_interval (current, previous)
  cur  = Time.parse(current).to_f
  prev = Time.parse(previous).to_f

  # to nano seconds
  (cur - prev) * 1000000000
end

#get_metricsObject

Metrics collection methods



70
71
72
73
74
# File 'lib/fluent/plugin/in_cadvisor.rb', line 70

def get_metrics
  list_container_ids.each do |obj|
    emit_container_info(obj)
  end
end

#get_specObject



64
65
66
67
# File 'lib/fluent/plugin/in_cadvisor.rb', line 64

def get_spec
  response = RestClient.get(@cadvisorEP + "/machine")
  JSON.parse(response.body)
end

#list_container_idsObject



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
# File 'lib/fluent/plugin/in_cadvisor.rb', line 76

def list_container_ids
  socket_path = "/var/run/docker.sock"
  if File.exists?(socket_path)
    socket = Socket.unix(socket_path)
    socket.puts("GET /containers/json HTTP/1.0\n\r")

    res = socket.readlines
    socket.close

    # Find body position
    idx = -1
    res.to_a.each_with_index do | stats, index |
      if stats[0] == '['
        idx = index
        break;
      end
    end

    #Remove HTTP Headers and parse the body
    jsn = JSON.parse(res.to_a[idx..-1].join)
    jsn.collect { |obj| {:id => obj['Id'], :name => obj['Image']} }
  else
    []
  end
end

#runObject



49
50
51
52
53
54
# File 'lib/fluent/plugin/in_cadvisor.rb', line 49

def run
  @loop.run
rescue
  log.error "unexpected error", :error=>$!.to_s
  log.error_backtrace
end

#shutdownObject



156
157
158
159
# File 'lib/fluent/plugin/in_cadvisor.rb', line 156

def shutdown
  @loop.stop
  @thread.join
end

#startObject



39
40
41
42
43
44
45
46
47
# File 'lib/fluent/plugin/in_cadvisor.rb', line 39

def start
  @cadvisorEP ||= "http://#{@host}:#{@port}/api/v#{@api_version}"
  @machine    ||= get_spec

  @loop = Coolio::Loop.new
  tw = TimerWatcher.new(@stats_interval, true, @log, &method(:get_metrics))
  tw.attach(@loop)
  @thread = Thread.new(&method(:run))
end