Last active
April 15, 2019 03:34
-
-
Save david-zw-liu/c7b9c257e586f06dd5f1b29ab038ecb2 to your computer and use it in GitHub Desktop.
Docker stats with image name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'open3' | |
class String | |
def truncate(max, omission: '') | |
length > max ? "#{self[0...max - omission.length]}#{omission}" : self | |
end | |
end | |
COLUMN_WIDTH = 30 | |
id2name = {} | |
header = 'IMAGE NAME'.ljust(COLUMN_WIDTH).freeze | |
Thread.new do | |
while true | |
_, stdout = Open3.popen2('docker ps --format "{{.ID}}\t{{.Image}}"') | |
stdout.each_line do |line| | |
container_id, image_name = line.chomp.split("\t") | |
id2name[container_id] = image_name | |
end | |
sleep 0.5 | |
end | |
end | |
Open3.popen3('docker stats') do |stdin, stdout, stderr, wait_thr| | |
stdout.each_line do |line| | |
matched = line.to_s.match(/^(?<container_id>[a-z0-9]+)\s+/) | |
if matched | |
container_id = matched[:container_id] | |
image_name = id2name[container_id] || "Not Found" | |
optimized_image_name = image_name.truncate(COLUMN_WIDTH - 1, omission: '...').ljust(COLUMN_WIDTH) | |
puts "#{optimized_image_name}#{line}" | |
else | |
line.gsub!('CONTAINER ID', "#{header}CONTAINER ID") | |
puts line | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment