Class: StorageVisualizer

Inherits:
Object
  • Object
show all
Defined in:
lib/storage_visualizer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target_dir_passed = nil) ⇒ StorageVisualizer

Constructor



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/storage_visualizer.rb', line 115

def initialize(target_dir_passed = nil)

  if (target_dir_passed != nil)
    expanded = File.expand_path(target_dir_passed)
    puts "Target dir: #{expanded}"
    if (Dir.exist?(expanded))
      self.target_dir = expanded
    else
      raise "Target directory does not exist: #{expanded}"
    end
  else
    # no target passed, use the user's home dir
    self.target_dir = File.expand_path('~')
  end
  
  
  self.threshold_pct = 0.05
  self.diskhash = {}
  self.tree = []
  self.tree_formatted = ''
end

Instance Attribute Details

#availableObject

Returns the value of attribute available.



102
103
104
# File 'lib/storage_visualizer.rb', line 102

def available
  @available
end

#available_gbObject

Returns the value of attribute available_gb.



106
107
108
# File 'lib/storage_visualizer.rb', line 106

def available_gb
  @available_gb
end

#capacityObject

disk Bytes



100
101
102
# File 'lib/storage_visualizer.rb', line 100

def capacity
  @capacity
end

#capacity_gbObject

disk GB for display



104
105
106
# File 'lib/storage_visualizer.rb', line 104

def capacity_gb
  @capacity_gb
end

#diskhashObject

Returns the value of attribute diskhash.



111
112
113
# File 'lib/storage_visualizer.rb', line 111

def diskhash
  @diskhash
end

#target_dirObject

other



108
109
110
# File 'lib/storage_visualizer.rb', line 108

def target_dir
  @target_dir
end

#threshold_pctObject

Returns the value of attribute threshold_pct.



112
113
114
# File 'lib/storage_visualizer.rb', line 112

def threshold_pct
  @threshold_pct
end

#treeObject

Returns the value of attribute tree.



109
110
111
# File 'lib/storage_visualizer.rb', line 109

def tree
  @tree
end

#tree_formattedObject

Returns the value of attribute tree_formatted.



110
111
112
# File 'lib/storage_visualizer.rb', line 110

def tree_formatted
  @tree_formatted
end

#usedObject

Returns the value of attribute used.



101
102
103
# File 'lib/storage_visualizer.rb', line 101

def used
  @used
end

#used_gbObject

Returns the value of attribute used_gb.



105
106
107
# File 'lib/storage_visualizer.rb', line 105

def used_gb
  @used_gb
end

Class Method Details

.installObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/storage_visualizer.rb', line 42

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.expand_path(__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

Static



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/storage_visualizer.rb', line 27

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] ./visualize_storage[.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) ⇒ Object



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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/storage_visualizer.rb', line 327

def analyze_dirs(dir_to_analyze)

  # bootstrap case
  if (dir_to_analyze == '/')

    # run on all child dirs
    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))
        # puts "Contender: >#{full_path}<"
        analyze_dirs(full_path)
      end
    end
    return
  end


  cmd = "du -sxk \"#{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 = (size.to_f / self.capacity.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 (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}%"
    # push this dir's info
    
    if (dir_to_analyze == self.target_dir)
      
      other_space = self.used - size
      other_space_gb = "#{'%.0f' % (other_space / 1024 / 1024)}"
      other_space_array = ['/', 'Other', other_space_gb]

      short_target_dir = self.target_dir.split('/').reverse[0]
      short_target_dir = (short_target_dir == nil) ? self.target_dir : short_target_dir

      comparison = ['/', short_target_dir, size_gb]
      
      # add them to the array
      self.tree.push(other_space_array)
      self.tree.push(comparison)

    else
      # get parent dir and add to the tree
      short_parent = dir_to_analyze.split('/').reverse[1]

      # short_parent = (short_parent == nil) ? parent : short_parent
      # case for when parent is '/'
      short_parent = (short_parent == '') ? '/' : short_parent
      
      short_dir = dir_to_analyze.split('/').reverse[0]
      
      # array_to_push = [parent, dir_to_analyze, size_gb]
      array_to_push = [short_parent, short_dir, size_gb]
      self.tree.push(array_to_push)
    end

    # run on all child dirs
    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))
        # puts "Contender: >#{full_path}<"
        analyze_dirs(full_path)
      end
    end
    
  end
    
end

#format_data_for_the_chartObject



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/storage_visualizer.rb', line 139

def format_data_for_the_chart
  working_string = "[\n"
  
  self.tree.each_with_index do |entry, index|
    if(index == self.tree.length - 1)
      # this is the next to last element, it gets no comma
      working_string << "[ '#{entry[0]}', '#{entry[1]}', #{entry[2]} ]\n"
    else
      # mind the comma
      working_string << "[ '#{entry[0]}', '#{entry[1]}', #{entry[2]} ],\n"
    end
  end
  working_string << "]\n"
  self.tree_formatted = working_string
  
end

#get_basic_disk_infoObject



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
292
293
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
# File 'lib/storage_visualizer.rb', line 245

def get_basic_disk_info
  # df -l gets info about locally-mounted filesystems
  output = `df -lk`
  
  # 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}
  # }

  output.lines.each_with_index do |line, index|
    if (index == 0)
      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
  self.capacity = self.diskhash['/']['capacity']
  self.used = self.diskhash['/']['used']
  self.available = self.diskhash['/']['available']



  free_space = (self.available).to_i
  free_space_gb = "#{'%.0f' % (free_space / 1024 / 1024)}"
  free_space_array = ['/', 'Free Space', free_space_gb]
  self.tree.push(free_space_array)

  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)}"



end

#runObject



413
414
415
416
417
418
419
# File 'lib/storage_visualizer.rb', line 413

def run
  self.get_basic_disk_info
  self.analyze_dirs(self.target_dir)
  self.format_data_for_the_chart
  self.write_storage_report
  
end

#write_storage_reportObject



157
158
159
160
161
162
163
164
165
166
167
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
202
203
204
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
# File 'lib/storage_visualizer.rb', line 157

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', 'Weight');
      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