Module: MiqVimUpdate

Included in:
MiqVim
Defined in:
lib/VMwareWebService/MiqVimUpdate.rb

Constant Summary collapse

@@max_retries =
4

Instance Method Summary collapse

Instance Method Details

#addObject(objUpdate, initialUpdate) ⇒ Object



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
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 264

def addObject(objUpdate, initialUpdate)
  objType     = objUpdate.obj.vimType
  objBaseType = objUpdate.obj.vimBaseType

  # always log additions to the inventory.
  $vim_log.info "MiqVimUpdate.addObject (#{@connId}): #{objType}: #{objUpdate.obj}"
  return unless (pm = @propMap[objBaseType.to_sym])  # not an object type we cache
  $vim_log.info "MiqVimUpdate.addObject (#{@connId}): Adding object #{objType}: #{objUpdate.obj}"

  #
  # First, add the object's MOR to the @inventoryHash entry for the object's type.
  #
  ia = @inventoryHash[objType] = [] unless (ia = @inventoryHash[objType])
  ia << objUpdate.obj unless ia.include? objUpdate.obj

  begin
    #
    # Then hash the object's properties in its type specific hash.
    #
    hashName = "#{pm[:baseName]}ByMor"
    unless instance_variable_get(hashName) # no cache to update
      return unless initialUpdate
      $vim_log.info "MiqVimUpdate.addObject: setting #{hashName} and #{pm[:baseName]} to empty hash"
      instance_variable_set(hashName, {})
      instance_variable_set(pm[:baseName], {})
    end

    obj = VimHash.new
    obj['MOR'] = objUpdate.obj
    propUpdate(obj, objUpdate.changeSet)

    addObjHash(objBaseType.to_sym, obj)

    #
    # Call the notify callback if enabled, defined and we are past the initial update
    #
    if @notifyMethod && !initialUpdate
      $vim_log.debug "MiqVimUpdate.addObject: server = #{@server}, mor = (#{objUpdate.obj.vimType}, #{objUpdate.obj})"
      Thread.new do
        @notifyMethod.call(:server   => @server,
                           :username => @username,
                           :op       => 'create',
                           :objType  => objUpdate.obj.vimType,
                           :mor      => objUpdate.obj
                          )
      end
    end

  rescue => err
    $vim_log.warn "MiqVimUpdate::addObject: #{err}"
    $vim_log.warn "Clearing cache for: #{pm[:baseName]}"
    $vim_log.debug err.backtrace.join("\n")
    dumpCache("#{pm[:baseName]}ByMor")

    instance_variable_set("#{pm[:baseName]}ByMor", nil)
    instance_variable_set(pm[:baseName], nil)
  end
end

#debugUpdates=(val) ⇒ Object



4
5
6
7
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 4

def debugUpdates=(val)
  @debugUpdates = val
  @dumpToLog = true if @debugUpdates
end

#deleteObject(objUpdate, initialUpdate = false) ⇒ Object



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
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 323

def deleteObject(objUpdate, initialUpdate = false)
  objType     = objUpdate.obj.vimType
  objBaseType = objUpdate.obj.vimBaseType

  # always log deletions from the inventory.
  $vim_log.info "MiqVimUpdate.deleteObject (#{@connId}): #{objType}: #{objUpdate.obj}"
  return unless (pm = @propMap[objBaseType.to_sym])      # not an object type we cache
  $vim_log.info "MiqVimUpdate.deleteObject (#{@connId}): Deleting object: #{objType}: #{objUpdate.obj}"

  ia = @inventoryHash[objType]
  ia.delete(objUpdate.obj)

  return unless instance_variable_get("#{pm[:baseName]}ByMor")  # no cache to update

  begin
    removeObjByMor(objUpdate.obj)

    #
    # Call the notify callback if enabled, defined and we are past the initial update
    #
    if @notifyMethod && !initialUpdate
      $vim_log.debug "MiqVimUpdate.deleteObject: server = #{@server}, mor = (#{objUpdate.obj.vimType}, #{objUpdate.obj})"
      Thread.new do
        @notifyMethod.call(:server   => @server,
                           :username => @username,
                           :op       => 'delete',
                           :objType  => objUpdate.obj.vimType,
                           :mor      => objUpdate.obj
                          )
      end
    end

  rescue => err
    $vim_log.warn "MiqVimUpdate::deleteObject: #{err}"
    $vim_log.warn "Clearing cache for: #{pm[:baseName]}"
    $vim_log.debug err.backtrace.join("\n")
    dumpCache("#{pm[:baseName]}ByMor")

    instance_variable_set("#{pm[:baseName]}ByMor", nil)
    instance_variable_set(pm[:baseName], nil)
  end
