SHARE
TWEET

Untitled

a guest May 21st, 2019 89 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. class AlarmsController < ApplicationController
  3.   include Ivona::Speech
  4.  
  5.   before_filter :ensure_authenticated_user, :setup_user_scope
  6.  
  7.   respond_to :json
  8.  
  9.   def setup_user_scope()
  10.     if current_user.is_super?
  11.       @companies = Company.all
  12.       @data_centers = DataCenter.includes(:data_centers_instances).all
  13.       @instances = Instance.active_with_source
  14.     else
  15.       @companies = current_user.companies
  16.       @data_centers = DataCenter.includes(:data_centers_instances).company(@companies)
  17.       @instances = Instance.active.from_dcs(@data_centers.map(&:id)).active
  18.     end
  19.   end
  20.  
  21.   def index
  22.     timestamp = Time.now
  23.     if current_user.is_super?
  24.       @active_alarms = Alarm.active_with_source
  25.       @comments = AlarmComment.all
  26.     else
  27.       # @active_alarms = Alarm.from_instances(@instances.map(&:id)).active
  28.       @active_alarms = Alarm.from_instances_with_source(current_user.allow_instances).active
  29.       @comments = AlarmComment.from_instances(current_user.allow_instances) # @instances.map(&:id)
  30.     end
  31.  
  32.     @descriptions = Dsc.all
  33.     instance_alarms_dat = {}
  34.     alarms_id_map = {}
  35.     safe_comments = []
  36.     @active_alarms.each do |alarm|
  37.       instance_id = alarm.instance_id
  38.       alarms_id_map[instance_id] ||= []
  39.       alarms_id_map[instance_id].push(alarm.id)
  40.       instance_alarms_dat[instance_id] ||= {:last_metric => nil, :last_alarm => nil}
  41.       key = ( alarm.object == 'last_metric' ? :last_metric : :last_alarm )
  42.       instance_alarms_dat[instance_id][key] = alarm.dat if instance_alarms_dat[instance_id][key].to_i < alarm.dat.to_i
  43.       alarm_comments = []
  44.       @comments.each do | comment |
  45.         if comment.alarm_id == alarm.id
  46.           alarm_comments.push(comment.id)
  47.           safe_comments.push(comment)
  48.         end
  49.       end
  50.       alarm.alarm_comment_ids = alarm_comments
  51.     end
  52.     blackout_instances = {}
  53.     Blackout.active.each { | bo | blackout_instances[bo.up] = bo }
  54.     active_instances = {}
  55.     clusters = {}
  56.     safe_instances = []
  57.     # sql = "SELECT n, up, dat FROM (SELECT n, up, dat, rank() over (partition by up order by n desc) rnk FROM monitor.monitor) WHERE rnk = 1"
  58.     sql = "select inst n,(select dat from  monitor.monitor m where m.n=a.n) dat from (select i.n inst,(select  max(m.n) n from monitor.monitor m where m.up=i.n) n from monitor.instance i where i.td>systimestamp) a"
  59.     ldats_query = ActiveRecord::Base.connection.execute(sql)
  60.     last_dates = {}
  61.     while row = ldats_query.fetch do
  62.       last_dates[row[0].to_i] = row[1]
  63.     end
  64.     @instances.each do |instance|
  65.       instance.alarm_ids = alarms_id_map[instance.id]
  66.       active_instances[instance.id] = true
  67.       if blackout_instances.has_key?(instance.id)
  68.         instance.is_blackout = true
  69.         instance.blackout_dsc = blackout_instances[instance.id].dsc
  70.         instance.blackout_fd = blackout_instances[instance.id].fd
  71.         instance.blackout_td = blackout_instances[instance.id].td
  72.         instance.blackout_notify = blackout_instances[instance.id].type_notify
  73.         instance.blackout_user_id = blackout_instances[instance.id].user_id
  74.       else
  75.         if instance_alarms_dat.has_key?(instance.id)
  76.           if (Time.now.to_i - instance_alarms_dat[instance.id][:last_alarm].to_i) < 30*60
  77.             instance.last_mon_date = instance_alarms_dat[instance.id][:last_alarm]
  78.           end
  79.         end
  80.         unless instance.last_mon_date
  81.           # last_mon_date = MonitorMonitor.where(n: MonitorMonitor.select('max(n)').where(up: instance.id)).pluck(:dat)
  82.           # instance.last_mon_date = last_mon_date[0] || Time.at(0)
  83.           instance.last_mon_date = last_dates[instance.id.to_i] || Time.at(0)
  84.           if instance_alarms_dat.has_key?(instance.id) && instance_alarms_dat[instance.id][:last_metric].to_i >= instance.last_mon_date.to_i
  85.             instance.has_last_metric_alarm = true
  86.             instance.last_metric_alarm_date = instance_alarms_dat[instance.id][:last_metric]
  87.           end
  88.         end
  89.       end
  90.       if instance.cluster_name && !instance.is_blackout
  91.         cluster_key = "#{instance.sid}|#{instance.cluster_name}|#{instance.dbid}"
  92.         clusters[cluster_key] = [] unless clusters.has_key?(cluster_key)
  93.         last_mon = instance.last_mon_date || Time.at(0)
  94.         clusters[cluster_key].push([instance.id, last_mon])
  95.       end
  96.       safe_instances.push(instance)
  97.     end
  98.     clusters.each do | key, inst |
  99.       inst.sort! { |a,b| b[1] <=> a[1]}
  100.       inst.slice(1, inst.length - 1).each do | el |
  101.         safe_instances.delete_if {|item| item.id == el[0]}
  102.         active_instances.delete(el[0])
  103.       end
  104.     end
  105.     companies_info = {}
  106.     @data_centers.each do |data_center|
  107.       alarm_ids = []
  108.       instance_ids = []
  109.       data_center.data_centers_instances.each do |dc_instance|
  110.         next unless active_instances.has_key?(dc_instance.instance_id)
  111.         alarm_ids += alarms_id_map[dc_instance.instance_id] if alarms_id_map.has_key?(dc_instance.instance_id)
  112.         instance_ids.push(dc_instance.instance_id)
  113.       end
  114.       data_center.alarm_ids = alarm_ids
  115.       data_center.instance_ids = instance_ids
  116.       companies_info[data_center.company_id] = {:dcs => [], :instances => [], :alarms => [], :schemes => []} unless companies_info.has_key?(data_center.company_id)
  117.       companies_info[data_center.company_id][:dcs].push(data_center.id)
  118.       companies_info[data_center.company_id][:instances] += instance_ids
  119.       companies_info[data_center.company_id][:alarms] += alarm_ids
  120.     end
  121.     @company_schemes = CompanyScheme.company(@companies)
  122.     @company_schemes.each do |scheme|
  123.       companies_info[scheme.company_id] = {:dcs => [], :instances => [], :alarms => [], :schemes => []} unless companies_info.has_key?(scheme.company_id)
  124.       companies_info[scheme.company_id][:schemes].push(scheme.id)
  125.     end
  126.     @companies.each do | company |
  127.       next unless companies_info.has_key?(company.id)
  128.       company.data_center_ids = companies_info[company.id][:dcs]
  129.       company.instance_ids = companies_info[company.id][:instances]
  130.       company.alarm_ids = companies_info[company.id][:alarms]
  131.       company.company_scheme_ids = companies_info[company.id][:schemes]
  132.     end
  133.     # active_instances = safe_instances.collect {|item| item.id}
  134.  
  135.     ::AlarmSerializer.root = false
  136.     ::InstanceSerializer.root = false
  137.     ::DataCenterSerializer.root = false
  138.     ::CompanySerializer.root = false
  139.     ::DscSerializer.root = false
  140.     ::CompanySchemeSerializer.root = false
  141.     ::AlarmCommentSerializer.root = false
  142.     logger.debug(' =========== Alarm index end ========')
  143.  
  144.     render :json => {
  145.         :timestamp => (timestamp.to_f * 1000.0).to_i,
  146.         :alarms => @active_alarms.map { |alarm| ::AlarmSerializer.new(alarm) },
  147.         :instances => safe_instances.map { |instance| ::InstanceSerializer.new(instance) },
  148.         :data_centers => @data_centers.map { |data_center| ::DataCenterSerializer.new(data_center) },
  149.         :companies => @companies.map { |company| ::CompanySerializer.new(company) },
  150.         :dscs => @descriptions.map { |dsc| ::DscSerializer.new(dsc) },
  151.         :company_schemes => @company_schemes.map { |scheme| ::CompanySchemeSerializer.new(scheme) },
  152.         :alarm_comments => safe_comments.map { |scheme| ::AlarmCommentSerializer.new(scheme) }
  153.     }
  154.   end
  155.  
  156.   def latest
  157.     delta_time = 30*60
  158.     timestamp = Time.now
  159.     @@del_logger ||= Logger.new("#{Rails.root}/log/latest.log")
  160.     if params[:lastUpdate].to_i > 0
  161.       start_time = Time.at(params[:lastUpdate].to_i / 1000, params[:lastUpdate].to_i % 1000)
  162.       if timestamp.to_i - start_time.to_i > 8*60*60
  163.         start_time = timestamp - 8*60*60
  164.       elsif start_time.to_i - 30 > timestamp.to_i - 30
  165.         start_time = timestamp - 30
  166.       end
  167.       if current_user && current_user.is_super?
  168.         @close = Alarm.includes(:data_centers_instance).where('EDAT >= ? AND EDAT < ?', start_time - delta_time, Time.now)
  169.         @new = Alarm.active_with_source.where('DAT > ?', start_time - delta_time).order(rdat: :desc) # .active  or N=1344639 or N=1339354
  170.         @update = Alarm.active_with_source.where('DAT < ? AND RDAT > ?', start_time, start_time - delta_time)
  171.  
  172.         @comments = AlarmComment.where('created_at > ?', start_time - delta_time)
  173.       else
  174.         # @close = Alarm.includes(:data_centers_instance).company(@user_companies.pluck(:id)).where('EDAT >= ? AND EDAT < ?', start_time, Time.now)
  175.  
  176.         # @instances.map(&:id)
  177.         @close = Alarm.from_instances_with_source(current_user.allow_instances).where('EDAT >= ? AND EDAT < ?', start_time - delta_time, Time.now)
  178.         @new = Alarm.from_instances_with_source(current_user.allow_instances).active.where('DAT > ?', start_time - delta_time).order(rdat: :desc)
  179.         @update = Alarm.from_instances_with_source(current_user.allow_instances).active.where('DAT < ? AND RDAT > ?', start_time, start_time - delta_time)
  180.  
  181.         @comments = AlarmComment.from_instances(current_user.allow_instances).where('created_at > ?', start_time - delta_time)
  182.         # @new = Alarm.active_with_source.company(@user_companies.pluck(:id)).where('DAT > ?', start_time).order(rdat: :desc) # .active  or N=1344639 or N=1339354
  183.         # @update = Alarm.active_with_source.company(@user_companies.pluck(:id)).where('DAT < ? AND RDAT > ?', start_time, start_time)
  184.       end
  185.  
  186.  
  187.       # Test data
  188.       #@new.push(create_test_alarm(:new, :warn))
  189.       #@new.push(create_test_alarm(:new, :crit))
  190.       #@new.push(create_test_alarm(:new, :warn))
  191.       #@update.push(create_test_alarm(:update, :warn))
  192.       #@close.push(create_test_alarm(:close, :crit, 1427325))
  193.       # End test data
  194.  
  195.       # Dev log for latest data
  196.       if @new.length > 0 || @update.length > 0 || @close.length > 0
  197.         @@del_logger.info("[#{timestamp}] Latest for #{current_user.login} from #{request.remote_ip} time #{start_time}")
  198.         if @new.length > 0
  199.           @@del_logger.info("  New alarms")
  200.           @new.each { |c| @@del_logger.info("\tn:#{c.n} warntyp:#{c.warntyp} up:#{c.up} object:'#{c.object}' val:'#{c.val}' dat:'#{c.dat}' rdat:'#{c.rdat}' edat:'#{c.edat}'") }
  201.         end
  202.         if @update.length > 0
  203.           @@del_logger.info("  Updated alarms")
  204.           @update.each { |c| @@del_logger.info("\tn:#{c.n} warntyp:#{c.warntyp} up:#{c.up} object:'#{c.object}' val:'#{c.val}' dat:'#{c.dat}' rdat:'#{c.rdat}' edat:'#{c.edat}'") }
  205.         end
  206.         if @close.length > 0
  207.           @@del_logger.info("  Closed alarms")
  208.           @close.each { |c| @@del_logger.info("\tn:#{c.n} warntyp:#{c.warntyp} up:#{c.up} object:'#{c.object}' val:'#{c.val}' dat:'#{c.dat}' rdat:'#{c.rdat}' edat:'#{c.edat}'") }
  209.         end
  210.       end
  211.  
  212.       alarm_comments = {}
  213.       AlarmComment.where('created_at > ?', start_time) do | ac |
  214.         alarm_comments[ac.alarm_id] = [] unless alarm_comments.has_key?(ac.alarm_id)
  215.         alarm_comments[ac.alarm_id].push(ac.id)
  216.       end
  217.       @new.each do |alarm|
  218.         if alarm_comments.has_key?(alarm.id)
  219.           comments = []
  220.           AlarmComment.where('alarm_id = ?', alarm.id) { | ac | comments.push(ac.id) }
  221.           alarm.alarm_comment_ids = comments
  222.         end
  223.         if alarm.warntyp_num == 2 || alarm.warntyp_num == 3
  224.           speech_text = (alarm.warntyp_num == 3 ? 'Critical' : 'Warning') + ' alarm on ' + alarm.instance.host + ' ' + alarm.instance.sid
  225.           alarm.speech_url = get_speech_url(speech_text)
  226.         end
  227.       end
  228.       @update.each do |alarm|
  229.         if alarm_comments.has_key?(alarm.id)
  230.           comments = []
  231.           AlarmComment.where('alarm_id = ?', alarm.id) { | ac | comments.push(ac.id) }
  232.           alarm.alarm_comment_ids = comments
  233.         end
  234.       end
  235.       @instance_update = {}
  236.       sql = "select inst n,(select dat from monitor.monitor m where m.n=a.n) dat from (select i.n inst,(select  max(m.n) n from monitor.monitor m where m.up=i.n) n from monitor.instance i where i.td>systimestamp and i.n in (#{current_user.allow_instances.to_sql})) a"
  237.       if current_user && current_user.is_super?
  238.         sql = "select inst n,(select dat from monitor.monitor m where m.n=a.n) dat from (select i.n inst,(select  max(m.n) n from monitor.monitor m where m.up=i.n) n from monitor.instance i where i.td>systimestamp) a"
  239.       end
  240.       ldats_query = ActiveRecord::Base.connection.execute(sql)
  241.       while row = ldats_query.fetch do
  242.         @instance_update[row[0].to_i] = {last_mon_date: row[1]}
  243.       end
  244.       # TODO: Если у инстанса нет событий статус блэкаута не изменится
  245.       Blackout.active.each do | bo |
  246.         next unless @instance_update.has_key?(bo.up.to_i)
  247.         @instance_update[bo.up.to_i][:is_blackout] = true
  248.         @instance_update[bo.up.to_i][:blackout_dsc] = bo.dsc
  249.         @instance_update[bo.up.to_i][:blackout_fd] = bo.fd
  250.         @instance_update[bo.up.to_i][:blackout_td] = bo.td
  251.         @instance_update[bo.up.to_i][:blackout_notify] = bo.type_notify
  252.         @instance_update[bo.up.to_i][:blackout_user_id] = bo.user_id
  253.       end
  254.       @instance_data = []
  255.       @instance_update.each {|key,data| data[:id] = key; @instance_data.push(data)}
  256.  
  257.       ::AlarmSerializer.root = false
  258.       ::AlarmCommentSerializer.root = false
  259.       render :json => {
  260.           :timestamp => (timestamp.to_f * 1000.0).to_i,
  261.           :close => @close.map { |alarm| ::AlarmSerializer.new(alarm)},
  262.           :new => @new.map { |alarm| ::AlarmSerializer.new(alarm)},
  263.           :update => @update.map { |alarm| ::AlarmSerializer.new(alarm)},
  264.           :instance_update => @instance_data,
  265.           :comments => @comments.map { |comment| ::AlarmCommentSerializer.new(comment)}
  266.       }
  267.  
  268.     else
  269.       render json: {}
  270.     end
  271.   end
  272.  
  273.   def show
  274.     ::AlarmSerializer.root = true
  275.     render json: Alarm.find(params[:id])
  276.   end
  277.  
  278.   def update
  279.     @alarm = Alarm.find(params[:id])
  280.     safe_params = alarm_params
  281.     if safe_params[:close_control].to_s == 'close'
  282.       if current_user.is_super?
  283.         close_time = Time.now
  284.         @alarm.update(edat: close_time)
  285.         close_comment = CloseAlarmComment.new(comment: safe_params[:close_comment], alarm_id: @alarm.id, instance_id: @alarm.up, closed_at: close_time)
  286.         close_comment.user = current_user
  287.         close_comment.save
  288.         render json: {}
  289.       else
  290.         render :json => {
  291.             :errors => {blackout: 'Permission denied'}
  292.         }, status: :unprocessable_entity
  293.       end
  294.     else
  295.       render json: {}
  296.     end
  297.   end
  298.  
  299.   def history
  300.     instance_id = params[:instance]
  301.     @instance = @instances.to_a.find { |inst| inst.n == instance_id.to_i }
  302.     return head(:unauthorized) if @instance.nil?
  303.     where_str = ''
  304.     where_params = {}
  305.     logger.debug("Params 1 #{params[:alarm_id].inspect} #{params[:alarm_id].nil?}")
  306.     if params[:alarm_id] != ''
  307.       where_str = 'MONITOR.ALARM.N = :alarm_id'
  308.       where_params[:alarm_id] = params[:alarm_id]
  309.     end
  310.     if params[:dbobject] != ''
  311.       where_str += ' and ' if where_str.length > 0
  312.       where_str += 'MONITOR.ALARM.OBJECT = :dbobject'
  313.       where_params[:dbobject] = params[:dbobject]
  314.     end
  315.     if params[:type] != ''
  316.       where_str += ' and ' if where_str.length > 0
  317.       where_str += 'MONITOR.ALARM.TYPE = :type'
  318.       where_params[:type] = params[:type]
  319.     end
  320.     @alarms = Alarm.closed_with_source.from_instances(@instance).where(where_str, where_params).order(edat: :desc)
  321.     @descriptions = Dsc.all
  322.     @comments = CloseAlarmComment.where(instance_id: @instance.id)
  323.     comments_map = {}
  324.     @comments.each { | comment | comments_map[comment.alarm_id] = comment }
  325.     alarms_id_map = {}
  326.     @alarms.each do |alarm|
  327.       instance_id = alarm.instance_id
  328.       alarms_id_map[instance_id] ||= []
  329.       alarms_id_map[instance_id].push(alarm.id)
  330.       if comments_map.has_key?(alarm.id)
  331.         alarm.close_comment = comments_map[alarm.id].comment
  332.         alarm.close_user_id = comments_map[alarm.id].user_id
  333.       end
  334.     end
  335.     @instances.each do |instance|
  336.       instance.alarm_ids = alarms_id_map[instance.id]
  337.     end
  338.     companies_info = {}
  339.     @data_centers.each do |data_center|
  340.       alarm_ids = []
  341.       instance_ids = []
  342.       data_center.data_centers_instances.each do |dc_instance|
  343.         alarm_ids += alarms_id_map[dc_instance.instance_id] if alarms_id_map.has_key?(dc_instance.instance_id)
  344.         instance_ids.push(dc_instance.instance_id)
  345.       end
  346.       data_center.alarm_ids = alarm_ids
  347.       data_center.instance_ids = instance_ids
  348.       companies_info[data_center.company_id] = {:dcs => [], :instances => [], :alarms => []} unless companies_info.has_key?(data_center.company_id)
  349.       companies_info[data_center.company_id][:dcs].push(data_center.id)
  350.       companies_info[data_center.company_id][:instances] += instance_ids
  351.       companies_info[data_center.company_id][:alarms] += alarm_ids
  352.     end
  353.     @companies.each do | company |
  354.       next unless companies_info.has_key?(company.id)
  355.       company.data_center_ids = companies_info[company.id][:dcs]
  356.       company.instance_ids = companies_info[company.id][:instances]
  357.       company.alarm_ids = companies_info[company.id][:alarms]
  358.     end
  359.     ::AlarmHistorySerializer.root = false
  360.     ::InstanceSerializer.root = false
  361.     ::DataCenterSerializer.root = false
  362.     ::CompanySerializer.root = false
  363.     ::DscSerializer.root = false
  364.     render :json => {
  365.         :alarm_histories => @alarms.map { |alarm| ::AlarmHistorySerializer.new(alarm) },
  366.         :instances => @instances.map { |instance| ::InstanceSerializer.new(instance) },
  367.         :data_centers => @data_centers.map { |data_center| ::DataCenterSerializer.new(data_center) },
  368.         :companies => @companies.map { |company| ::CompanySerializer.new(company) },
  369.         :dscs => @descriptions.map { |dsc| ::DscSerializer.new(dsc) }
  370.     }
  371.   end
  372.  
  373.   private
  374.   def alarm_params
  375.     params.require(:alarm).permit(:close_control, :close_comment)
  376.   end
  377.  
  378.   def create_test_alarm(op, level, id = nil)
  379.  
  380.     level_num = 2
  381.     level_str = 'critical'
  382.     if level == :warn
  383.       level_num = 4
  384.       level_str = 'warning'
  385.     elsif level == :info
  386.       level_num = 6
  387.       level_str = 'informational'
  388.     end
  389.  
  390.     test_instance_id = 32653
  391.     test_dc_id = 17
  392.     test_company_id = 1
  393.  
  394.     edat = Time.local(2999, 12, 31)
  395.     dat = Time.now
  396.     rdat = Time.now
  397.     if op == :update
  398.       dat = Time.at(dat.to_i - 30)
  399.       rdat = Time.at(rdat.to_i - 3)
  400.     elsif op == :close
  401.       edat = Time.at(dat - 30)
  402.       dat = edat
  403.       rdat = edat
  404.     end
  405.  
  406.     c_alarm = Alarm.new do | a |
  407.       if op == :close
  408.         a.n = id
  409.       else
  410.         a.n = Random.new.rand(2000000..3000000)
  411.       end
  412.       a.edat = edat
  413.       a.rdat = rdat
  414.       a.dat = dat
  415.       a.up = test_instance_id
  416.       a.type = 'test'
  417.       a.warntyp = level_str
  418.       a.severity_level = level_num
  419.       a.object = "Test #{level_str} alarm"
  420.       a.val = 'Test_test_test_test_test_test Test_test_test_test_test_test Test_test_test_test_test_test'
  421.       a.data_centers_instance = DataCentersInstance.new do | dc |
  422.         dc.instance_id = test_instance_id
  423.         dc.data_center_id = test_dc_id
  424.         dc.company_id = test_company_id
  425.       end
  426.     end
  427.     c_alarm
  428.   end
  429. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top