lib/fluent/plugin/in_cadvisor.rb in fluent-plugin-cadvisor-0.2.5 vs lib/fluent/plugin/in_cadvisor.rb in fluent-plugin-cadvisor-0.3.0

- old
+ new

@@ -1,8 +1,9 @@ require 'rest-client' require 'digest/sha1' require 'time' +require 'docker' class CadvisorInput < Fluent::Input class TimerWatcher < Coolio::TimerWatcher def initialize(interval, repeat, log, &callback) @@ -23,14 +24,17 @@ config_param :host, :string, :default => 'localhost' config_param :port, :string, :default => 8080 config_param :api_version, :string, :default => '1.1' config_param :stats_interval, :time, :default => 60 # every minute config_param :tag_prefix, :string, :default => "metric" + config_param :docker_url, :string, :default => 'unix:///var/run/docker.sock' def initialize super require 'socket' + + Docker.url = @docker_url @hostname = Socket.gethostname @dict = {} end def configure(conf) @@ -67,43 +71,23 @@ JSON.parse(response.body) end # Metrics collection methods def get_metrics - list_container_ids.each do |obj| + Docker::Container.all.each do |obj| emit_container_info(obj) end end - 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") + def emit_container_info(obj) + container_json = obj.json + config = container_json['Config'] - res = socket.readlines - socket.close + id = container_json['Id'] + name = container_json['Image'] + env = config['Hostname'].split('--')[2] || '' # app--version--env - # 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 - - 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'] @@ -131,12 +115,13 @@ 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 = { - 'id' => Digest::SHA1.hexdigest("#{obj[:name]}#{id}#{timestamp.to_s}"), + 'id' => Digest::SHA1.hexdigest("#{name}#{id}#{timestamp.to_s}"), 'container_id' => id, - 'image' => obj[:name], + 'image' => name, + 'environment' => env, '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,