Module: RVC::Util

Extended by:
Util
Included in:
CommandSlate, RubyEvaluator, Util
Defined in:
lib/rvc/util.rb

Constant Summary collapse

TCSETPGRP =
0x5410
UserError =
Class.new(Exception)
PROGRESS_BAR_LEFT =
"["
PROGRESS_BAR_MIDDLE =
"="
PROGRESS_BAR_RIGHT =
"]"

Instance Method Summary collapse

Instance Method Details

#collect_children(obj, path) ⇒ Object



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
# File 'lib/rvc/util.rb', line 171

def collect_children obj, path
  spec = {
    :objectSet => [
      {
        :obj => obj,
        :skip => true,
        :selectSet => [
          RbVmomi::VIM::TraversalSpec(
            :path => path,
            :type => obj.class.wsdl_name
          )
        ]
      }
    ],
    :propSet => [
      {
        :type => 'ManagedEntity',
        :pathSet => %w(name),
      }
    ]
  }

  results = obj._connection.propertyCollector.RetrieveProperties(:specSet => [spec])

  # Work around ESX 4.0 ignoring the skip field
  results.reject! { |r| r.obj == obj }

  Hash[results.map { |r| [r['name'], r.obj] }]
end

#display_inventory(tree, folder, indent = 0, &b) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rvc/util.rb', line 40

def display_inventory tree, folder, indent=0, &b
  tree[folder].sort_by { |k,(o,h)| o._ref }.each do |k,(o,h)|
    case o
    when VIM::Folder
      puts "#{"  "*indent}--#{k}"
      display_inventory tree, o, (indent+1), &b
    else
      b[o,h,indent]
    end
  end
end

#err(msg) ⇒ Object

Raises:



61
62
63
# File 'lib/rvc/util.rb', line 61

def err msg
  raise UserError.new(msg)
end

#http_clone(main_http) ⇒ Object



270
271
272
273
274
275
276
277
278
# File 'lib/rvc/util.rb', line 270

