-
Notifications
You must be signed in to change notification settings - Fork 358
/
application_controller.rb
2356 lines (2061 loc) · 89.2 KB
/
application_controller.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
# rubocop:disable Metrics/LineLength, Lint/EmptyWhen
require 'open-uri'
require 'simple-rss'
# Need to make sure models are autoloaded
MiqCompare
MiqFilter
MiqExpression
MiqSearch
class ApplicationController < ActionController::Base
include Vmdb::Logging
if Vmdb::Application.config.action_controller.allow_forgery_protection
# Add CSRF protection for this controller, which enables the
# verify_authenticity_token before_action, with a random secret.
# This secret is reset to a value found in the miq_databases table in
# MiqWebServerWorkerMixin.configure_secret_token for rails server, UI, and
# web service worker processes.
protect_from_forgery :secret => SecureRandom.hex(64), :except => [:authenticate, :external_authenticate, :kerberos_authenticate, :saml_login, :initiate_saml_login, :csp_report], :with => :exception
end
helper GtlHelper
helper ChartingHelper
Charting.load_helpers(self)
include ActionView::Helpers::NumberHelper # bring in the number helpers for number_to_human_size
include ActionView::Helpers::TextHelper
include ActionView::Helpers::DateHelper
include ApplicationHelper
include Mixins::TimeHelper
include Mixins::MenuSection
include Mixins::GenericToolbarMixin
include Mixins::ControllerConstants
include Mixins::CustomButtons
include Mixins::CheckedIdMixin
include ParamsHelper
helper ToolbarHelper
helper JsHelper
helper QuadiconHelper
helper ImageEncodeHelper
helper ViewFormattingHelper
helper CloudResourceQuotaHelper
# Expose constants as a helper method in views
helper do
def pp_choices
PPCHOICES
end
end
include_concern 'AdvancedSearch'
include_concern 'Automate'
include_concern 'Buttons'
include_concern 'CiProcessing'
include_concern 'Compare'
include_concern 'CurrentUser'
include_concern 'DialogRunner'
include_concern 'Explorer'
include_concern 'Filter'
include_concern 'MiqRequestMethods'
include_concern 'Network'
include_concern 'Performance'
include_concern 'PolicySupport'
include_concern 'ReportDownloads'
include_concern 'SessionSize'
include_concern 'SysprepAnswerFile'
include_concern 'Tags'
include_concern 'Tenancy'
include_concern 'Timelines'
include_concern 'Timezone'
include_concern 'TreeSupport'
include_concern 'WaitForTask'
before_action :reset_toolbar
before_action :set_session_tenant
before_action :get_global_session_data, :except => [:resize_layout, :authenticate]
before_action :set_user_time_zone
before_action :set_gettext_locale
before_action :allow_websocket
after_action :set_global_session_data, :except => [:resize_layout]
TIMELINES_FOLDER = Rails.root.join("product", "timelines")
ONE_MILLION = 1_000_000 # Setting high number incase we don't want to display paging controls on list views
PERPAGE_TYPES = %w(grid tile list reports).each_with_object({}) { |value, acc| acc[value] = value.to_sym }.freeze
TREND_MODEL = "VimPerformanceTrend".freeze # Performance trend model name requiring special processing
# Default UI settings
DEFAULT_SETTINGS = {
:quadicons => { # Show quad icons, by resource type
:service => true,
:ems => true,
:ems_cloud => true,
:host => true,
:miq_template => true,
:physical_server => true,
:storage => true,
:vm => true,
:ems_container => true
},
:views => { # List view setting, by resource type
:authkeypaircloud => "list",
:availabilityzone => "list",
:hostaggregate => "list",
:catalog => "list",
:cm_providers => "list",
:cm_configured_systems => "list",
:compare => "expanded",
:compare_mode => "details",
:condition => "list",
:container => "list",
:containergroup => "list",
:containernode => "list",
:containerservice => "list",
:containerroute => "list",
:containerproject => "list",
:containerreplicator => "list",
:containerimage => "list",
:containerimageregistry => "list",
:persistentvolume => "list",
:containerbuild => "list",
:containertemplate => "list",
:cloudobjectstorecontainer => "list",
:cloudobjectstoreobject => "list",
:cloudtenant => "list",
:cloudvolume => "list",
:cloudvolumebackup => "list",
:cloudvolumesnapshot => "list",
:drift => "expanded",
:drift_mode => "details",
:emscluster => "grid",
:emscontainer => "grid",
:filesystem => "list",
:flavor => "list",
:host => "grid",
:job => "list",
:manageiq_providers_cloudmanager => "grid",
:manageiq_providers_cloudmanager_template => "list",
:manageiq_providers_cloudmanager_vm => "grid",
:manageiq_providers_containermanager => "grid",
:manageiq_providers_inframanager => "grid",
:manageiq_providers_inframanager_vm => "grid",
:manageiq_providers_inframanager_template => "list",
:manageiq_providers_middlewaremanager => "grid",
:manageiq_providers_physicalinframanager => "list",
:manageiq_providers_storagemanager => "list",
:middlewaredatasource => "list",
:middlewaredeployment => "list",
:middlewaredomain => "list",
:middlewaremessaging => "list",
:middlewareserver => "list",
:middlewareservergroup => "list",
:miqaction => "list",
:miqaeclass => "list",
:miqaeinstance => "list",
:miqevent => "list",
:miqpolicy => "list",
:miqpolicyset => "list",
:miqreportresult => "list",
:miqrequest => "list",
:miqtemplate => "list",
:orchestrationstack => "list",
:orchestrationtemplate => "list",
:servicetemplate => "list",
:storagemanager => "list",
:miqtask => "list",
:ms => "grid",
:physicalserver => "list",
:policy => "list",
:policyset => "grid",
:resourcepool => "grid",
:service => "grid",
:scanhistory => "list",
:storage_files => "list",
:summary_mode => "dashboard",
:registryitems => "list",
:serverbuild => "list",
:storage => "grid",
:tagging => "grid",
:treesize => "20",
:vm => "grid",
:vmortemplate => "grid",
:vmcompare => "compressed"
},
:perpage => { # Items per page, by view setting
:grid => 20,
:tile => 20,
:list => 20,
:reports => 20
},
:topology => {
:containers_max_items => 100
},
:display => {
:startpage => "/dashboard/show",
:reporttheme => "MIQ",
:quad_truncate => "m",
:theme => "red", # Luminescent Blue
:taskbartext => true, # Show button text on taskbar
:vmcompare => "Compressed", # Start VM compare and drift in compressed mode
:hostcompare => "Compressed", # Start Host compare in compressed mode
:timezone => nil, # This will be set when the user logs in
:display_vms => false # don't display vms by default
},
}.freeze
AE_MAX_RESOLUTION_FIELDS = 5 # Maximum fields to show for automation engine resolution screens
PROV_STATES = {
"pending_approval" => N_("Pending Approval"),
"approved" => N_("Approved"),
"denied" => N_("Denied")
}.freeze
def local_request?
Rails.env.development? || Rails.env.test?
end
def allow_websocket
override_content_security_policy_directives(:connect_src => ["'self'", websocket_origin])
end
private :allow_websocket
def reset_toolbar
@toolbars = {}
end
# Convert Controller Name to Actual Model
def self.model
@model ||= name[0..-11].safe_constantize
rescue
@model = nil
end
def self.permission_prefix
controller_name
end
def self.table_name
@table_name ||= model.name.underscore
end
def table_name
self.class.table_name
end
def self.session_key_prefix
table_name
end
# This will rescue any un-handled exceptions
rescue_from StandardError, :with => :error_handler
def self.handle_exceptions?
Thread.current[:application_controller_handles_exceptions] != false
end
def self.handle_exceptions=(v)
Thread.current[:application_controller_handles_exceptions] = v
end
def error_handler(e)
raise e unless ApplicationController.handle_exceptions?
logger.fatal "Error caught: [#{e.class.name}] #{e.message}\n#{e.backtrace.join("\n")}"
msg = case e
when ::ActionController::RoutingError
_("Action not implemented")
when ::AbstractController::ActionNotFound # Prevent Rails showing all known controller actions
_("Unknown Action")
else
e.message
end
render_exception(msg)
end
private :error_handler
def render_exception(msg)
respond_to do |format|
format.js do
render :update do |page|
page << javascript_prologue
page.replace_html("center_div", :partial => "layouts/exception_contents", :locals => {:message => msg})
page << "miqSparkle(false);"
page << javascript_hide_if_exists("adv_searchbox_div")
end
end
format.html do # HTML, send error screen
@layout = "exception"
response.status = 500
render(:template => "layouts/exception", :locals => {:message => msg})
end
format.any { head :not_found } # Anything else, just send 404
end
end
private :render_exception
def change_tab
redirect_to(:action => params[:tab], :id => params[:id])
end
def download_summary_pdf
# do not build quadicon links
@embedded = true
@showlinks = false
# encode images and embed in HTML that is sent to Prince
@base64_encode_images = true
@record = identify_record(params[:id])
yield if block_given?
return if record_no_longer_exists?(@record)
get_tagdata(@record) if @record.try(:taggings)
@display = "download_pdf"
set_summary_pdf_data
end
def build_targets_hash(items)
@targets_hash ||= {}
# if array of objects came in
items.each do |item|
@targets_hash[item.id.to_i] = item
end
end
# Send chart data to the client
def render_chart
if params[:report]
rpt = MiqReport.for_user(current_user).find_by(:name => params[:report])
rpt.generate_table(:userid => session[:userid])
else
rpt = if session[:report_result_id]
MiqReportResult.for_user(current_user).find(session[:report_result_id]).report_results
elsif session[:rpt_task_id].present?
MiqTask.find(session[:rpt_task_id]).task_results
else
@report
end
end
# Following works around a caching issue that causes timeouts for charts in IE using SSL
if is_browser_ie?
response.headers["Cache-Control"] = "cache, must-revalidate"
response.headers["Pragma"] = "public"
end
rpt.to_chart(settings(:display, :reporttheme), true, MiqReport.graph_options)
render Charting.render_format => rpt.chart
end
# Method for creating object with data for report.
# Report is either grid/table or list.
# @param controller_name name of JS controller. Typically `reportDataController`.
def init_report_data(controller_name)
view_url = view_to_url(@view) unless @view.nil?
{
:controller_name => controller_name,
:data => {
:model_name => @display.nil? && !self.class.model.nil? ? self.class.model.to_s.tableize : @display,
:activeTree => x_active_tree.to_s,
:gtlType => @gtl_type,
:parentId => params[:id],
:sortColIdx => @sortcol,
:sortDir => @sortdir,
:isExplorer => @explorer,
:showUrl => view_url
}
}
end
# Private method for processing params.
# params can contain these options:
# @param params parameters object.
# @option params :explorer [String]
# String value of boolean if we are fetching data for explorer or not. "true" | "false"
# @option params :active_tree [String]
# String value of active tree node.
# @option params :model_id [String]
# String value of model's ID to be filtered with.
def process_params_options(params)
restore_quadicon_options(params[:additional_options] || {})
options = from_additional_options(params[:additional_options] || {})
if params[:explorer]
params[:action] = "explorer"
@explorer = params[:explorer] == "true"
end
# if params[:active_tree] && defined? get_node_info
# node_info = get_node_info(x_node, false)
# options.merge!(node_info) if node_info.kind_of?(Hash)
# end
# handle exceptions
if params[:model_name]
options = case params[:model_name]
when 'MiqRequest'
page_display_options
when 'miq_tasks'
jobs_info
when 'physical_servers_with_host'
options.merge!(generate_options)
else
options
end
end
if params[:parent_id]
parent_id = from_cid(params[:parent_id])
unless parent_id.nil?
options[:parent] = identify_record(parent_id, controller_to_model) if parent_id && options[:parent].nil?
end
end
options[:parent] = options[:parent] || @parent
options[:association] = HAS_ASSOCATION[params[:model_name]] if HAS_ASSOCATION.include?(params[:model_name])
options[:selected_ids] = params[:records]
options
end
private :process_params_options
# Method for processing params and finding correct model for current params.
# @param params parameters object.
# @option params :active_tree [String]
# String value of active tree node.
# @option params :model [String]
# String value of model to be selected.
# @param options options Object.
# @option options :model [Object]
# If model was chosen somehow before calling this method use this model instead of finding it.
def process_params_model_view(params, options)
model_view = options[:model_name].constantize if options[:model_name]
model_view ||= model_string_to_constant(params[:model_name]) if params[:model_name]
model_view ||= model_from_active_tree(params[:active_tree].to_sym) if params[:active_tree]
model_view || controller_to_model
end
private :process_params_model_view
def set_variables_report_data(settings, current_view)
settings[:sort_dir] = @sortdir unless settings.nil?
settings[:sort_col] = @sortcol unless settings.nil?
@edit = session[:edit]
@policy_sim = @edit[:policy_sim] unless @edit.nil?
controller, _action = db_to_controller(current_view.db) unless current_view.nil?
if !@policy_sim.nil? && session[:policies] && !session[:policies].empty?
settings[:url] = '/' + controller + '/policies/'
end
settings
end
private :set_variables_report_data
def allowed_tenant_names
current_tenant = User.current_user.current_tenant
(current_tenant.descendants + [current_tenant]).map(&:name)
end
private :allowed_tenant_names
# Exception: Model Tenant and named_scope :in_my_region need to filter out the parent name if current user has no access to it.
# This can be removed once this is somehow fixed on the backend.
def filter_parent_name_tenant(table)
table.data.map! do |x|
x['parent_name'] = '' unless allowed_tenant_names.include?(x['parent_name'])
x
end
table
end
private :filter_parent_name_tenant
# Method for fetching report data. These data can be displayed in Grid/Tile/List.
# This method will first process params for options and then for current model.
# From these options and model we get view (for fetching data) and settings (will hold info about paging).
# Then this method will return JSON object with settings and data.
def report_data
options = process_params_options(params)
if options.nil? || options[:view].nil?
model_view = process_params_model_view(params, options)
@edit = session[:edit]
@view, settings = get_view(model_view, options, true)
else
@view = options[:view]
settings = options[:pages]
end
settings = set_variables_report_data(settings, @view)
if options && options[:named_scope] == "in_my_region" && options[:model] == "Tenant"
@view.table = filter_parent_name_tenant(@view.table)
end
# Foreman has some unassigned rows which needs to be added after view is fetched
if options && options[:unassigned_profile_row] && options[:unassigned_configuration_profile]
options[:unassigned_profile_row][:id] ||= options[:unassigned_profile_row]['manager_id']
@view.table.data.push(options[:unassigned_profile_row])
@targets_hash[options[:unassigned_profile_row]['id']] = options[:unassigned_configuration_profile]
end
render :json => {
:settings => settings,
:data => view_to_hash(@view, true),
:messages => @flash_array
}
end
def event_logs
@record = identify_record(params[:id])
@view = session[:view] # Restore the view from the session to get column names for the display
return if record_no_longer_exists?(@record)
@lastaction = "event_logs"
obj = @record.kind_of?(Vm) ? "vm" : "host"
bc_text = @record.kind_of?(Vm) ? _("Event Logs") : _("ESX Logs")
@sb[:action] = params[:action]
@explorer = true if @record.kind_of?(VmOrTemplate)
params[:display] = "event_logs"
if !params[:show].nil? || !params[:x_show].nil?
id = params[:show] ? params[:show] : params[:x_show]
@item = @record.event_logs.find(from_cid(id))
drop_breadcrumb(:name => @record.name + " (#{bc_text})", :url => "/#{obj}/event_logs/#{@record.id}?page=#{@current_page}")
drop_breadcrumb(:name => @item.name, :url => "/#{obj}/show/#{@record.id}?show=#{@item.id}")
show_item
else
drop_breadcrumb(:name => @record.name + " (#{bc_text})", :url => "/#{obj}/event_logs/#{@record.id}")
@listicon = "event_logs"
show_details(EventLog, :association => "event_logs")
end
end
# Common method to show a standalone report
def report_only
@report_only = true # Indicate stand alone report for views
# Render error message if report doesn't exist
if params[:rr_id].nil? && @sb.fetch_path(:pages, :rr_id).nil?
add_flash(_("This report isn't generated yet. It cannot be rendered."), :error)
render :partial => "layouts/flash_msg"
return
end
# Dashboard widget will send in report result id else, find report result in the sandbox
search_id = params[:rr_id] ? params[:rr_id].to_i : @sb[:pages][:rr_id]
rr = MiqReportResult.for_user(current_user).find(search_id)
session[:report_result_id] = rr.id # Save report result id for chart rendering
session[:rpt_task_id] = nil # Clear out report task id, using a saved report
@report = rr.report
@html = report_build_html_table(rr.report_results, rr.html_rows.join)
@ght_type = params[:type] || (@report.graph.blank? ? 'tabular' : 'hybrid')
@render_chart = (@ght_type == 'hybrid')
render 'shared/show_report'
end
def show_statistics
db = self.class.model
@display = "show_statistics"
session[:stats_record_id] = params[:id] if params[:id]
@record = find_record_with_rbac(db, session[:stats_record_id])
# Need to use paged_view_search code, once the relationship is working. Following is workaround for the demo
@stats = @record.derived_metrics
drop_breadcrumb(:name => _("Utilization"), :url => "/#{db}/show_statistics/#{@record.id}?refresh=n")
render :template => "show_statistics"
end
# moved this method here so it can be accessed from pxe_server controller as well
def log_depot_validate # this is a terrible name, it doesn't validate log_depots
@schedule = nil # setting to nil, since we are using same view for both db_back and log_depot edit
# if zone is selected in tree replace tab#3
pfx = if x_active_tree == :diagnostics_tree
if @sb[:active_tab] == "diagnostics_database"
# coming from diagnostics/database tab
"dbbackup"
end
elsif session[:edit] && session[:edit].key?(:pxe_id)
# add/edit pxe server
"pxe"
else
# add/edit dbbackup schedule
"schedule"
end
id = params[:id] ? params[:id] : "new"
if pfx == "pxe"
return unless load_edit("#{pfx}_edit__#{id}")
settings = {:username => @edit[:new][:log_userid], :password => @edit[:new][:log_password]}
settings[:uri] = @edit[:new][:uri_prefix] + "://" + @edit[:new][:uri]
else
settings = {:username => params[:log_userid], :password => params[:log_password]}
settings[:uri] = "#{params[:uri_prefix]}://#{params[:uri]}"
settings[:uri_prefix] = params[:uri_prefix]
end
begin
if pfx == "pxe"
msg = _('PXE Credentials successfuly validated')
PxeServer.verify_depot_settings(settings)
else
msg = _('Depot Settings successfuly validated')
MiqSchedule.new.verify_file_depot(settings)
end
rescue => bang
add_flash(_("Error during 'Validate': %{error_message}") % {:error_message => bang.message}, :error)
else
add_flash(msg)
end
@changed = (@edit[:new] != @edit[:current]) if pfx == "pxe"
javascript_flash
end
# to reload currently displayed summary screen in explorer
def reload
@_params[:id] = x_node
tree_select
end
def filesystem_download
fs = identify_record(params[:id], Filesystem)
send_data fs.contents, :filename => fs.name
end
def adv_search_text_clear
if params[:in_explorer] == "true"
@search_text = @sb[:search_text] = nil
reload
end
end
protected
def render_flash(add_flash_text = nil, severity = nil)
javascript_flash(:text => add_flash_text, :severity => severity)
end
def tagging_explorer_controller?
false
end
private
def move_cols_left_right(direction)
flds = direction == "right" ? "available_fields" : "selected_fields"
edit_fields = direction == "right" ? "available_fields" : "fields"
sort_fields = direction == "right" ? "fields" : "available_fields"
if !params[flds.to_sym] || params[flds.to_sym].empty? || params[flds.to_sym][0] == ""
lr_messages = {
"left" => _("No fields were selected to move left"),
"right" => _("No fields were selected to move right")
}
add_flash(lr_messages[direction], :error)
else
@edit[:new][edit_fields.to_sym].each do |af| # Go thru all available columns
if params[flds.to_sym].include?(af[1].to_s) # See if this column was selected to move
next if @edit[:new][sort_fields.to_sym].include?(af) # Only move if it's not there already
@edit[:new][sort_fields.to_sym].push(af) # Add it to the new fields list
end
end
# Remove selected fields
@edit[:new][edit_fields.to_sym].delete_if { |af| params[flds.to_sym].include?(af[1].to_s) }
@edit[:new][sort_fields.to_sym].sort! # Sort the selected fields array
@refresh_div = "column_lists"
@refresh_partial = "column_lists"
end
end
# Build a Catalog Items explorer tree
def build_ae_tree(type = :ae, name = :ae_tree)
# build the ae tree to show the tree select box for entry point
if x_active_tree == :automate_tree && @edit && @edit[:new][:fqname]
nodes = @edit[:new][:fqname].split("/")
@open_nodes = []
# if there are more than one nested namespaces
nodes.each_with_index do |_node, i|
if i == nodes.length - 1
# check if @cls is there, to make sure the class/instance still exists in Automate db
inst = @cls ? MiqAeInstance.find_by(:class_id => @cls.id, :name => nodes[i]) : nil
# show this as selected/expanded node when tree loads
if inst
@open_nodes.push("aei-#{inst.id}")
@active_node = "aei-#{to_cid(inst.id)}"
end
elsif i == nodes.length - 2
@cls = MiqAeClass.find_by(:namespace_id => @ns.id, :name => nodes[i])
@open_nodes.push("aec-#{to_cid(@cls.id)}") if @cls
else
@ns = MiqAeNamespace.find_by(:name => nodes[i])
@open_nodes.push("aen-#{to_cid(@ns.id)}") if @ns
end
end
end
if name == :ae_tree
TreeBuilderAeClass.new(name, type, @sb)
else
@automate_tree = TreeBuilderAutomate.new(name, type, @sb)
end
end
# moved this method here so it can be accessed from pxe_server controller as well
def log_depot_set_verify_status
if (@edit[:new][:log_password] == @edit[:new][:log_verify]) && @edit[:new][:uri_prefix] != "nfs" &&
(!@edit[:new][:uri].blank? && !@edit[:new][:log_userid].blank? && !@edit[:new][:log_password].blank? && !@edit[:new][:log_verify].blank?)
@edit[:log_verify_status] = true
elsif @edit[:new][:uri_prefix] == "nfs" && !@edit[:new][:uri].blank?
@edit[:log_verify_status] = true
else
@edit[:log_verify_status] = false
end
end
# Build an audit object when configuration is changed in configuration and ops controllers
def build_config_audit(new, current)
if controller_name == "ops" && @sb[:active_tab] == "settings_server"
server = MiqServer.find(@sb[:selected_server_id])
msg = "#{server.name} [#{server.id}] in zone #{server.my_zone} VMDB config updated"
else
msg = "VMDB config updated"
end
{
:event => "vmdb_config_update",
:userid => session[:userid],
:message => build_audit_msg(new, current, msg)
}
end
PASSWORD_FIELDS = [:password, :_pwd, :amazon_secret, :token].freeze
def filter_config(data)
@parameter_filter ||=
ActionDispatch::Http::ParameterFilter.new(
Rails.application.config.filter_parameters + PASSWORD_FIELDS
)
return data.map { |e| filter_config(e) } if data.kind_of?(Array)
data.kind_of?(Hash) ? @parameter_filter.filter(data) : data
end
def password_field?(k)
PASSWORD_FIELDS.any? { |p| k.to_s.ends_with?(p.to_s) }
end
def build_audit_msg(new, current, msg_in)
msg_arr = []
new.each_key do |k|
if !k.to_s.ends_with?("password2", "verify") &&
(current.nil? || (new[k] != current[k]))
if password_field?(k) # Asterisk out password fields
msg_arr << "#{k}:[*]#{' to [*]' unless current.nil?}"
elsif new[k].kind_of?(Hash) # If the field is a hash,
# Make current a blank hash for following comparisons
current[k] = {} if !current.nil? && current[k].nil?
# process keys of the current and new hashes
(new[k].keys | (current.nil? ? [] : current[k].keys)).each do |hk|
if current.nil? || (new[k][hk] != current[k][hk])
if password_field?(hk) # Asterisk out password fields
msg_arr << "#{hk}:[*]#{' to [*]' unless current.nil?}"
else
msg_arr << "#{hk}:[" +
(current.nil? ? "" : "#{filter_config(current[k][hk])}] to [") +
"#{filter_config(new[k][hk])}]"
end
end
end
else
msg_arr << "#{k}:[" +
(current.nil? ? "" : "#{filter_config(current[k])}] to [") +
"#{filter_config(new[k])}]"
end
end
end
"#{msg_in} (#{msg_arr.join(', ')})"
end
# Disable client side caching of the response being sent
def disable_client_cache
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
# IE will not allow downloads if no-cache is used because it won't save the file in the temp folder, so use private
response.headers["Pragma"] = if is_browser_ie?
'private'
else
'no-cache'
end
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end
# Common method enable/disable schedules
def schedule_enable_disable(schedules, enabled)
schedules.select { |schedule| schedule.enabled != enabled }
.sort_by { |e| e.name.downcase }.each do |schedule|
schedule.enabled = enabled
schedule.save!
end
end
# Build the user_emails hash for edit screens needing the edit_email view
def build_user_emails_for_edit
@edit[:user_emails] = {}
to_email = @edit[:new][:email][:to] || []
users_in_current_groups = User.with_current_user_groups.distinct.sort_by { |u| u.name.downcase }
users_in_current_groups.each do |u|
next if u.email.blank?
next if to_email.include?(u.email)
@edit[:user_emails][u.email] = "#{u.name} (#{u.email})"
end
end
# Build the first html page for a report results record
def report_first_page(rr)
rr.build_html_rows_for_legacy # Create the report result details for legacy reports
@report = rr.report # Grab the report, not including table
@sb[:pages] ||= {}
@sb[:pages][:rr_id] = rr.id
@sb[:pages][:items] = @report.extras[:total_html_rows]
@sb[:pages][:perpage] = settings(:perpage, :reports)
@sb[:pages][:current] = 1
total = @sb[:pages][:items] / @sb[:pages][:perpage]
total += 1 if @sb[:pages][:items] % @sb[:pages][:perpage] != 0
@sb[:pages][:total] = total
@title = @report.title
if @report.extras[:total_html_rows].zero?
add_flash(_("No records found for this report"), :warning)
html = nil
else
html = report_build_html_table(@report,
rr.html_rows(:page => @sb[:pages][:current],
:per_page => @sb[:pages][:perpage]).join)
end
html
end
def calculate_lastaction(lastaction)
return 'show_list' unless lastaction
parts = lastaction.split('__')
if parts.first == "replace_cell"
parts.last
else
params[:id] == 'new' ? 'show_list' : lastaction
end
end
def report_edit_aborted(lastaction)
add_flash(_("Edit aborted! %{product} does not support the browser's back button or access from multiple tabs or windows of the same browser. Please close any duplicate sessions before proceeding.") % {:product => Vmdb::Appliance.PRODUCT_NAME}, :error)
session[:flash_msgs] = @flash_array.dup
if request.xml_http_request? # Is this an Ajax request?
if lastaction == "configuration"
edit
redirect_to_action = 'index'
else
redirect_to_action = lastaction
end
js_args = {
:action => redirect_to_action,
:id => params[:id],
:escape => false,
:load_edit_err => true
}
javascript_redirect(javascript_process_redirect_args(js_args))
else
redirect_to :action => lastaction, :id => params[:id], :escape => false
end
end
def load_edit(key, lastaction = @lastaction)
lastaction = calculate_lastaction(lastaction)
if session.fetch_path(:edit, :key) != key
report_edit_aborted(lastaction)
return false
end
@edit = session[:edit]
true
end
# Put all time profiles for the current user in session[:time_profiles] for pulldowns
def get_time_profiles(obj = nil)
session[:time_profiles] = {}
region_id = obj ? obj.region_id : MiqRegion.my_region_number
time_profiles = TimeProfile.profiles_for_user(session[:userid], region_id)
time_profiles.collect { |tp| session[:time_profiles][tp.id] = tp.description }
end
def selected_time_profile_for_pull_down
tp = TimeProfile.profile_for_user_tz(session[:userid], session[:user_tz])
tp = TimeProfile.default_time_profile if tp.nil?
if tp.nil? && !session[:time_profiles].blank?
first_id_in_hash = Array(session[:time_profiles].invert).min_by(&:first).last
tp = TimeProfile.find_by(:id => first_id_in_hash)
end
tp
end
def set_time_profile_vars(tp, options)
if tp
options[:time_profile] = tp.id
options[:time_profile_tz] = tp.tz
options[:time_profile_days] = tp.days
else
options[:time_profile] = nil
options[:time_profile_tz] = nil
options[:time_profile_days] = nil
end
options[:tz] = options[:time_profile_tz]
end
# if authenticating or past login screen
def set_user_time_zone
user = current_user || (params[:user_name].presence && User.find_by(:userid => params[:user_name]))
session[:user_tz] = Time.zone = (user ? user.get_timezone : server_timezone)
end
# Initialize the options for server selection
def init_server_options(show_all = true)
@server_options ||= {}
@server_options[:zones] = []
@server_options[:zone_servers] = {}
MiqServer.all.each do |ms|
next if !show_all && !ms.started? # Collect all or only started servers
if ms.id == MiqServer.my_server.id # This is the current server
@server_options[:server_id] ||= ms.id
next # Don't add to list
end
@server_options[:zones].push(ms.my_zone) unless @server_options[:zones].include?(ms.my_zone)
@server_options[:zone_servers][ms.my_zone] ||= []
@server_options[:zone_servers][ms.my_zone].push(ms.id)
end
@server_options[:server_id] ||= MiqServer.my_server.id
@server_options[:zone] = MiqServer.find(@server_options[:server_id]).my_zone
@server_options[:hostname] = ""
@server_options[:ipaddress] = ""
end
def populate_reports_menu(tree_type = 'reports', mode = 'menu')
# checking to see if group (used to be role) was selected in menu editor tree, or came in from reports/timeline tree calls
group = !session[:role_choice].blank? ? MiqGroup.find_by(:description => session[:role_choice]) : current_group
@sb[:rpt_menu] = get_reports_menu(group, tree_type, mode)
end
def reports_group_title
tenant_name = current_tenant.name
if current_user.admin_user?
_("%{tenant_name} (All Groups)") % {:tenant_name => tenant_name}
else
_("%{tenant_name} (Group): %{group_description}") %
{:tenant_name => tenant_name,
:group_description => current_user.current_group.description}
end
end
def get_reports_menu(group = current_group, tree_type = "reports", mode = "menu")
rptmenu = []
reports = []
folders = []
user = current_user
@sb[:grp_title] = reports_group_title
data = []
if !group.settings || group.settings[:report_menus].blank? || mode == "default"
# array of all reports if menu not configured
data = MiqReport.for_user(current_user).where(:template_type => "report").order(:rpt_type, :filename, :name)
data.where.not(:timeline => nil) if tree_type == "timeline"
data.each do |r|
r_group = r.rpt_group == "Custom" ? "#{@sb[:grp_title]} - Custom" : r.rpt_group # Get the report group
title = r_group.reverse.split('-', 2).collect(&:reverse).collect(&:strip).reverse
if @temp_title != title[0]
@temp_title = title[0]
reports = []
folders = []
end
if title[1].nil?
if title[0] == @temp_title
reports.push(r.name) unless reports.include?(r.name)
rptmenu.push([title[0], reports]) unless rptmenu.include?([title[0], reports])
end
else
if @temp_title1 != title[1]
reports.sort!
reports = []
@temp_title1 = title[1]
end
rptmenu.push([title[0], folders]) unless rptmenu.include?([title[0], folders])
reports.push(r.name) unless reports.include?(r.name)
folders.push([title[1], reports]) unless folders.include?([title[1], reports])
end
end
else
# Building custom reports array for super_admin/admin roles, it doesnt show up on menu if their menu was set which didnt contain custom folder in it
temp = []
subfolder = %w(Custom)
@custom_folder = [@sb[:grp_title]]
@custom_folder.push([subfolder]) unless @custom_folder.include?([subfolder])