end

#forceFailObject



154
155
156
157
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 154

def forceFail
  isDead
  cancelWaitForUpdates(@umPropCol) if @umPropCol
end

#monitorUpdates(preLoad = false) ⇒ Object



92
93
94
95
96
97
98
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
132
133
134
135
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 92

def monitorUpdates(preLoad = false)
  log_prefix = "MiqVimUpdate.monitorUpdates (#{@connId})"
  @umPropCol      = nil
  @filterSpecRef  = nil
  @monitor        = true
  @debugUpdates   = false if @debugUpdates.nil?
  @dumpToLog      = true  if @debugUpdates

  $vim_log.debug "#{log_prefix}: debugUpdates = #{@debugUpdates}"

  begin
    @umPropCol     = @sic.propertyCollector
    @filterSpecRef = createFilter(@umPropCol, @updateSpec, "true")

    version = monitorUpdatesInitial(preLoad)
    @updateMonitorReady = true

    while @monitor
      updates_version = monitorUpdatesSince(version)
      next if updates_version.nil?
      version = updates_version
      sleep @updateDelay if @updateDelay
    end # while @monitor
  rescue SignalException
    # Ignore signals, except TERM
  rescue => herr
    if herr.respond_to?(:reason) && herr.reason == 'The task was canceled by a user.'
      $vim_log.info "#{log_prefix}: waitForUpdates canceled"
    else
      $vim_log.error "******* #{herr.class}"
      $vim_log.error herr.to_s
      $vim_log.error herr.backtrace.join("\n") unless herr.kind_of?(HTTPClient::ReceiveTimeoutError) # already logged in monitorUpdatesInitial or monitorUpdatesSince
      raise herr
    end
  ensure
    if @filterSpecRef && isAlive?
      $vim_log.info "#{log_prefix}: calling destroyPropertyFilter...Starting"
      destroyPropertyFilter(@filterSpecRef)
      $vim_log.info "#{log_prefix}: calling destroyPropertyFilter...Complete"
    end
    @filterSpecRef = nil
    # @umPropCol     = nil
  end
end

#monitorUpdatesInitial(preLoad) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 21

def monitorUpdatesInitial(preLoad)
  log_prefix = "MiqVimUpdate.monitorUpdatesInitial (#{@connId})"

  version      = nil
  truncated    = true
  wait_options = {:max_objects => @maxObjects}

  while truncated
    begin
      $vim_log.info "#{log_prefix}: call to waitForUpdates...Starting" if $vim_log
      updateSet = waitForUpdatesEx(@umPropCol, version, wait_options)
      $vim_log.info "#{log_prefix}: call to waitForUpdates...Complete" if $vim_log

      version   = updateSet.version
      truncated = updateSet.truncated

      if preLoad && @monitor
        @cacheLock.synchronize(:EX) do
          updateSet.filterSet.each do |fu|
            next if fu.filter != @filterSpecRef
            fu.objectSet.each { |objUpdate| updateObject(objUpdate, true) }
          end # updateSet.filterSet.each
          iUpdateFixUp
        end
      end
      # Help out the Ruby Garbage Collector by resetting variables pointing to large objects back to nil
      updateSet = nil
    rescue HTTPClient::ReceiveTimeoutError => terr
      $vim_log.info "#{log_prefix}: call to waitForUpdates...Timeout" if $vim_log
      raise terr if !isAlive?
      retry
    end
  end

  return version
end

#monitorUpdatesSince(version) ⇒ Object



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
85
86
87
88
89
90
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 58

