Class: StorageVisualizer
- Inherits:
-
Object
- Object
- StorageVisualizer
- Defined in:
- lib/storage_visualizer.rb
Instance Attribute Summary collapse
-
#available ⇒ Object
Returns the value of attribute available.
-
#available_gb ⇒ Object
Returns the value of attribute available_gb.
-
#capacity ⇒ Object
disk Bytes.
-
#capacity_gb ⇒ Object
disk GB for display.
-
#dir_tree ⇒ Object
this is the root DirNode object.
-
#diskhash ⇒ Object
Returns the value of attribute diskhash.
-
#dupe_counter ⇒ Object
Returns the value of attribute dupe_counter.
-
#target_dir ⇒ Object
other.
-
#target_volume ⇒ Object
Returns the value of attribute target_volume.
-
#threshold_pct ⇒ Object
Returns the value of attribute threshold_pct.
-
#tree ⇒ Object
Returns the value of attribute tree.
-
#tree_formatted ⇒ Object
Returns the value of attribute tree_formatted.
-
#used ⇒ Object
Returns the value of attribute used.
-
#used_gb ⇒ Object
Returns the value of attribute used_gb.
Class Method Summary collapse
Instance Method Summary collapse
-
#analyze_dirs(dir_to_analyze, parent) ⇒ Object
Crawl the dirs recursively, beginning with the target dir.
- #format_data_for_the_chart ⇒ Object
- #get_basic_disk_info ⇒ Object
-
#initialize(target_dir_passed = nil) ⇒ StorageVisualizer
constructor
Constructor.
- #run ⇒ Object
- #traverse_tree_and_remove_duplicates ⇒ Object
- #write_storage_report ⇒ Object
Constructor Details
#initialize(target_dir_passed = nil) ⇒ StorageVisualizer
Constructor
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/storage_visualizer.rb', line 143 def initialize(target_dir_passed = nil) if (target_dir_passed != nil) = File.(target_dir_passed) # puts "Target dir: #{expanded}" if (Dir.exist?()) self.target_dir = else raise "Target directory does not exist: #{}" end else # no target passed, use the user's home dir self.target_dir = File.('~') end # how much space is considered worthy of noting on the chart self.threshold_pct = 0.05 self.diskhash = {} self.tree = [] self.tree_formatted = '' self.dupe_counter = 0 end |
Instance Attribute Details
#available ⇒ Object
Returns the value of attribute available.
125 126 127 |
# File 'lib/storage_visualizer.rb', line 125 def available @available end |
#available_gb ⇒ Object
Returns the value of attribute available_gb.
129 130 131 |
# File 'lib/storage_visualizer.rb', line 129 def available_gb @available_gb end |
#capacity ⇒ Object
disk Bytes
123 124 125 |
# File 'lib/storage_visualizer.rb', line 123 def capacity @capacity end |
#capacity_gb ⇒ Object
disk GB for display
127 128 129 |
# File 'lib/storage_visualizer.rb', line 127 def capacity_gb @capacity_gb end |
#dir_tree ⇒ Object
this is the root DirNode object
140 141 142 |
# File 'lib/storage_visualizer.rb', line 140 def dir_tree @dir_tree end |
#diskhash ⇒ Object
Returns the value of attribute diskhash.
134 135 136 |
# File 'lib/storage_visualizer.rb', line 134 def diskhash @diskhash end |
#dupe_counter ⇒ Object
Returns the value of attribute dupe_counter.
137 138 139 |
# File 'lib/storage_visualizer.rb', line 137 def dupe_counter @dupe_counter end |
#target_dir ⇒ Object
other
131 132 133 |
# File 'lib/storage_visualizer.rb', line 131 def target_dir @target_dir end |
#target_volume ⇒ Object
Returns the value of attribute target_volume.
136 137 138 |
# File 'lib/storage_visualizer.rb', line 136 def target_volume @target_volume end |
#threshold_pct ⇒ Object
Returns the value of attribute threshold_pct.
135 136 137 |
# File 'lib/storage_visualizer.rb', line 135 def threshold_pct @threshold_pct end |
#tree ⇒ Object
Returns the value of attribute tree.
132 133 134 |
# File 'lib/storage_visualizer.rb', line 132 def tree @tree end |
#tree_formatted ⇒ Object
Returns the value of attribute tree_formatted.
133 134 135 |
# File 'lib/storage_visualizer.rb', line 133 def tree_formatted @tree_formatted end |
#used ⇒ Object
Returns the value of attribute used.
124 125 126 |
# File 'lib/storage_visualizer.rb', line 124 def used @used end |
#used_gb ⇒ Object
Returns the value of attribute used_gb.
128 129 130 |
# File 'lib/storage_visualizer.rb', line 128 def used_gb @used_gb end |
Class Method Details
.install ⇒ Object
66 67 68 69 70 71 72 73 74 75 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 101 102 103 104 105 106 107 108 |
# File 'lib/storage_visualizer.rb', line 66 def self.install # This function installs a copy & symlink into /usr/local/bin, so the utility can simply be run by typing `storage_visualizer` # To install for command line use type: # git clone https://github.com/teecay/StorageVisualizer.git && ./StorageVisualizer/storage_visualizer.rb --install # To install for gem usage type: # gem install storage_visualizer script_src_path = File.(__FILE__) # File.expand_path('./StorageVisualizer/lib/storage_visualizer.rb') script_dest_path = '/usr/local/bin/storage_visualizer.rb' symlink_path = '/usr/local/bin/storage_visualizer' if (!File.exist?(script_src_path)) raise "Error: file does not exist: #{script_src_path}" end if (File.exist?(script_dest_path)) puts "Removing old installed script" File.delete(script_dest_path) end if (File.exist?(symlink_path)) puts "Removing old symlink" File.delete(symlink_path) end cp_cmd = "cp -f #{script_src_path} #{script_dest_path}" puts "Copying script into place: #{cp_cmd}" `#{cp_cmd}` ln_cmd = "ln -s #{script_dest_path} #{symlink_path}" puts "Installing: #{ln_cmd}" `#{ln_cmd}` chmod_cmd = "chmod ugo+x #{symlink_path}" puts "Setting permissions: #{chmod_cmd}" `#{chmod_cmd}` puts "Installation is complete, run `storage_visualizer -h` for help" end |
.print_usage ⇒ Object
Static
51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/storage_visualizer.rb', line 51 def self.print_usage puts "\nThis tool helps visualize which directories are occupying the most storage. Any directory that occupies more than 5% of disk space is added to a visual hierarchichal storage report in the form of a Google Sankey diagram. The storage data is gathered using the linux `du` utility. It has been tested on Mac OSX, should work on linux systems, will not work on Windows. Run as sudo if analyzing otherwise inaccessible directories. May take a while to run\n" puts "\nCommand line usage: \n\t[sudo] storage_visualizer[.rb] [directory to visualize (default ~/) | -h (help) -i | --install (install to /usr/local/bin)]\n\n" puts "API usage: " puts "\tgem install storage_visualizer" puts "\t'require storage_visualizer'" puts "\tsv = StorageVisualizer.new('[directory to visualize, ~/ by default]')" puts "\tsv.run()\n\n" puts "A report will be created in the current directory named as such: StorageReport_2015_05_25-17_19_30.html" puts "Status messages are printed to STDOUT" puts "\n\n" end |
Instance Method Details
#analyze_dirs(dir_to_analyze, parent) ⇒ Object
Crawl the dirs recursively, beginning with the target dir
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 |
# File 'lib/storage_visualizer.rb', line 393 def analyze_dirs(dir_to_analyze, parent) # bootstrap case # don't create an entry for the root because there's nothing to link to yet, scan the subdirs if (dir_to_analyze == self.target_volume) # puts "Dir to analyze is the target volume" # run on all child dirs, not this dir Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name| # puts "\tentry: >#{file}<" full_path = File.join(dir_to_analyze, name) if (Dir.exist?(full_path) && !File.symlink?(full_path)) # puts "Contender: >#{full_path}<" analyze_dirs(full_path, self.dir_tree) end end return end # use "P" to help prevent following any symlinks cmd = "du -sxkP \"#{dir_to_analyze}\"" puts "\trunning #{cmd}" output = `#{cmd}`.strip().split("\t") # puts "Du output:" # pp output size = output[0].to_i size_gb = "#{'%.0f' % (size.to_f / 1024 / 1024)}" # puts "Size: #{size}\nCapacity: #{self.diskhash['/']['capacity']}" # Occupancy as a fraction of total space # occupancy = (size.to_f / self.capacity.to_f) # Occupancy as a fraction of USED space occupancy = (size.to_f / self.used.to_f) occupancy_pct = "#{'%.0f' % (occupancy * 100)}" capacity_gb = "#{'%.0f' % (self.capacity.to_f / 1024 / 1024)}" # if this dir contains more than 5% of disk space, add it to the tree if (dir_to_analyze == self.target_dir) # puts "Dir to analyze is the target dir, space used outside this dir.." # account for space used outside of target dir other_space = self.used - size other_space_gb = "#{'%.0f' % (other_space / 1024 / 1024)}" parent.children.push(DirNode.new(parent, self.target_volume, 'Other Space', other_space_gb)) end if (occupancy > self.threshold_pct) # puts "Dir contains more than 5% of disk space: #{dir_to_analyze} \n\tsize:\t#{size_gb} / \ncapacity:\t#{capacity_gb} = #{occupancy_pct}%" puts "Dir contains more than 5% of used disk space: #{dir_to_analyze} \n\tsize:\t\t#{size_gb} / \n\toccupancy:\t#{self.used_gb} = #{occupancy_pct}% of used space" # puts "Dir to analyze (#{dir_to_analyze}) is not the target dir (#{self.target_dir})" dirs = dir_to_analyze.split('/') short_dir = dirs.pop().gsub("'","\\\\'") full_parent = dirs.join('/') if (dir_to_analyze == self.target_dir || full_parent == self.target_volume) # puts "Either this dir is the target dir, or the parent is the target volume, make parent the full target volume" short_parent = self.target_volume.gsub("'","\\\\'") else # puts "Neither this dir or parent is the target dir, making parent short" short_parent = dirs.pop().gsub("'","\\\\'") end this_node = DirNode.new(parent, dir_to_analyze, short_dir, size_gb) parent.children.push(this_node) # run on all child dirs Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name| full_path = File.join(dir_to_analyze, name) # don't follow any symlinks if (Dir.exist?(full_path) && !File.symlink?(full_path)) # puts "Contender: >#{full_path}<" analyze_dirs(full_path, this_node) end end end # occupancy > threshold end |
#format_data_for_the_chart ⇒ Object
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
# File 'lib/storage_visualizer.rb', line 168 def format_data_for_the_chart # Build the list of nodes nodes = [] nodes.push(self.dir_tree) comparison_list = [] while true if (nodes.length == 0) break end node = nodes.shift comparison_list.push(node) nodes.concat(node.children) end # format the data for the chart working_string = "[\n" comparison_list.each_with_index do |entry, index| if (entry.parent == nil) next end if(index == comparison_list.length - 1) # this is the next to last element, it gets no comma working_string << "[ '#{entry.parent.dir_short}', '#{entry.dir_short}', #{entry.size_gb} ]\n" else # mind the comma working_string << "[ '#{entry.parent.dir_short}', '#{entry.dir_short}', #{entry.size_gb} ],\n" end end working_string << "]\n" self.tree_formatted = working_string end |
#get_basic_disk_info ⇒ Object
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
# File 'lib/storage_visualizer.rb', line 294 def get_basic_disk_info # df -l gets info about locally-mounted filesystems output = `df -k` # OSX: # Filesystem 1024-blocks Used Available Capacity iused ifree %iused Mounted on # /dev/disk1 975912960 349150592 626506368 36% 87351646 156626592 36% / # localhost:/QwnJE6UBvlR1EvqouX6gMM 975912960 975912960 0 100% 0 0 100% /Volumes/MobileBackups # CentOS: # Filesystem 1K-blocks Used Available Use% Mounted on # /dev/xvda1 82436764 3447996 78888520 5% / # devtmpfs 15434608 56 15434552 1% /dev # tmpfs 15443804 0 15443804 0% /dev/shm # Ubuntu: # Filesystem 1K-blocks Used Available Use% Mounted on # /dev/xvda1 30832636 797568 28676532 3% / # none 4 0 4 0% /sys/fs/cgroup # udev 3835900 12 3835888 1% /dev # tmpfs 769376 188 769188 1% /run # none 5120 0 5120 0% /run/lock # none 3846876 0 3846876 0% /run/shm # none 102400 0 102400 0% /run/user # /dev/xvdb 30824956 45124 29207352 1% /mnt # Populate disk info into a hash of hashes # {"/"=> # {"capacity"=>498876809216, "used"=>434777001984, "available"=>63837663232}, # "/Volumes/MobileBackups"=> # {"capacity"=>498876809216, "used"=>498876809216, "available"=>0} # } # get each mount's capacity & utilization output.lines.each_with_index do |line, index| if (index == 0) # skip the header line next end cols = line.split # ["Filesystem", "1024-blocks", "Used", "Available", "Capacity", "iused", "ifree", "%iused", "Mounted", "on"] # line: ["/dev/disk1", "974368768", "849157528", "124699240", "88%", "106208689", "15587405", "87%", "/"] if cols.length == 9 # OSX self.diskhash[cols[8]] = { 'capacity' => (cols[1].to_i ).to_i, 'used' => (cols[2].to_i ).to_i, 'available' => (cols[3].to_i ).to_i } elsif cols.length == 6 # Ubuntu & CentOS self.diskhash[cols[5]] = { 'capacity' => (cols[1].to_i ).to_i, 'used' => (cols[2].to_i ).to_i, 'available' => (cols[3].to_i ).to_i } else raise "Reported disk utilization not understood" end end # puts "Disk mount info:" # pp diskhash # find the (self.)target_volume # look through diskhash keys, to find the one that most matches target_dir val_of_min = 1000 # puts "Determining which volume contains the target directory.." self.diskhash.keys.each do |volume| result = self.target_dir.gsub(volume, '') diskhash['match_amt'] = result.length # puts "Considering:\t#{volume}, \t closeness: #{result.length}, \t (#{result})" if (result.length < val_of_min) # puts "Candidate: #{volume}" val_of_min = result.length self.target_volume = volume end end puts "Target volume is #{self.target_volume}" self.capacity = self.diskhash[self.target_volume]['capacity'] self.used = self.diskhash[self.target_volume]['used'] self.available = self.diskhash[self.target_volume]['available'] self.capacity_gb = "#{'%.0f' % (self.capacity.to_i / 1024 / 1024)}" self.used_gb = "#{'%.0f' % (self.used.to_i / 1024 / 1024)}" self.available_gb = "#{'%.0f' % (self.available.to_i / 1024 / 1024)}" self.dir_tree = DirNode.new(nil, self.target_volume, self.target_volume, self.capacity) self.dir_tree.children.push(DirNode.new(self.dir_tree, 'Free Space', 'Free Space', self.available_gb)) end |
#run ⇒ Object
519 520 521 522 523 524 525 526 |
# File 'lib/storage_visualizer.rb', line 519 def run self.get_basic_disk_info self.analyze_dirs(self.target_dir, self.dir_tree) self.traverse_tree_and_remove_duplicates self.format_data_for_the_chart self.write_storage_report end |
#traverse_tree_and_remove_duplicates ⇒ Object
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/storage_visualizer.rb', line 479 def traverse_tree_and_remove_duplicates puts "\nHandling duplicate entries.." nodes = [] nodes.push(self.dir_tree) comparison_list = [] while true if (nodes.length == 0) break end node = nodes.shift comparison_list.push(node) # pp node if node.parent == nil # puts "\tparent: no parent \n\tdir: #{node.dir_name} \n\tshort: #{node.dir_short} \n\tsize: #{node.size_gb}" else # puts "\tparent: #{node.parent.dir_short.to_s} \n\tdir: #{node.dir_name} \n\tshort: #{node.dir_short} \n\tsize: #{node.size_gb}" end nodes.concat(node.children) end # puts "Done building node list" for i in 0..comparison_list.length do for j in 0..comparison_list.length do if (comparison_list[i] != nil && comparison_list[j] != nil) if (i != j && comparison_list[i].dir_short == comparison_list[j].dir_short) puts "\t#{comparison_list[i].dir_short} is the same as #{comparison_list[j].dir_short}, changing to #{comparison_list[j].dir_short}*" comparison_list[j].dir_short = "#{comparison_list[j].dir_short}*" end end end end puts "Duplicate handling complete" end |
#write_storage_report ⇒ Object
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
# File 'lib/storage_visualizer.rb', line 205 def write_storage_report the_html = %q|<html> <body> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['sankey']}]}"> </script> <style> td { font-family:sans-serif; font-size:8pt; } .bigger { font-family:sans-serif; font-size:10pt; font-weight:bold } </style> <div class="table"> <div class="bigger">Storage Report</div> <table> <tr> <td style="text-align:right">Disk Capacity:</td><td>| + self.capacity_gb + %q| GB</td> </tr> <tr> <td style="text-align:right">Disk Used:</td><td>| + self.used_gb + %q| GB</td> </tr> <tr> <td style="text-align:right">Free Space:</td><td>| + self.available_gb + %q| GB</td> </tr> </table> </div> <div id="sankey_multiple" style="width: 900px; height: 300px;"></div> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'From'); data.addColumn('string', 'To'); data.addColumn('number', 'Size (GB)'); data.addRows( | + self.tree_formatted + %q|); // Set chart options var options = { width: 1000, sankey: { iterations: 32, node: { label: { fontName: 'Arial', fontSize: 10, color: '#871b47', bold: false, italic: true } } }, }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.Sankey(document.getElementById('sankey_multiple')); chart.draw(data, options); } </script> </body> </html>| filename = DateTime.now.strftime("./StorageReport_%Y_%m_%d-%H_%M_%S.html") puts "Writing html file #{filename}" f = File.open(filename, 'w+') f.write(the_html) f.close end |