Class: Classification

Inherits:
ApplicationRecord show all
Defined in:
app/models/classification.rb

Direct Known Subclasses

Category

Constant Summary collapse

NAME_MAX_LENGTH =
50
DEFAULT_NAMESPACE =
"/managed"
FIXTURE_FILE =
FIXTURE_DIR.join("classifications.yml")

Constants inherited from ApplicationRecord

ApplicationRecord::FIXTURE_DIR

Constants included from ArRegion

ArRegion::CID_OR_ID_MATCHER, ArRegion::COMPRESSED_ID_SEPARATOR, ArRegion::DEFAULT_RAILS_SEQUENCE_FACTOR, ArRegion::RE_COMPRESSED_ID

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ArTableLock

#with_lock

Methods included from ToModelHash

#to_model_hash, #to_model_yaml

Methods included from ArLock

#lock

Methods included from ArRegion

anonymous_class_with_ar_region, #compressed_id, #in_current_region?, #miq_region, #my_region_number, #region_description, #region_number, #split_id

Methods inherited from ActiveRecord::Base

acts_as_miq_set, acts_as_miq_set_member, acts_as_miq_taggable, column_names_symbols, extract_ids, extract_objects, model_suffix, #number_of, paginate, truncate

Methods included from VirtualDelegates

select_from_alias, select_from_alias_table

Methods included from Vmdb::Logging

#_log

Instance Attribute Details

#nameObject


320
321
322
# File 'app/models/classification.rb', line 320

def name
  @name ||= tag2name(tag_name || tag.name)
end

#nsObject


76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'app/models/classification.rb', line 76

def ns
  @ns ||= DEFAULT_NAMESPACE if self.new_record?

  # @ns = tag2ns(self.tag.name) unless self.tag.nil?
  return @ns if tag.nil?

  return @ns unless @ns.nil?

  if category?
    @ns = tag2ns(tag.name)
  else
    @ns = tag2ns(parent.tag.name) unless parent_id.nil?
  end
end

Class Method Details

.bulk_reassignment(options = {}) ⇒ Object


127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
# File 'app/models/classification.rb', line 127

def self.bulk_reassignment(options = {})
  # options = {
  #   :model      => Target class name
  #   :object_ids => Array of target ids
  #   :add_ids    => Array of entry ids to be assigned to targets
  #   :delete_ids => Array of entry ids to be unassigned from targets
  # }

  model = options[:model].constantize
  targets = model.where(:id => options[:object_ids]).includes(:taggings, :tags)

  adds = where(:id => options[:add_ids]).includes(:tag)
  adds.each { |a| raise _("Classification add id: [%{id}] is not an entry") % {:id => a.id} if a.category? }

  deletes = where(:id => options[:delete_ids]).includes(:tag)
  deletes.each { |d| raise _("Classification delete id: [%{id}] is not an entry") % {:id => d.id} if d.category? }

  failed_deletes = Hash.new { |h, k| h[k] = [] }
  failed_adds    = Hash.new { |h, k| h[k] = [] }

  targets.each do |t|
    deletes.each do |d|
      _log.info("Removing entry name: [#{d.name}] from #{options[:model]} name: #{t.name}")

      begin
        d.remove_entry_from(t)
      rescue => err
        _log.error("Error occurred while removing entry name: [#{d.name}] from #{options[:model]} name: #{t.name}")
        _log.error("#{err.class} - #{err}")
        failed_deletes[t] << d
      end
    end

    adds.each do |a|
      _log.info("Adding entry name: [#{a.name}] to #{options[:model]} name: #{t.name}")

      begin
        a.assign_entry_to(t)
      rescue => err
        _log.error("Error occurred while adding entry name: [#{a.name}] to #{options[:model]} name: #{t.name}")
        _log.error("#{err.class} - #{err}")
        failed_adds[t] << a
      end
    end
  end

  if failed_deletes.any? || failed_adds.any?
    msg = _("Failures occurred during bulk reassignment.")
    failed_deletes.each do |target, deletes|
      names = deletes.collect(&:name).sort
      msg += _("  Unable to remove the following tags from %{class_name} %{id}: %{names}.") %
               {:class_name => target.class.name, :id => target.id, :names => names.join(", ")}
    end
    failed_adds.each do |target, adds|
      names = adds.collect(&:name).sort
      msg += _("  Unable to add the following tags to %{class_name} %{id}: %{names}.") %
               {:class_name => target.class.name, :id => target.id, :names => names.join(", ")}
    end
    raise msg
  end

  true
