Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created January 18, 2018 00:45
Show Gist options
  • Save SegFaultAX/76f9f1896e00d8a6b8ea68185286d778 to your computer and use it in GitHub Desktop.
Save SegFaultAX/76f9f1896e00d8a6b8ea68185286d778 to your computer and use it in GitHub Desktop.
Parse Graphite creates log and render as a tree [Ruby]
class Node
attr_reader :name
def initialize(name)
@name = name
@children = []
end
def children
@children.dup.freeze
end
def insert_path(path)
return if path.empty?
insert_child(path[0]).insert_path(path[1..-1])
end
def insert_child(name)
c = child(name)
if c.nil?
c = Node.new(name)
@children << c
end
c
end
def child(name)
@children.find { |c| c.name == name }
end
def has_child?(name)
!child(name).nil?
end
def child_count
@children.size
end
def descendants_count
@children.map(&:descendants_count).reduce(child_count, &:+)
end
def to_s
"Node(#{name}, [#{children.join(", ")}])"
end
def draw(maxdepth=999, indent=0)
return if maxdepth <= 0
puts("#{" " * indent}#{name} (c:#{child_count}/d:#{descendants_count})")
children
.select { |c| c.descendants_count >= 100 }
.sort_by { |c| [-c.descendants_count, c.name] }
.each { |c| c.draw(maxdepth - 1, indent + 2) }
end
end
root = Node.new(".")
File.foreach("metrics.log") do |line|
return if line.strip.empty?
root.insert_path(line.strip.split("."))
end
root.draw(6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment