forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
miq_request_workflow.rb
1468 lines (1240 loc) · 49.8 KB
/
miq_request_workflow.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
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
85
86
87
88
89
90
91
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
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
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
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
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
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
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
476
477
478
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'enumerator'
require 'miq-hash_struct'
class MiqRequestWorkflow
include Vmdb::Logging
include_concern "DialogFieldValidation"
# We rely on MiqRequestWorkflow's descendants to be comprehensive
singleton_class.send(:prepend, DescendantLoader::ArDescendantsWithLoader)
attr_accessor :dialogs, :requester, :values, :last_vm_id
def self.automate_dialog_request
nil
end
def self.default_dialog_file
nil
end
def self.default_pre_dialog_file
nil
end
def self.encrypted_options_fields
[]
end
def self.encrypted_options_field_regs
encrypted_options_fields.map { |f| /\[:#{f}\]/ }
end
def self.all_encrypted_options_fields
descendants.flat_map(&:encrypted_options_fields).uniq
end
def self.update_requester_from_parameters(data, user)
return user if data[:user_name].blank?
new_user = User.lookup_by_identity(data[:user_name])
unless new_user
_log.error "requested not changed to <#{data[:user_name]}> due to a lookup failure"
raise ActiveRecord::RecordNotFound
end
_log.warn "requested changed to <#{new_user.userid}>"
new_user
end
def initialize(values, requester, options = {})
instance_var_init(values, requester, options)
unless options[:skip_dialog_load] == true
# If this is the first time we are called the values hash will be empty
# Also skip if we are being called from a web-service
if @dialogs.nil?
@dialogs = get_dialogs
normalize_numeric_fields
else
@running_pre_dialog = true if options[:use_pre_dialog] != false
end
end
unless options[:skip_dialog_load] == true
set_default_values
update_field_visibility
end
end
def instance_var_init(values, requester, options)
@values = values
@filters = {}
@requester = requester.kind_of?(User) ? requester : User.lookup_by_identity(requester)
group_description = values[:requester_group]
if group_description && group_description != @requester.miq_group_description
@requester = @requester.clone
@requester.current_group_by_description = group_description
end
@values.merge!(options) unless options.blank?
end
# Helper method when not using workflow
def make_request(request, values, requester = nil, auto_approve = false)
return false unless validate(values)
password_helper(values, true)
# Ensure that tags selected in the pre-dialog get applied to the request
values[:vm_tags] = (values[:vm_tags].to_miq_a + @values[:pre_dialog_vm_tags]).uniq if @values.try(:[], :pre_dialog_vm_tags).present?
if request
MiqRequest.update_request(request, values, @requester)
else
set_request_values(values)
req = request_class.new(:options => values, :requester => @requester, :request_type => request_type.to_s)
return req unless req.valid? # TODO: CatalogController#atomic_req_submit is the only one that enumerates over the errors
values[:__request_type__] = request_type.to_s.presence # Pass this along to MiqRequest#create_request
request_class.create_request(values, @requester, auto_approve)
end
end
def init_from_dialog(init_values)
@dialogs[:dialogs].keys.each do |dialog_name|
get_all_fields(dialog_name).each_pair do |field_name, field_values|
next unless init_values[field_name].nil?
next if field_values[:display] == :ignore
if !field_values[:default].nil?
val = field_values[:default]
end
if field_values[:values]
if field_values[:values].kind_of?(Hash)
# Save [value, description], skip for timezones array
init_values[field_name] = [val, field_values[:values][val]]
else
field_values[:values].each do |tz|
if tz[1].to_i_with_method == val.to_i_with_method
# Save [value, description] for timezones array
init_values[field_name] = [val, tz[0]]
end
end
end
else
# Set to default value
init_values[field_name] = val
end
end
end
end
def validate(values)
# => Input - A hash keyed by field name with entered values
# => Output - true || false
#
# Update @dialogs adding error keys to fields that don't validate
valid = true
get_all_dialogs(false).each do |d, dlg|
# Check if the entire dialog is ignored or disabled and check while processing the fields
dialog_disabled = !dialog_active?(d, dlg, values)
get_all_fields(d, false).each do |f, fld|
fld[:error] = nil
# Check the disabled flag here so we reset the "error" value on each field
next if dialog_disabled || fld[:display] == :hide
value = fld[:data_type] =~ /array_/ ? values[f] : get_value(values[f])
if fld[:required] == true
# If :required_method is defined let it determine if the field is value
unless fld[:required_method].nil?
Array.wrap(fld[:required_method]).each do |method|
fld[:error] = send(method, f, values, dlg, fld, value)
# Bail out early if we see an error
break unless fld[:error].nil?
end
unless fld[:error].nil?
valid = false
next
end
else
default_require_method = "default_require_#{f}".to_sym
if self.respond_to?(default_require_method)
fld[:error] = send(default_require_method, f, values, dlg, fld, value)
unless fld[:error].nil?
valid = false
next
end
else
if value.blank?
fld[:error] = "#{required_description(dlg, fld)} is required"
valid = false
next
end
end
end
end
if fld[:validation_method] && respond_to?(fld[:validation_method])
if (fld[:error] = send(fld[:validation_method], f, values, dlg, fld, value))
valid = false
next
end
end
next if value.blank?
msg = "'#{fld[:description]}' in dialog #{dlg[:description]} must be of type #{fld[:data_type]}"
validate_data_types(value, fld, msg, valid)
end
end
valid
end
def validate_data_types(value, fld, msg, valid)
case fld[:data_type]
when :integer
unless is_integer?(value)
fld[:error] = msg; valid = false
end
when :float
unless is_numeric?(value)
fld[:error] = msg; valid = false
end
when :boolean
# TODO: do we need validation for boolean
when :button
# Ignore
when :array_integer
unless value.kind_of?(Array)
fld[:error] = msg; valid = false
end
else
data_type = Object.const_get(fld[:data_type].to_s.camelize)
unless value.kind_of?(data_type)
fld[:error] = msg; valid = false
end
end
[valid, fld]
end
def get_dialog_order
@dialogs[:dialog_order]
end
def get_buttons
@dialogs[:buttons] || [:submit, :cancel]
end
def provisioning_tab_list
dialog_names = @dialogs[:dialog_order].collect(&:to_s)
dialog_descriptions = dialog_names.collect do |dialog_name|
@dialogs.fetch_path(:dialogs, dialog_name.to_sym, :description)
end
dialog_display = dialog_names.collect do |dialog_name|
@dialogs.fetch_path(:dialogs, dialog_name.to_sym, :display)
end
tab_list = []
dialog_names.each_with_index do |dialog_name, index|
next if dialog_display[index] == :hide || dialog_display[index] == :ignore
tab_list << {
:name => dialog_name,
:description => dialog_descriptions[index]
}
end
tab_list
end
def get_all_dialogs(refresh_values = true)
@dialogs[:dialogs].each_key { |d| get_dialog(d, refresh_values) }
@dialogs[:dialogs]
end
def get_dialog(dialog_name, refresh_values = true)
dialog = @dialogs.fetch_path(:dialogs, dialog_name.to_sym)
return {} unless dialog
get_all_fields(dialog_name, refresh_values)
dialog
end
def get_all_fields(dialog_name, refresh_values = true)
dialog = @dialogs.fetch_path(:dialogs, dialog_name.to_sym)
return {} unless dialog
dialog[:fields].each_key { |f| get_field(f, dialog_name, refresh_values) }
dialog[:fields]
end
def get_field(field_name, dialog_name = nil, refresh_values = true)
field_name = field_name.to_sym
dialog_name = find_dialog_from_field_name(field_name) if dialog_name.nil?
field = @dialogs.fetch_path(:dialogs, dialog_name.to_sym, :fields, field_name)
return {} unless field
if field.key?(:values_from) && refresh_values
options = field[:values_from][:options] || {}
options[:prov_field_name] = field_name
field[:values] = send(field[:values_from][:method], options)
# Reset then currently selected item if it no longer appears in the available values
if field[:values].kind_of?(Hash)
if field[:values].length == 1
unless field[:auto_select_single] == false
@values[field_name] = field[:values].to_a.first
end
else
currently_selected = get_value(@values[field_name])
unless currently_selected.nil? || field[:values].key?(currently_selected)
@values[field_name] = [nil, nil]
end
end
end
end
field
end
# TODO: Return list in defined ordered
def dialogs
@dialogs[:dialogs].each_pair { |n, d| yield(n, d) }
end
def fields(dialog = nil)
dialog = [*dialog] unless dialog.nil?
@dialogs[:dialogs].each_pair do |dn, d|
next unless dialog.blank? || dialog.include?(dn)
d[:fields].each_pair do |fn, f|
yield(fn, f, dn, d)
end
end
end
def normalize_numeric_fields
fields do |_fn, f, _dn, _d|
if f[:data_type] == :integer
f[:default] = f[:default].to_i_with_method unless f[:default].blank?
unless f[:values].blank?
keys = f[:values].keys.dup
keys.each { |k| f[:values][k.to_i_with_method] = f[:values].delete(k) }
end
end
end
end
# Helper method to write message to the rails log (production.log) for debugging
def rails_logger(_name, _start)
# Rails.logger.warn("#{name} #{start.zero? ? 'start' : 'end'}")
end
def parse_ws_string(text_input, options = {})
self.class.parse_ws_string(text_input, options)
end
def self.parse_ws_string(text_input, options = {})
return parse_request_parameter_hash(text_input, options) if text_input.kind_of?(Hash)
return {} unless text_input.kind_of?(String)
deprecated_warn = "method: parse_ws_string, arg Type => String"
solution = "arg should be a hash"
MiqAeMethodService::Deprecation.deprecation_warning(deprecated_warn, solution)
result = {}
text_input.split('|').each do |value|
next if value.blank?
idx = value.index('=')
next if idx.nil?
key = options[:modify_key_name] == false ? value[0, idx].strip : value[0, idx].strip.downcase.to_sym
result[key] = value[idx + 1..-1].strip
end
result
end
def self.parse_request_parameter_hash(parameter_hash, options = {})
parameter_hash.each_with_object({}) do |param, hash|
key, value = param
key = key.strip.downcase.to_sym unless options[:modify_key_name] == false
hash[key] = value
end
end
def ws_tags(tag_string, parser = :parse_ws_string)
# Tags are passed as category|value. Example: cc|001|environment|test
ws_tags = send(parser, tag_string)
tags = allowed_tags.each_with_object({}) do |v, tags|
tags[v[:name]] = v[:children].each_with_object({}) { |(k, v), tc| tc[v[:name]] = k }
end
ws_tags.collect { |cat, tag| tags.fetch_path(cat.to_s.downcase, tag.downcase) }.compact
end
# @param parser [:parse_ws_string|:parse_ws_string_v1]
# @param additional_values [String] values of the form cc=001|environment=test
def ws_values(additional_values, parser = :parse_ws_string, parser_options = {})
parsed_values = send(parser, additional_values, parser_options)
parsed_values.each_with_object({}) { |(k, v), ws_values| ws_values[k.to_sym] = v }
end
def parse_ws_string_v1(values, _options = {})
na = []
values.to_s.split("|").each_slice(2) do |k, v|
next if v.nil?
na << [k.strip, v.strip]
end
na
end
def find_dialog_from_field_name(field_name)
@dialogs[:dialogs].each_key do |dialog_name|
return dialog_name if @dialogs[:dialogs][dialog_name][:fields].key?(field_name.to_sym)
end
nil
end
def get_value(data)
data.kind_of?(Array) ? data.first : data
end
def set_or_default_field_values(values)
field_names = values.keys
fields do |fn, f, _dn, _d|
if field_names.include?(fn)
if f.key?(:values)
selected_key = nil
if f[:values].key?(values[fn])
selected_key = values[fn]
elsif f.key?(:default) && f[:values].key?(f[:default])
selected_key = f[:default]
else
unless f[:values].blank?
sorted_values = f[:values].sort
selected_key = sorted_values.first.first
end
end
@values[fn] = [selected_key, f[:values][selected_key]] unless selected_key.nil?
else
@values[fn] = values[fn]
end
end
end
end
def clear_field_values(field_names)
fields do |fn, f, _dn, _d|
if field_names.include?(fn)
@values[fn] = f.key?(:values) ? [nil, nil] : nil
end
end
end
def set_value_from_list(fn, f, value, values = nil, partial_key = false)
@values[fn] = [nil, nil]
values = f[:values] if values.nil?
unless value.nil?
@values[fn] = values.to_a.detect do |v|
if partial_key
_log.warn "comparing [#{v[0]}] to [#{value}]"
v[0].to_s.downcase.include?(value.to_s.downcase)
else
v.include?(value)
end
end
if @values[fn].nil?
_log.info "set_value_from_list did not matched an item" if partial_key
@values[fn] = [nil, nil]
else
_log.info "set_value_from_list matched item value:[#{value}] to item:[#{@values[fn][0]}]" if partial_key
end
end
end
def show_dialog(dialog_name, show_flag, enabled_flag = nil)
dialog = @dialogs.fetch_path(:dialogs, dialog_name.to_sym)
unless dialog.nil?
dialog[:display_init] = dialog[:display] if dialog[:display_init].nil?
# If the initial dialog is not set to show then do not modify it here.
return if dialog[:display_init] != :show
dialog[:display] = show_flag
@values["#{dialog_name}_enabled".to_sym] = [enabled_flag] unless enabled_flag.nil?
end
end
def required_description(dlg, fld)
"'#{dlg[:description]}/#{fld[:required_description] || fld[:description]}'"
end
def allowed_filters(options = {})
model_name = options[:category]
return @filters[model_name] unless @filters[model_name].nil?
rails_logger("allowed_filters - #{model_name}", 0)
@filters[model_name] = @requester.get_expressions(model_name).invert
rails_logger("allowed_filters - #{model_name}", 1)
@filters[model_name]
end
def dialog_active?(name, config, values)
return false if config[:display] == :ignore
enabled_field = "#{name}_enabled".to_sym
# Check if the fields hash contains a <dialog_name>_enabled field
enabled = get_value(values[enabled_field])
return false if enabled == false || enabled == "disabled"
true
end
def show_fields(display_flag, field_names, display_field = :display)
fields do |fn, f, _dn, _d|
if field_names.include?(fn)
flag = f[:display_override].blank? ? display_flag : f[:display_override]
f[display_field] = flag
end
end
end
def retrieve_ldap(_options = {})
email = get_value(@values[:owner_email])
unless email.blank?
l = MiqLdap.new
if l.bind_with_default == true
raise _("No information returned for %{email}") % {:email => email} if (d = l.get_user_info(email)).nil?
[:first_name, :last_name, :address, :city, :state, :zip, :country, :title, :company,
:department, :office, :phone, :phone_mobile, :manager, :manager_mail, :manager_phone].each do |prop|
@values["owner_#{prop}".to_sym] = d[prop].nil? ? nil : d[prop].dup
end
@values[:sysprep_organization] = d[:company].nil? ? nil : d[:company].dup
end
end
end
def default_schedule_time(options = {})
# TODO: Added support for "default_from", like values_from, that gets called once after dialog creation
# Update VM description
fields do |fn, f, _dn, _d|
if fn == :schedule_time
f[:default] = Time.now + options[:offset].to_i_with_method if f[:default].nil?
break
end
end
end
def values_less_then(options)
results = options[:values].transform_keys(&:to_i_with_method)
field, include_equals = options[:field], options[:include_equals]
max_value = field.nil? ? options[:value].to_i_with_method : get_value(@values[field]).to_i_with_method
return results if max_value <= 0
results.reject { |k, _v| include_equals == true ? max_value < k : max_value <= k }
end
def tags
vm_tags = @values[:vm_tags]
vm_tags.each do |tag_id|
tag = Classification.find(tag_id)
yield(tag.name, tag.parent.name) unless tag.nil? # yield the tag's name and category
end if vm_tags.kind_of?(Array)
end
def get_tags
tag_string = ''
tags do |tag, cat|
tag_string << ':' unless tag_string.empty?
tag_string << "#{cat}/#{tag}"
end
tag_string
end
def allowed_tags(options = {})
return @tags unless @tags.nil?
region_number = options.delete(:region_number)
# TODO: Call allowed_tags properly from controller - it is currently hard-coded with no options passed
field_options = @dialogs.fetch_path(:dialogs, :purpose, :fields, :vm_tags, :options)
options = field_options unless field_options.nil?
rails_logger('allowed_tags', 0)
st = Time.now
@tags = {}
exclude_list = options[:exclude].blank? ? [] : options[:exclude].collect(&:to_s)
include_list = options[:include].blank? ? [] : options[:include].collect(&:to_s)
single_select = options[:single_select].blank? ? [] : options[:single_select].collect(&:to_s)
cats = Classification.visible.writeable.managed
cats = cats.in_region(region_number) if region_number
cats.each do |t|
next if exclude_list.include?(t.name)
next unless include_list.blank? || include_list.include?(t.name)
# Force passed tags to be single select
single_value = single_select.include?(t.name) ? true : t.single_value?
@tags[t.id] = {:name => t.name, :description => t.description, :single_value => single_value, :children => {}, :id => t.id}
end
ents = Classification.visible.writeable.parent_ids(@tags.keys).with_tag_name
ents = ents.in_region(region_number) if region_number
ents.each do |t|
full_tag_name = "#{@tags[t.parent_id][:name]}/#{t.name}"
next if exclude_list.include?(full_tag_name)
@tags[t.parent_id][:children][t.id] = {:name => t.name, :description => t.description}
end
@tags.delete_if { |_k, v| v[:children].empty? }
# Now sort the tags based on the order passed options. All remaining tags not defined in the order
# will be sorted by description and appended to the other sorted tags
tag_results, tags_to_sort = [], []
sort_order = options[:order].blank? ? [] : options[:order].collect(&:to_s)
@tags.each do |_k, v|
(idx = sort_order.index(v[:name])).nil? ? tags_to_sort << v : tag_results[idx] = v
end
tags_to_sort = tags_to_sort.sort_by { |a| a[:description] }
@tags = tag_results.compact + tags_to_sort
@tags.each do |tag|
tag[:children] = if tag[:children].first.last[:name] =~ /^\d/
tag[:children].sort_by { |_k, v| v[:name].to_i }
else
tag[:children].sort_by { |_k, v| v[:description] }
end
end
rails_logger('allowed_tags', 1)
_log.info "allowed_tags returned [#{@tags.length}] objects in [#{Time.now - st}] seconds"
@tags
end
def allowed_tags_and_pre_tags
pre_tags = @values[:pre_dialog_vm_tags].to_miq_a
return allowed_tags if pre_tags.blank?
tag_cats = allowed_tags.dup
tag_cat_names = tag_cats.collect { |cat| cat[:name] }
Classification.where(:id => pre_tags).each do |tag|
parent = tag.parent
next if tag_cat_names.include?(parent.name)
new_cat = {:name => parent.name, :description => parent.description, :single_value => parent.single_value?, :children => {}, :id => parent.id}
parent.children.each { |c| new_cat[:children][c.id] = {:name => c.name, :description => c.description} }
tag_cats << new_cat
tag_cat_names << new_cat[:name]
end
tag_cats
end
def tag_symbol
:tag_ids
end
def build_ci_hash_struct(ci, props)
nh = MiqHashStruct.new(:id => ci.id, :evm_object_class => ci.class.base_class.name.to_sym)
props.each { |p| nh.send("#{p}=", ci.send(p)) }
nh
end
def get_dialogs
@values[:miq_request_dialog_name] ||= @values[:provision_dialog_name] || dialog_name_from_automate || self.class.default_dialog_file
dp = @values[:miq_request_dialog_name] = File.basename(@values[:miq_request_dialog_name], ".rb")
_log.info "Loading dialogs <#{dp}> for user <#{@requester.userid}>"
d = MiqDialog.find_by("lower(name) = ? and dialog_type = ?", dp.downcase, self.class.base_model.name)
if d.nil?
raise MiqException::Error,
"Dialog cannot be found. Name:[%{name}] Type:[%{type}]" % {:name => @values[:miq_request_dialog_name],
:type => self.class.base_model.name}
end
d.content
end
def get_pre_dialogs
pre_dialogs = nil
pre_dialog_name = dialog_name_from_automate('get_pre_dialog_name')
unless pre_dialog_name.blank?
pre_dialog_name = File.basename(pre_dialog_name, ".rb")
d = MiqDialog.find_by(:name => pre_dialog_name, :dialog_type => self.class.base_model.name)
unless d.nil?
_log.info "Loading pre-dialogs <#{pre_dialog_name}> for user <#{@requester.userid}>"
pre_dialogs = d.content
end
end
pre_dialogs
end
def dialog_name_from_automate(message = 'get_dialog_name', input_fields = [:request_type], extra_attrs = {})
return nil if self.class.automate_dialog_request.nil?
_log.info "Querying Automate Profile for dialog name"
attrs = {'request' => self.class.automate_dialog_request, 'message' => message}
extra_attrs.each { |k, v| attrs[k] = v }
@values.each_key do |k|
key = "dialog_input_#{k.to_s.downcase}"
if attrs.key?(key)
_log.info "Skipping key=<#{key}> because already set to <#{attrs[key]}>"
else
value = (k == :vm_tags) ? get_tags : get_value(@values[k]).to_s
_log.info "Setting attrs[#{key}]=<#{value}>"
attrs[key] = value
end
end
input_fields.each { |k| attrs["dialog_input_#{k.to_s.downcase}"] = send(k).to_s }
ws = MiqAeEngine.resolve_automation_object("REQUEST", @requester, attrs, :vmdb_object => @requester)
if ws && ws.root
dialog_option_prefix = 'dialog_option_'
dialog_option_prefix_length = dialog_option_prefix.length
ws.root.attributes.each do |key, value|
next unless key.downcase.starts_with?(dialog_option_prefix)
next unless key.length > dialog_option_prefix_length
key = key[dialog_option_prefix_length..-1].downcase
_log.info "Setting @values[#{key}]=<#{value}>"
@values[key.to_sym] = value
end
name = ws.root("dialog_name")
return name.presence
end
nil
end
def self.request_type(type)
type.presence.try(:to_sym) || request_class.request_types.first
end
def request_type
self.class.request_type(get_value(@values[:request_type]))
end
def request_class
req_class = self.class.request_class
return req_class unless get_value(@values[:service_template_request]) == true
(req_class.name + "Template").constantize
end
def self.request_class
@workflow_class ||= name.underscore.gsub(/_workflow$/, "_request").camelize.constantize
end
def set_default_values
set_default_user_info rescue nil
end
def set_default_user_info
return if get_dialog(:requester).blank?
if get_value(@values[:owner_email]).blank? && @requester.email.present?
@values[:owner_email] = @requester.email
retrieve_ldap if MiqLdap.using_ldap?
end
show_flag = MiqLdap.using_ldap? ? :show : :hide
show_fields(show_flag, [:owner_load_ldap])
end
def set_request_values(values)
values[:requester_group] ||= @requester.current_group.description
email = values[:owner_email]
if email.present? && values[:owner_group].blank?
values[:owner_group] = User.find_by_lower_email(email, @requester).try(:miq_group_description)
end
end
def password_helper(values = @values, encrypt = true)
self.class.encrypted_options_fields.each do |pwd_key|
next if values[pwd_key].blank?
if encrypt
values[pwd_key].replace(MiqPassword.try_encrypt(values[pwd_key]))
else
values[pwd_key].replace(MiqPassword.try_decrypt(values[pwd_key]))
end
end
end
def update_field_visibility
end
def refresh_field_values(values)
st = Time.now
@values = values
get_source_and_targets(true)
# @values gets modified during this call
get_all_dialogs
values.merge!(@values)
# Update the display flag for fields based on current settings
update_field_visibility
_log.info "refresh completed in [#{Time.now - st}] seconds"
rescue => err
_log.error "[#{err}]"
$log.error err.backtrace.join("\n")
raise err
end
# Run the relationship methods and perform set intersections on the returned values.
# Optional starting set of results maybe passed in.
def allowed_ci(ci, relats, sources, filtered_ids = nil)
result = nil
relats.each do |rsc_type|
rails_logger("allowed_ci - #{rsc_type}_to_#{ci}", 0)
rc = send("#{rsc_type}_to_#{ci}", sources)
rails_logger("allowed_ci - #{rsc_type}_to_#{ci}", 1)
unless rc.nil?
rc = rc.to_a
result = result.nil? ? rc : result & rc
end
end
result = [] if result.nil?
result.reject! { |k, _v| !filtered_ids.include?(k) } unless filtered_ids.nil?
result.each_with_object({}) { |s, hash| hash[s[0]] = s[1] }
end
def process_filter(filter_prop, ci_klass, targets)
rails_logger("process_filter - [#{ci_klass}]", 0)
filter_id = get_value(@values[filter_prop]).to_i
MiqSearch.filtered(filter_id, ci_klass, targets,
:user => @requester,
:miq_group => @requester.current_group,
).tap { rails_logger("process_filter - [#{ci_klass}]", 1) }
end
def find_all_ems_of_type(klass, src = nil)
result = []
each_ems_metadata(src, klass) { |ci| result << ci }
result
end
def find_hosts_under_ci(item)
find_classes_under_ci(item, Host)
end
def find_respools_under_ci(item)
find_classes_under_ci(item, ResourcePool)
end
def find_classes_under_ci(item, klass)
results = []
return results if item.nil?
node = load_ems_node(item, _log.prefix)
each_ems_metadata(node.attributes[:object], klass) { |ci| results << ci } unless node.nil?
results
end
def load_ems_node(item, log_header)
@ems_xml_nodes ||= {}
klass_name = item.kind_of?(MiqHashStruct) ? item.evm_object_class : item.class.base_class.name
node = @ems_xml_nodes["#{klass_name}_#{item.id}"]
$log.error "#{log_header} Resource <#{klass_name}_#{item.id} - #{item.name}> not found in cached resource tree." if node.nil?
node
end
def ems_has_clusters?
found = each_ems_metadata(nil, EmsCluster) { |ci| break(ci) }
return found.evm_object_class == :EmsCluster if found.kind_of?(MiqHashStruct)
false
end
def get_ems_folders(folder, dh = {}, full_path = "")
if folder.evm_object_class == :EmsFolder
if folder.hidden
return dh if folder.name != 'vm'
else
full_path += full_path.blank? ? folder.name.to_s : " / #{folder.name}"
dh[folder.id] = full_path unless folder.type == "Datacenter"
end
end
# Process child folders
node = load_ems_node(folder, _log.prefix)
node.children.each { |child| get_ems_folders(child.attributes[:object], dh, full_path) } unless node.nil?
dh
end
def get_ems_respool(node, dh = {}, full_path = "")
return if node.nil?
if node.kind_of?(XmlHash::Element)
folder = node.attributes[:object]
if node.name == :ResourcePool
full_path += full_path.blank? ? folder.name.to_s : " / #{folder.name}"
dh[folder.id] = full_path
end
end
# Process child folders
node.children.each { |child| get_ems_respool(child, dh, full_path) }
dh
end
def find_datacenter_for_ci(item, ems_src = nil)
find_class_above_ci(item, EmsFolder, ems_src, true)
end
def find_hosts_for_respool(item, ems_src = nil)
hosts = find_class_above_ci(item, Host, ems_src)
return [hosts] unless hosts.blank?
cluster = find_cluster_above_ci(item)
find_hosts_under_ci(cluster)
end
def find_cluster_above_ci(item, ems_src = nil)
find_class_above_ci(item, EmsCluster, ems_src)
end
def find_class_above_ci(item, klass, _ems_src = nil, datacenter = false)
result = nil
node = load_ems_node(item, _log.prefix)
klass_name = klass.name.to_sym
# Walk the xml document parents to find the requested class
while node.kind_of?(XmlHash::Element)
ci = node.attributes[:object]
if node.name == klass_name && (datacenter == false || datacenter == true && ci.type == "Datacenter")
result = ci
break
end
node = node.parent
end
result
end
def each_ems_metadata(ems_ci = nil, klass = nil, &_blk)
if ems_ci.nil?
src = get_source_and_targets
ems_xml = get_ems_metadata_tree(src)
ems_node = ems_xml.try(:root)
else
ems_node = load_ems_node(ems_ci, _log.prefix)
end
klass_name = klass.name.to_sym unless klass.nil?
unless ems_node.nil?
ems_node.each_recursive { |node| yield(node.attributes[:object]) if klass.nil? || klass_name == node.name }
end
end
def get_ems_metadata_tree(src)
@ems_metadata_tree ||= begin
return if src[:ems].nil?
st = Time.zone.now
result = load_ar_obj(src[:ems]).fulltree_arranged(:except_type => "VmOrTemplate")
ems_metadata_tree_add_hosts_under_clusters!(result)
@ems_xml_nodes = {}
xml = MiqXml.newDoc(:xmlhash)
convert_to_xml(xml, result)
_log.info "EMS metadata collection completed in [#{Time.zone.now - st}] seconds"
xml
end
end
def ems_metadata_tree_add_hosts_under_clusters!(result)
result.each do |obj, children|
ems_metadata_tree_add_hosts_under_clusters!(children)
obj.hosts.each { |h| children[h] = {} } if obj.kind_of?(EmsCluster)
end
end
def convert_to_xml(xml, result)
result.each do |obj, children|
@ems_xml_nodes["#{obj.class.base_class}_#{obj.id}"] = node = xml.add_element(obj.class.base_class.name, :object => ci_to_hash_struct(obj))
convert_to_xml(node, children)
end
end
def add_target(dialog_key, key, klass, result)
key_id = "#{key}_id".to_sym
result[key_id] = get_value(@values[dialog_key])
result[key_id] = nil if result[key_id] == 0
result[key] = ci_to_hash_struct(klass.find_by(:id => result[key_id])) unless result[key_id].nil?
end
def ci_to_hash_struct(ci)
return if ci.nil?
return ci.collect { |c| ci_to_hash_struct(c) } if ci.respond_to?(:collect)
method_name = "#{ci.class.base_class.name.underscore}_to_hash_struct".to_sym
return send(method_name, ci) if respond_to?(method_name, true)
default_ci_to_hash_struct(ci)
end
def host_to_hash_struct(ci)
build_ci_hash_struct(ci, [:name, :vmm_product, :vmm_version, :state, :v_total_vms])
end
def vm_or_template_to_hash_struct(ci)
v = build_ci_hash_struct(ci, [:name, :platform])
v.snapshots = ci.snapshots.collect { |si| ci_to_hash_struct(si) }
v
end
def ems_folder_to_hash_struct(ci)
build_ci_hash_struct(ci, [:name, :type, :hidden])
end
def storage_to_hash_struct(ci)
storage_clusters = ci.storage_clusters.blank? ? nil : ci.storage_clusters.collect(&:name).join(', ')
build_ci_hash_struct(ci, [:name, :free_space, :total_space, :storage_domain_type]).tap do |hs|
hs.storage_clusters = storage_clusters
end
end
def snapshot_to_hash_struct(ci)
build_ci_hash_struct(ci, [:name, :current?])
end
def customization_spec_to_hash_struct(ci)