end

.categories(region_id = my_region_number, ns = DEFAULT_NAMESPACE) ⇒ Object


200
201
202
203
204
# File 'app/models/classification.rb', line 200

def self.categories(region_id = my_region_number, ns = DEFAULT_NAMESPACE)
  cats = where(:classifications => {:parent_id => 0}).includes(:tag, :children)
  cats = cats.in_region(region_id) if region_id
  cats.select { |c| c.ns == ns }
end

.category_names_for_perf_by_tag(region_id = my_region_number, ns = DEFAULT_NAMESPACE) ⇒ Object


206
207
208
209
210
211
212
# File 'app/models/classification.rb', line 206

def self.category_names_for_perf_by_tag(region_id = my_region_number, ns = DEFAULT_NAMESPACE)
  in_region(region_id)
    .where(:parent_id => 0, :perf_by_tag => true)
    .includes(:tag)
    .collect { |c| c.name if c.tag2ns(c.tag.name) == ns }
    .compact
end

.classify(obj, category_name, entry_name, is_request = true) ⇒ Object


91
92
93
94
95
96
97
# File 'app/models/classification.rb', line 91

def self.classify(obj, category_name, entry_name, is_request = true)
  cat = Classification.find_by_name(category_name, obj.region_id)
  unless cat.nil?
    ent = cat.find_entry_by_name(entry_name, obj.region_id)
    ent.assign_entry_to(obj, is_request) unless ent.nil? || obj.is_tagged_with?(ent.to_tag, :ns => "none")
  end
end

.classify_by_tag(obj, tag, is_request = true) ⇒ Object


107
108
109
110
111
112
113
114
115
# File 'app/models/classification.rb', line 107

def self.classify_by_tag(obj, tag, is_request = true)
  parts = tag.split("/")
  raise _("Tag %{tag} is not a category entry") % {:tag => tag} unless parts[1] == "managed"

  entry_name = parts.pop
  category_name = parts.pop

  classify(obj, category_name, entry_name, is_request)
end

.create_category!(options) ⇒ Object


196
197
198
# File 'app/models/classification.rb', line 196

def self.create_category!(options)
  self.create!(options.merge(:parent_id => 0))
end

.export_to_arrayObject


376
377
378
379
380
# File 'app/models/classification.rb', line 376

def self.export_to_array
  categories.inject([]) do |a, c|
    a.concat c.export_to_array
  end
end

.export_to_yamlObject


382
383
384
# File 'app/models/classification.rb', line 382

def self.export_to_yaml
  export_to_array.to_yaml
end

.find_assigned_entries(obj, ns = DEFAULT_NAMESPACE) ⇒ Object


214
215
216
217
218
219
220
221
# File 'app/models/classification.rb', line 214

def self.find_assigned_entries(obj, ns = DEFAULT_NAMESPACE)
  unless obj.respond_to?("tag_with")
    raise _("Class '%{name}' is not eligible for classification") % {:name => obj.class}
  end

  tag_ids = obj.tagged_with(:ns => ns).collect(&:id)
  where(:tag_id => tag_ids) rescue []
end

.find_by_name(name, region_id = my_region_number, ns = DEFAULT_NAMESPACE, parent_id = 0) ⇒ Object


330
331
332
333
# File 'app/models/classification.rb', line 330

def self.find_by_name(name, region_id = my_region_number, ns = DEFAULT_NAMESPACE, parent_id = 0)
  tag = Tag.find_by_classification_name(name, region_id, ns, parent_id)
  find_by(:tag_id => tag.id) if tag
end

.find_by_names(names, region_id = my_region_number, ns = DEFAULT_NAMESPACE) ⇒ Object