def monitorUpdatesSince(version)
  log_prefix = "MiqVimUpdate.monitorUpdatesSince (#{@connId})"
  begin
    $vim_log.info "#{log_prefix}: call to waitForUpdates...Starting (version = #{version})" if $vim_log
    updateSet = waitForUpdatesEx(@umPropCol, version, :max_wait => @maxWait)
    $vim_log.info "#{log_prefix}: call to waitForUpdates...Complete (version = #{version})" if $vim_log
    return version if updateSet.nil?

    version = updateSet.version

    return if updateSet.filterSet.nil? || updateSet.filterSet.empty?

    updateSet.filterSet.each do |fu|
      next if fu.filter != @filterSpecRef
      fu.objectSet.each do |objUpdate|
        $vim_log.info "#{log_prefix}: applying update...Starting (version = #{version})" if $vim_log
        @cacheLock.synchronize(:EX) do
          updateObject(objUpdate)
        end
        $vim_log.info "#{log_prefix}: applying update...Complete (version = #{version})" if $vim_log
        Thread.pass
      end
    end # updateSet.filterSet.each
    # Help out the Ruby Garbage Collector by resetting variables pointing to large objects back to nil
    updateSet = nil
    return version
  rescue HTTPClient::ReceiveTimeoutError => terr
    $vim_log.info "#{log_prefix}: call to waitForUpdates...Timeout (version = #{version})" if $vim_log
    retry if isAlive?
    $vim_log.warn "#{log_prefix}: connection lost"
    raise terr
  end
end

#notifyMethod=(val) ⇒ Object



9
10
11
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 9

def notifyMethod=(val)
  @notifyMethod = val
end

#propUpdate(propHash, changeSet, returnChangedProps = false) ⇒ Object



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
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 366

def propUpdate(propHash, changeSet, returnChangedProps = false)
  changedProps = [] if returnChangedProps
  changeSet.each do |propChange|
    if @debugUpdates
      $vim_log.debug "\tpropChange name (path): #{propChange.name}"
      $vim_log.debug "\tpropChange op: #{propChange.op}"
      $vim_log.debug "\tpropChange val (type): #{propChange.val.class}"

      $vim_log.debug "\t*** propChange val START:"
      oGi = @globalIndent
      @globalIndent = "\t\t"
      dumpObj(propChange.val)
      @globalIndent = oGi
      $vim_log.debug "\t*** propChange val END"
      $vim_log.debug "\t***"
    end

    #
    # h is the parent hash of the property we're dealing with.
    # tag is the property name relative to the parent hash.
    # key identifies a specific array element, when the property is in an array.
    #
    h, propStr = hashTarget(propHash, propChange.name, true)
    tag, key   = tagAndKey(propStr)

    case propChange.op
    #
    # Add new entry into a collection (array)
    #
    when 'add'
      addToCollection(h, tag, propChange.val)
    #
    # Remove the property
    #
    when /remove|indirectRemove/
      if key
        # The property is an element in an array
        a, i = getVimArrayEnt(h[tag], key)
        a.delete_at(i)
      else
        h.delete(tag)
      end
    #
    # Assign a new value to the property
    #
    when 'assign'
      if key
        # The property is an element in an array
        a, i = getVimArrayEnt(h[tag], key, true)
        a[i] = propChange.val
      else
        h[tag] = propChange.val
      end
    end
    changedProps << propChange.name if returnChangedProps
  end
  return changedProps if returnChangedProps
end

#stopUpdateMonitorObject

def monitorUpdates



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 137

def stopUpdateMonitor
  log_prefix = "MiqVimUpdate.stopUpdateMonitor (#{@connId})"

  $vim_log.info "#{log_prefix}: for address=<#{@server}>, username=<#{@username}>...Starting"
  @monitor = false
  if @umPropCol
    if isAlive?
      $vim_log.info "#{log_prefix}: calling cancelWaitForUpdates...Starting"
      cancelWaitForUpdates(@umPropCol)
      $vim_log.info "#{log_prefix}: calling cancelWaitForUpdates...Complete"
    end
    @umPropCol = nil
    @updateThread.run if @updateThread.status == "sleep"
  end
  $vim_log.info "#{log_prefix}: for address=<#{@server}>, username=<#{@username}>...Complete"
end

#updateDelayObject



17
18
19
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 17

def updateDelay
  @updateDelay
end

#updateDelay=(val) ⇒ Object



13
14
15
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 13

def updateDelay=(val)
  @updateDelay = val
