-
Notifications
You must be signed in to change notification settings - Fork 358
/
application_controller.rb
2372 lines (2077 loc) · 92.9 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 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::CustomButtons
include Mixins::CheckedIdMixin
helper ToolbarHelper
helper JsHelper
helper QuadiconHelper
helper CloudResourceQuotaHelper
include_concern 'Automate'
include_concern 'CiProcessing'
include_concern 'Compare'
include_concern 'CurrentUser'
include_concern 'Buttons'
include_concern 'DialogRunner'
include_concern 'Explorer'
include_concern 'Filter'
include_concern 'MiqRequestMethods'
include_concern 'Performance'
include_concern 'PolicySupport'
include_concern 'Tags'
include_concern 'Tenancy'
include_concern 'Timelines'
include_concern 'Timezone'
include_concern 'TreeSupport'
include_concern 'SysprepAnswerFile'
include_concern 'ReportDownloads'
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]
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].constantize
end
def self.permission_prefix
controller_name
end
def self.table_name
@table_name ||= model.name.underscore
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
@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, typ = true)
@targets_hash ||= {}
if typ
# if array of objects came in
items.each do |item|
@targets_hash[item.id.to_i] = item
end
else
# if only array of id's came in look up for a record, following code is not being used right now.
klass = session[:view].db.constantize
items.each do |item|
@targets_hash[item.to_i] = klass.find(item)
end
end
end
# Send chart data to the client
def render_chart
if params[:report]
rpt = MiqReport.find_by_name(params[:report])
rpt.generate_table(:userid => session[:userid])
else
rpt = if session[:report_result_id]
MiqReportResult.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
###########################################################################
# Use ajax to retry until the passed in task is complete, then rerun the original action
# This action can be called directly or via URL
# If called directly, options will have the task_id
# Otherwise, task_id will be in the params
###########################################################################
def wait_for_task
@edit = session[:edit] # If in edit, need to preserve @edit object
raise Forbidden, _('Invalid input for "wait_for_task".') unless params[:task_id]
@edit = session[:edit] # If in edit, need to preserve @edit object
session[:async] ||= {}
session[:async][:interval] ||= 1000 # Default interval to 1 second
session[:async][:params] ||= {}
if MiqTask.find(params[:task_id].to_i).state != "Finished" # Task not done --> retry
browser_refresh_task(params[:task_id])
else # Task done
@_params.instance_variable_get(:@parameters).merge!(session[:async][:params]) # Merge in the original parms and
send(session.fetch_path(:async, :params, :action)) # call the orig. method
end
end
def browser_refresh_task(task_id)
session[:async][:interval] += 250 if session[:async][:interval] < 5000 # Slowly move up to 5 second retries
render :update do |page|
page << javascript_prologue
ajax_call = remote_function(:url => {:action => 'wait_for_task', :task_id => task_id})
page << "setTimeout(\"#{ajax_call}\", #{session[:async][:interval]});"
end
end
private :browser_refresh_task
#
# :task_id => id of task to wait for
# :action => 'action_to_call' -- action to be called when the task finishes
#
def initiate_wait_for_task(options = {})
task_id = options[:task_id]
session[:async] ||= {}
session[:async][:interval] ||= 1000 # Default interval to 1 second
session[:async][:params] ||= {}
session[:async][:params] = copy_hash(params) # Save the incoming parms
session[:async][:params][:task_id] = task_id
# override method to be called, when the task is done
session[:async][:params][:action] = options[:action] if options.key?(:action)
browser_refresh_task(task_id)
end
private :initiate_wait_for_task
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)
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
# Handle paging bar controls
def saved_report_paging
# Check new paging parms coming in
if params[:ppsetting]
@settings.store_path(:perpage, :reports, params[:ppsetting].to_i)
@sb[:pages][:current] = 1
total = @sb[:pages][:items] / settings(:perpage, :reports)
total += 1 if @sb[:pages][:items] % settings(:perpage, :reports) != 0
@sb[:pages][:total] = total
end
@sb[:pages][:current] = params[:page].to_i if params[:page]
@sb[:pages][:perpage] = settings(:perpage, :reports)
rr = MiqReportResult.find(@sb[:pages][:rr_id])
@html = report_build_html_table(rr.report_results,
rr.html_rows(:page => @sb[:pages][:current],
:per_page => @sb[:pages][:perpage]).join)
render :update do |page|
page << javascript_prologue
page.replace("report_html_div", :partial => "layouts/report_html")
page.replace_html("paging_div", :partial => 'layouts/saved_report_paging_bar',
:locals => {:pages => @sb[:pages]})
page << javascript_hide_if_exists("form_buttons_div")
page << javascript_show_if_exists("rpb_div_1")
page << "miqSparkle(false)"
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.find(search_id)
session[:report_result_id] = rr.id # Save report result id for render_zgraph
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')
@title = @report.title
@zgraph = case @ght_type
when 'tabular' then nil
when 'hybrid' then true
end
render controller_name == 'report' ? 'show' : '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
if x_active_tree == :diagnostics_tree
if @sb[:active_tab] == "diagnostics_database"
# coming from diagnostics/database tab
pfx = "dbbackup"
end
else
if session[:edit] && session[:edit].key?(:pxe_id)
# add/edit pxe server
pfx = "pxe"
else
# add/edit dbbackup schedule
pfx = "schedule"
end
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
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].length == 0 || 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
unless @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
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_and_name(@cls.id, nodes[i]) : nil
# show this as selected/expanded node when tree loads
@open_nodes.push("aei-#{inst.id}") if inst
@active_node = "aei-#{to_cid(inst.id)}" if inst
elsif i == nodes.length - 2
@cls = MiqAeClass.find_by_namespace_id_and_name(@ns.id, 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
if is_browser_ie?
response.headers["Pragma"] = "private"
else
response.headers["Pragma"] = "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)
MiqSchedule.where(:id => schedules, :enabled => !enabled).order("lower(name)").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.name
@title = @report.title
if @report.extras[:total_html_rows] == 0
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 => I18n.t('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|
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
name = "#{ms.name} [#{ms.id}]"
@server_options[:zones].push(ms.my_zone) unless @server_options[:zones].include?(ms.my_zone) # Collect all of the zones
@server_options[:zone_servers][ms.my_zone] ||= [] # Initialize zone servers array
@server_options[:zone_servers][ms.my_zone].push(ms.id) # Add server to the zone
end
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, :groups => ui_lookup(:models => "MiqGroup")}
else
_("%{tenant_name} (%{group}): %{group_description}") %
{:tenant_name => tenant_name,
:group => ui_lookup(:model => "MiqGroup"),
: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
@rep = MiqReport.all.sort_by { |r| [r.rpt_type, r.filename.to_s, r.name] }
if tree_type == "timeline"
@data = @rep.reject { |r| r.timeline.nil? }
else
@data = @rep.select do |r|
r.template_type == "report" && !r.template_type.blank?
end
end
@data.each do |r|
next if r.template_type != "report" && !r.template_type.blank?
r_group = r.rpt_group == "Custom" ? "#{@sb[:grp_title]} - Custom" : r.rpt_group # Get the report group
title = r_group.split('-').collect(&:strip)
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 = []
@temp_title1 = title[1]
end
rptmenu.push([title[0], folders]) unless rptmenu.include?([title[0], folders])
if user.admin_user?
# for admin user show all the reports
reports.push(r.name) unless reports.include?(r.name)
else
# for non admin users, only show custom reports for their group
if title[1] == "Custom"
reports.push(r.name) if !reports.include?(r.name) && (r.miq_group && user.current_group.id == r.miq_group.id)
else
reports.push(r.name) unless reports.include?(r.name)
end
end
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])
custom = MiqReport.all.sort_by { |r| [r.rpt_type, r.filename.to_s, r.name] }
rep = custom.select do |r|
r.rpt_type == "Custom" && (user.admin_user? || r.miq_group_id.to_i == current_group.try(:id))
end.map(&:name).uniq
subfolder.push(rep) unless subfolder.include?(rep)
temp.push(@custom_folder) unless temp.include?(@custom_folder)
if tree_type == "timeline"
temp2 = []
group.settings[:report_menus].each do |menu|
folder_arr = []
menu_name = menu[0]
menu[1].each_with_index do |reports, _i|
reports_arr = []
folder_name = reports[0]
reports[1].each do |rpt|
r = MiqReport.find_by_name(rpt)
if r && !r.timeline.nil?
temp2.push([menu_name, folder_arr]) unless temp2.include?([menu_name, folder_arr])
reports_arr.push(rpt) unless reports_arr.include?(rpt)
folder_arr.push([folder_name, reports_arr]) unless folder_arr.include?([folder_name, reports_arr])
end
end
end
end
else
temp2 = group.settings[:report_menus]
end
rptmenu = temp.concat(temp2)
end
# move Customs folder as last item in tree
rptmenu[0].each do |r|
if r.class == String && r == @sb[:grp_title]
@custom_folder = copy_array(rptmenu[0]) if @custom_folder.nil?
# Keeping My Company Reports folder on top of the menu tree only if user is on edit tab, else delete it from tree
# only add custom folder if it has any reports
rptmenu.push(rptmenu[0]) unless rptmenu[0][1][0][1].empty?
rptmenu.delete_at(0)
end
end
rptmenu
end
# Render the view data to a Hash structure for the list view
def view_to_hash(view)
# Get the time zone in effect for this view
tz = (view.db.downcase == 'miqschedule') ? server_timezone : Time.zone
root = {:head => [], :rows => []}
has_checkbox = !@embedded && !@no_checkboxes
has_listicon = !%w(miqaeclass miqaeinstance).include?(view.db.downcase) # do not add listicon for AE class show_list
# Show checkbox or placeholder column
if has_checkbox
root[:head] << {:is_narrow => true}
end
if has_listicon
# Icon column
root[:head] << {:is_narrow => true}
end
view.headers.each_with_index do |h, i|
align = [:fixnum, :integer, :Fixnum, :float].include?(column_type(view.db, view.col_order[i])) ? 'right' : 'left'
root[:head] << {:text => h,
:sort => 'str',
:col_idx => i,
:align => align}
end
if @row_button # Show a button as last col
root[:head] << {:is_narrow => true}
end
# Add table elements
table = view.sub_table ? view.sub_table : view.table
table.data.each do |row|
new_row = {:id => list_row_id(row), :cells => []}
root[:rows] << new_row
if has_checkbox
new_row[:cells] << {:is_checkbox => true}
end
# Generate html for the list icon
if has_listicon
item = listicon_item(view, row['id'])
new_row[:cells] << {:title => _('View this item'),
:image => fileicon(item, view),
:icon => listicon_icon(item)}
end
view.col_order.each_with_index do |col, col_idx|
celltext = nil
case view.col_order[col_idx]
when 'db'
celltext = Dictionary.gettext(row[col], :type => :model, :notfound => :titleize)
when 'approval_state'
celltext = _(PROV_STATES[row[col]])
when 'prov_type'
celltext = row[col] ? _(ServiceTemplate::CATALOG_ITEM_TYPES[row[col]]) : ''
when "result"
new_row[:cells] << {:span => result_span_class(row[col]), :text => row[col].titleize}
when "severity"
new_row[:cells] << {:span => severity_span_class(row[col]), :text => row[col].titleize}
when 'state'
celltext = row[col].titleize
when 'hardware.bitness'
celltext = row[col] ? "#{row[col]} bit" : ''
when 'image?'
celltext = row[col] ? _("Image") : _("Snapshot")
else
# Use scheduled tz for formatting, if configured
if ['miqschedule'].include?(view.db.downcase)
celltz = row['run_at'][:tz] if row['run_at'] && row['run_at'][:tz]
end
celltext = format_col_for_display(view, row, col, celltz || tz)
end
new_row[:cells] << {:text => celltext} if celltext
end
if @row_button # Show a button in the last col
new_row[:cells] << {:is_button => true,
:text => @row_button[:label],
:title => @row_button[:title],
:onclick => "#{@row_button[:function]}(\"#{row['id']}\");"}
end
end
root
end
def result_span_class(value)
case value.downcase
when "pass"
"label label-success center-block"
when "fail"
"label label-danger center-block"
else
"label label-primary center-block"
end
end
def severity_span_class(value)
case value.downcase
when "high"
"label label-danger center-block"
when "medium"
"label label-warning center-block"
else
"label label-low-severity center-block"
end
end
def calculate_pct_img(val)
val == 100 ? 20 : ((val + 2) / 5.25).round # val is the percentage value of free space
end
def listicon_item(view, id = nil)
id = @id if id.nil?
if @targets_hash
@targets_hash[id] # Get the record from the view
else
klass = view.db.constantize
klass.find(id) # Read the record from the db
end
end
# Return the icon classname for the list view icon of a db,id pair
# this always supersedes fileicon if not nil
def listicon_icon(item)
item.decorate.try(:fonticon)
end
# Return the image name for the list view icon of a db,id pair
def fileicon(item, view)
default = "100/#{(@listicon || view.db).underscore}.png"
image = case item
when EventLog, OsProcess
"100/#{@listicon.downcase}.png"
when Storage
"100/piecharts/datastore/#{calculate_pct_img(item.v_free_space_percent_of_total)}.png"
when MiqRequest
item.decorate.fileicon || "100/#{@listicon.downcase}.png"
when ManageIQ::Providers::CloudManager::AuthKeyPair
"100/auth_key_pair.png"
else
item.decorate.try(:fileicon)
end
image || default
end
def get_host_for_vm(vm)
@hosts = [vm.host] if vm.host
end
# Add a msg to the @flash_array