335
336
337
338
339
340
# File 'app/models/classification.rb', line 335

def self.find_by_names(names, region_id = my_region_number, ns = DEFAULT_NAMESPACE)
  tag_names = names.map { |name| Classification.name2tag(name, 0, ns) }
  # NOTE: tags is a subselect - not an array of ids
  tags = Tag.in_region(region_id).where(:name => tag_names).select(:id)
  where(:tag_id => tags)
end

.first_cat_entry(name, obj) ⇒ Object


223
224
225
226
227
228
229
230
231
# File 'app/models/classification.rb', line 223

def self.first_cat_entry(name, obj)
  cat = find_by_name(name, obj.region_id)
  return nil unless cat

  find_assigned_entries(obj).each do|e|
    return e if e.parent_id == cat.id
  end
  nil
end

.get_tags_from_object(obj) ⇒ Object


191
192
193
194
# File 'app/models/classification.rb', line 191

def self.get_tags_from_object(obj)
  tags = obj.tag_list(:ns => "/managed").split
  tags.delete_if { |t| t =~ /^\/folder_path_/ }
end

.hash_all_by_type_and_name(conditions = {}) ⇒ Object


43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/models/classification.rb', line 43

def self.hash_all_by_type_and_name(conditions = {})
  ret = {}

  where(conditions).where(:parent_id => 0).includes(:tag).each do |c|
    ret.store_path(c.name, :category, c)
  end

  where(conditions).where.not(:parent_id => 0).includes(:tag, :parent => :tag).each do |e|
    ret.store_path(e.parent.name, :entry, e.name, e) unless e.parent.nil?
  end

  ret
end

.import_from_hash(classification, parent = nil) ⇒ Object


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
# File 'app/models/classification.rb', line 402

def self.import_from_hash(classification, parent = nil)
  raise _("No Classification to Import") if classification.nil?

  stats = {"categories" => 0, "entries" => 0}

  if classification["parent_id"] == 0 # category
    cat = find_by_name(classification["name"])
    if cat
      _log.info("Skipping Classification (already in DB): Category: name=[#{classification["name"]}]")
      return stats
    end

    _log.info("Importing Classification: Category: name=[#{classification["name"]}]")

    entries = classification.delete("entries")
    cat = create(classification)
    stats["categories"] += 1
    entries.each do |e|
      stat, _e = import_from_hash(e, cat)
      stats.each_key { |k| stats[k] += stat[k] }
    end

    return stats, cat
  else
    entry = parent.find_entry_by_name(classification["name"])
    if entry
      _log.info("Skipping Classification (already in DB): Category: name: [#{parent.name}], Entry: name=[#{classification["name"]}]")
      return stats
    end

    _log.info("Importing Classification: Category: name: [#{parent.name}], Entry: name=[#{classification["name"]}]")
    entry = create(classification.merge("parent_id" => parent.id))
    stats["entries"] += 1

    return stats, entry
  end
end

.import_from_yaml(fd) ⇒ Object


440
441
442
443
444
445
446
447
448
449
450
# File 'app/models/classification.rb', line 440

def self.import_from_yaml(fd)
  stats = {"categories" => 0, "entries" => 0}

  input = YAML.load(fd)
  input.each do |c|
    stat, _c = import_from_hash(c)
    stats.each_key { |k| stats[k] += stat[k] }
  end

  stats
end

.managedObject


70
71
72
# File 'app/models/classification.rb', line 70

def self.managed
  with_tag_name.where(tags_arel[:name].matches_regexp("/managed/[^\\/]+$"))
end

.parent_ids(parent_ids) ⇒ Object


57
58
59
# File 'app/models/classification.rb', line 57

def self.parent_ids(parent_ids)
  where :parent_id => parent_ids
end

.sanitize_name(name) ⇒ Object


465
466
467
# File 'app/models/classification.rb', line 465

def self.sanitize_name(name)
  name.downcase.tr('^a-z0-9_:', '_')[0, NAME_MAX_LENGTH]
end

.seedObject