end

#updateObject(objUpdate, initialUpdate = false) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 159

def updateObject(objUpdate, initialUpdate = false)
  unless @inventoryHash # no cache to update
    return unless initialUpdate
    $vim_log.info "MiqVimUpdate.updateObject: setting @inventoryHash to empty hash"
    @inventoryHash = {}
  end

  case objUpdate.kind
  when 'enter'
    addObject(objUpdate, initialUpdate)
  when 'leave'
    deleteObject(objUpdate, initialUpdate)
  when 'modify'
    updateProps(objUpdate, initialUpdate)
  else
    $vim_log.warn "MiqVimUpdate.updateObject (#{@connId}): unrecognized operation: #{objUpdate.kind}"
  end
end

#updateProps(objUpdate, initialUpdate = false) ⇒ Object



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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/VMwareWebService/MiqVimUpdate.rb', line 178

def updateProps(objUpdate, initialUpdate = false)
  $vim_log.debug "Update object (#{@connId}): #{objUpdate.obj.vimType}: #{objUpdate.obj}" if @debugUpdates
  return if !objUpdate.changeSet || objUpdate.changeSet.empty?

  #
  # Look up root hash of object in the <objType>ByMor hash and pass it
  # to the prop update routines: add, remove, assign.
  #
  objType = objUpdate.obj.vimBaseType.to_sym
  unless (pm = @propMap[objType])
    # We don't cache this type of object
    return
  end
  hashName = "#{pm[:baseName]}ByMor"
  return unless (objHash = instance_variable_get(hashName)) # no cache to update
  unless (obj = objHash[objUpdate.obj])
    $vim_log.warn "updateProps (#{@connId}): object #{objUpdate.obj} not found in #{hashName}"
    return
  end

  begin
    #
    # Before updating the object's properties, save its initial key value.
    #
    keyPath   = pm[:keyPath]
    keyPath2  = pm[:keyPath2]
    key0    = keyPath ? obj.fetch_path(keyPath) : nil
    key0b   = keyPath2 ? obj.fetch_path(keyPath2) : nil

    changedProps = propUpdate(obj, objUpdate.changeSet, true)

    key1      = keyPath ? obj.fetch_path(keyPath) : nil

    #
    # If the property we use as a hash key has changed, re-hash the object.
    #
    if keyPath
      objHash = (key1 == key0) ? nil : instance_variable_get(pm[:baseName])
      unless objHash.nil?
        objHash.delete(key0)  if key0
        objHash.delete(key0b) if key0b # changes when key0 changes.
        objHash[key1] = obj   if key1
        # Gets hashed by keyPath2 in objFixUp().
      end
    end

    #
    # Add our local values to cache:
    #   VMs:             ['summary']['config']['vmLocalPathName']
    #                    ['summary']["runtime"]["hostName"]
    #                    snapshot ['ssMorHash']
    #   Resource Pools:  ['summary']['name']
    #
    objFixUp(objType, obj)

    #
    # Call the notify callback if enabled, defined and we are past the initial update
    #
    if @notifyMethod && !initialUpdate
      $vim_log.debug "MiqVimUpdate.updateProps (#{@connId}): server = #{@server}, mor = (#{objUpdate.obj.vimType}, #{objUpdate.obj})"
      $vim_log.debug "MiqVimUpdate.updateProps (#{@connId}): changedProps = [ #{changedProps.join(', ')} ]"
      Thread.new do
        @notifyMethod.call(:server       => @server,
                           :username     => @username,
                           :op           => 'update',
                           :objType      => objUpdate.obj.vimType,
                           :mor          => objUpdate.obj,
                           :changedProps => changedProps,
                           :changeSet    => objUpdate.changeSet,
                           :key          => key0,
                           :newKey       => key1
                          )
      end
    end

  rescue => err
    $vim_log.warn "MiqVimUpdate::updateProps (#{@connId}): #{err}"
    $vim_log.warn "Clearing cache for (#{@connId}): #{pm[:baseName]}"
    $vim_log.debug err.backtrace.join("\n")
    dumpCache("#{pm[:baseName]}ByMor")

    instance_variable_set("#{pm[:baseName]}ByMor", nil)
    instance_variable_set(pm[:baseName], nil)
  end
end