def http_clone main_http
  http = Net::HTTP.new(main_http.address, main_http.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  #http.set_debug_output $stderr
  http.start
  err "certificate mismatch" unless main_http.peer_cert.to_der == http.peer_cert.to_der
  return http
end

#http_download(connection, http_path, local_path) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/rvc/util.rb', line 280

def http_download connection, http_path, local_path
  http = http_clone connection.http

  headers = { 'cookie' => connection.cookie }
  http.request_get(http_path, headers) do |res|
    case res
    when Net::HTTPOK
      len = res.content_length
      count = 0
      File.open(local_path, 'wb') do |io|
        res.read_body do |segment|
          count += segment.length
          io.write segment
          $stdout.write "\e[0G\e[Kdownloading #{count}/#{len} bytes (#{(count*100)/len}%)"
          $stdout.flush
        end
      end
      $stdout.puts
    else
      err "download failed: #{res.message}"
    end
  end
end

#http_upload(connection, local_path, http_path) ⇒ Object



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
# File 'lib/rvc/util.rb', line 305

def http_upload connection, local_path, http_path
  err "local file does not exist" unless File.exists? local_path

  http = http_clone connection.http

  File.open(local_path, 'rb') do |io|
    stream = ProgressStream.new(io, io.stat.size) do |s|
      $stdout.write "\e[0G\e[Kuploading #{s.count}/#{s.len} bytes (#{(s.count*100)/s.len}%)"
      $stdout.flush
    end

    headers = {
      'cookie' => connection.cookie,
      'content-length' => io.stat.size.to_s,
      'Content-Type' => 'application/octet-stream',
    }

    request = Net::HTTP::Put.new http_path, headers
    request.body_stream = stream
    res = http.request(request)
    $stdout.puts
    case res
    when Net::HTTPOK
    else
      err "upload failed: #{res.message}"
    end
  end
end

#interactive?Boolean

Returns:

  • (Boolean)


148
149
150
# File 'lib/rvc/util.rb', line 148

def interactive?
  terminal_columns > 0
end


33
34
35
36
37
38
# File 'lib/rvc/util.rb', line 33

def menu items
  items.each_with_index { |x, i| puts "#{i} #{x}" }
  input = Readline.readline("? ", false)
  return if !input or input.empty?
  items[input.to_i]
end

#metric(num) ⇒ Object



205
206
207
# File 'lib/rvc/util.rb', line 205

def metric num
  MetricNumber.new(num.to_f, '', false).to_s
end

#one_progress(task) ⇒ Object



133
134
135
136
137
# File 'lib/rvc/util.rb', line 133

def one_progress task
  progress([task])[task].tap do |r|
    raise r if r.is_a? VIM::LocalizedMethodFault
  end
end

#progress(tasks) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/rvc/util.rb', line 99

def progress tasks
  results = {}
  interested = %w(info.progress info.state info.entityName info.error info.name)
  connection = single_connection tasks
  connection.serviceInstance.wait_for_multiple_tasks interested, tasks do |h|
    if interactive?
      h.each do |task,props|
        state, entityName, name = props['info.state'], props['info.entityName'], props['info.name']
        name = $` if name =~ /_Task$/
        if state == 'running'
          text = "#{name} #{entityName}: #{state} "
          progress = props['info.progress']
          barlen = terminal_columns - text.size - 2
          barlen = 0 if barlen < 0 # we can't draw -ive bars, simple fix TODO: draw on next line
          progresslen = ((progress||0)*barlen)/100
          progress_bar = "#{PROGRESS_BAR_LEFT}#{PROGRESS_BAR_MIDDLE * progresslen}#{' ' * (barlen-progresslen)}#{PROGRESS_BAR_RIGHT}"
          $stdout.write "\e[K#{text}#{progress_bar}\n"
        elsif state == 'error'
          error = props['info.error']
          results[task] = error
          $stdout.write "\e[K#{name} #{entityName}: #{error.fault.class.wsdl_name}: #{error.localizedMessage}\n"
        else
          results[task] = task.info.result if state == 'success'
          $stdout.write "\e[K#{name} #{entityName}: #{state}\n"
        end
      end
      $stdout.write "\e[#{h.size}A"
      $stdout.flush
    end
  end
  $stdout.write "\e[#{tasks.size}B" if interactive?
  results
end

#retrieve_fields(objs, fields) ⇒ Object



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
# File 'lib/rvc/util.rb', line 209

def retrieve_fields objs, fields
  pc = nil
  if objs.length == 0
    return {}
  end
  conn = objs.first._connection
  pc = conn.propertyCollector
  perfmgr = conn.serviceContent.perfManager
  objs_props = Hash[objs.map{|o| [o, o.field_properties(fields)]}]
  buckets = {}
  objs_props.each{|o,p| buckets[p] ||= []; buckets[p] << o}
  props_values = {}
  buckets.each do |props, o|
    begin
      props_values.merge!(pc.collectMultiple(o, *props))
    rescue VIM::ManagedObjectNotFound => ex
      o -= [ex.obj]
      retry
    end
  end

  buckets = {}
  objs.each do |o|
    metrics = o.perfmetrics(fields)
    if metrics.length > 0
      buckets[metrics] ||= []
      buckets[metrics] << o
    end
  end
  perf_values = {}
  buckets.each do |metrics, os|
    # XXX: Would be great if we could collapse metrics into a single call
    metrics.each do |metric|
      begin
        stats = perfmgr.retrieve_stats os, metric[:metrics], metric[:opts]
        os.each do |o|
          perf_values[o] = {}
          metric[:metrics].map do |x|
            if stats[o]
              perf_values[o][x] = stats[o][:metrics][x]
            end
          end
        end
      rescue VIM::ManagedObjectNotFound => ex
        o -= [ex.obj]
        retry
      end
    end
  end

  Hash[objs.map do |o|
    begin
      [o, Hash[fields.map do |f|
        [f, o.field(f, props_values[o], perf_values[o])]
      end]]
    rescue VIM::ManagedObjectNotFound
      next
    end
  end]
end

#search_path(bin) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/rvc/util.rb', line 52

def search_path bin
  ENV['PATH'].split(':').each do |x|
    path = File.join(x, bin)
    return path if File.exists? path
  end
  nil
end

#single_connection(objs) ⇒ Object



65
66
67
68
69
70
# File 'lib/rvc/util.rb', line 65

def single_connection objs
  conns = objs.map { |x| x._connection rescue nil }.compact.uniq
  err "No connections" if conns.size == 0
  err "Objects span multiple connections" if conns.size > 1
  conns[0]
end

#status_color(str, status) ⇒ Object



201
202
203
# File 'lib/rvc/util.rb', line 201

def status_color str, status
  $terminal.color(str, *VIM::ManagedEntity::STATUS_COLORS[status])
end

#system_fg(cmd, env = {}) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
# File 'lib/rvc/util.rb', line 159

def system_fg cmd, env={}
  pid = fork do
    env.each { |k,v| ENV[k] = v }
    Process.setpgrp
    tcsetpgrp
    exec cmd
  end
  Process.waitpid2 pid rescue nil
  tcsetpgrp
  nil
end

#tasks(objs, sym, args = {}) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/rvc/util.rb', line 72

def tasks objs, sym, args={}
  # Stores valid objs to send to progress method
  taskobjs = []

  objs.each do |obj|
    begin
      taskobjs.push (obj._call :"#{sym}_Task", args)
    rescue Exception => ex
      puts "util.rb:tasks: Skipping current object #{obj} due to Exception: #{ex.message}"
    end
  end

  #Process only those objects which haven't raised any exception
  progress (taskobjs)
end

#tcsetpgrp(pgrp = Process.getpgrp) ⇒ Object



152
153
154
155
156
157
# File 'lib/rvc/util.rb', line 152

def tcsetpgrp pgrp=Process.getpgrp
  return unless $stdin.tty?
  trap('TTOU', 'SIG_IGN')
  $stdin.ioctl TCSETPGRP, [pgrp].pack('I')
  trap('TTOU', 'SIG_DFL')
end

#terminal_columnsObject



139
140
141
142
143
144
145
146
# File 'lib/rvc/util.rb', line 139

def terminal_columns
  begin
    require 'curses'
    Curses.cols
  rescue LoadError
    80
  end
end