452
453
454
455
456
457
458
459
460
461
462
463
# File 'app/models/classification.rb', line 452

def self.seed
  YAML.load_file(FIXTURE_FILE).each do |c|
    cat = find_by_name(c[:name], my_region_number, (c[:ns] || DEFAULT_NAMESPACE))
    next if cat

    _log.info("Creating #{c[:name]}")
    add_entries_from_hash(create(c.except(:entries)), c[:entries])
  end

  # Fix categories that have a nill parent_id
  where(:parent_id => nil).update_all(:parent_id => 0)
end

.tag_name_split(tag_name) ⇒ Object

Splits a fully qualified tag into the namespace, category, and entry


234
235
236
237
238
# File 'app/models/classification.rb', line 234

def self.tag_name_split(tag_name)
  parts = tag_name.split("/")
  parts.shift
  parts
end

.tag_name_to_objects(tag_name) ⇒ Object

Splits a fully qualified tag into the namespace, category object, and entry object


241
242
243
244
245
246
# File 'app/models/classification.rb', line 241

def self.tag_name_to_objects(tag_name)
  ns, cat, entry = tag_name_split(tag_name)
  cat_obj = find_by_name(cat)
  entry_obj = cat_obj.nil? ? nil : cat_obj.find_entry_by_name(entry)
  return ns, cat_obj, entry_obj
end

.tag_to_model_hash(tag) ⇒ Object

Builds the given tag into a format usable when calling to_model_hash.


249
250
251
252
253
254
255
256
# File 'app/models/classification.rb', line 249

def self.tag_to_model_hash(tag)
  ns, cat, entry = tag_name_to_objects(tag.name)

  h = {:id => tag.id, :name => tag.name, :namespace => ns}
  %w(id name description single_value).each { |m| h[:"category_#{m}"] = cat.send(m) } unless cat.nil?
  %w(id name description).each { |m| h[:"entry_#{m}"] = entry.send(m) } unless entry.nil?
  h
end

.tags_arelObject


61
62
63
# File 'app/models/classification.rb', line 61

def self.tags_arel
  Tag.arel_table
end

.unclassify(obj, category_name, entry_name, is_request = true) ⇒ Object


99
100
101
102
103
104
105
# File 'app/models/classification.rb', line 99

def self.unclassify(obj, category_name, entry_name, is_request = true)
  cat = Classification.find_by_name(category_name, obj.region_id)
  unless cat.nil?
    ent = cat.find_entry_by_name(entry_name, obj.region_id)
    ent.remove_entry_from(obj, is_request) unless ent.nil? || !obj.is_tagged_with?(ent.to_tag, :ns => "none")
  end
end

.unclassify_by_tag(obj, tag, is_request = true) ⇒ Object


117
118
119
120
121
122
123
124
125
# File 'app/models/classification.rb', line 117

def self.unclassify_by_tag(obj, tag, is_request = true)
  parts = tag.split("/")
  raise _("Tag %{tag} is not a category entry") % {:tag => tag} unless parts[1] == "managed"

  entry_name = parts.pop
  category_name = parts.pop

  unclassify(obj, category_name, entry_name, is_request)
end

.with_tag_nameObject


65
66
67
68
# File 'app/models/classification.rb', line 65

def self.with_tag_name
  select(arel_table[Arel.star], tags_arel[:name].as('tag_name'))
    .joins(:tag)
end

Instance Method Details

#add_entry(options) ⇒ Object


258
259
260
261
262
263
# File 'app/models/classification.rb', line 258

def add_entry(options)
  raise _("entries can only be added to classifications") unless category?
  # Inherit from parent classification
  options.merge!(:read_only => read_only, :syntax => syntax, :single_value => single_value, :ns => ns)
  children.create(options)
end

#assign_entry_to(obj, is_request = true) ⇒ Object


279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'app/models/classification.rb', line 279

def assign_entry_to(obj, is_request = true)
  raise _("method is only available for an entry") if category?
  unless obj.respond_to?("tag_with")
    raise _("Class '%{name}' is not eligible for classification") % {:name => obj.class}
  end

  enforce_policy(obj, :request_assign_company_tag) if is_request
  if parent.single_value?
    obj.tag_with(name, :ns => ns, :cat => parent.name)
  else
    obj.tag_add(name, :ns => ns, :cat => parent.name)
  end
  obj.reload
  enforce_policy(obj, :assigned_company_tag)
end

#categoryObject


312
313
314
# File 'app/models/classification.rb', line 312

def category
  parent.try(:name)
end

#category?Boolean


308
309
310
# File 'app/models/classification.rb', line 308

def category?
  parent_id == 0
end

#enforce_policy(obj, event) ⇒ Object


357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'app/models/classification.rb', line 357

def enforce_policy(obj, event)
  return unless MiqEvent::SUPPORTED_POLICY_AND_ALERT_CLASSES.include?(obj.class.base_class)
  return if parent.name == "power_state" # special case for old power state classifications - don't enforce policy since this is being changed by the system

  mode = event.to_s.split("_").first # request/after
  begin
    MiqEvent.raise_evm_event(obj, event)
  rescue MiqException::PolicyPreventAction => err
    if mode == "request"
      # if it's the "before_..." event we can still prevent it from proceeding. Otherwise it's too late.
      _log.info("Event: [#{event}], #{err.message}")
      raise
    end
  rescue Exception => err
    _log.log_backtrace(err)
    raise
  end
end

#entriesObject


265
266
267
# File 'app/models/classification.rb', line 265

def entries
  children
end

#export_to_arrayObject


386
387
388
389
390
391
392
393
394
395
396
# File 'app/models/classification.rb', line 386

def export_to_array
  h = attributes
  h["name"] = name
  if category?
    ["id", "tag_id", "reserved"].each { |k| h.delete(k) }
    h["entries"] = entries.collect(&:export_to_array).flatten
  else
    ["id", "tag_id", "reserved", "parent_id"].each { |k| h.delete(k) }
  end
  [h]
end

#export_to_yamlObject


398
399
400
# File 'app/models/classification.rb', line 398

def export_to_yaml
  export_to_array.to_yaml
end

#find_by_entry(type) ⇒ Object


269
270
271
272
273
274
275
276
277
# File 'app/models/classification.rb', line 269

def find_by_entry(type)
  raise _("method is only available for an entry") if category?
  klass = type.constantize
  unless klass.respond_to?("find_tagged_with")
    raise _("Class '%{type}' is not eligible for classification") % {:type => type}
  end

  klass.find_tagged_with(:any => name, :ns => ns, :cat => parent.name)
end

#find_entry_by_name(name, region_id = my_region_number) ⇒ Object


326
327
328
# File 'app/models/classification.rb', line 326

def find_entry_by_name(name, region_id = my_region_number)
  self.class.find_by_name(name, region_id, ns, self)
end

#remove_entry_from(obj, is_request = true) ⇒ Object


295
296
297
298
299
300
301
302
# File 'app/models/classification.rb', line 295

def remove_entry_from(obj, is_request = true)
  enforce_policy(obj, :request_unassign_company_tag) if is_request
  tags = obj.tag_list(:ns => ns, :cat => parent.name).split
  tags.delete(name)
  obj.tag_with(tags.join(" "), :ns => ns, :cat => parent.name)
  obj.reload
  enforce_policy(obj, :unassigned_company_tag)
end

#tag2ns(tag) ⇒ Object


342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'app/models/classification.rb', line 342

def tag2ns(tag)
  unless tag.nil?
    ta = tag.split("/")
    ta[0..(ta.length - 2)].join("/")

    # tnew = []
    # tag.split("/").each {|level|
    #   p "level=#{level}"
    #   tnew.push(level) unless level == self.name
    #   p "level=#{level}, #{tnew.inspect}, #{(level == self.name)}"
    # }
    # tnew.join("/")
  end
end

#tag_nameObject


316
317
318
# File 'app/models/classification.rb', line 316

def tag_name
  attribute(:tag_name)
end

#to_tagObject


304
305
306
# File 'app/models/classification.rb', line 304

def to_tag
  tag.name unless tag.nil?
end