Class: CfnGuardian::DisplayFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/cfnguardian/display_formatter.rb

Instance Method Summary collapse

Constructor Details

#initialize(alarms = []) ⇒ DisplayFormatter

Returns a new instance of DisplayFormatter.



8
9
10
# File 'lib/cfnguardian/display_formatter.rb', line 8

def initialize(alarms=[])
  @alarms = alarms
end

Instance Method Details

#alarm_history(history, type) ⇒ Object



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
# File 'lib/cfnguardian/display_formatter.rb', line 156

def alarm_history(history,type)
  rows = []
  line_width = 100
  
  history.each do |item|
    data = JSON.load(item.history_data)
    
    case type
    when "StateUpdate" 
      rows << [
        item.timestamp.localtime, 
        item.history_summary,
        data['newState']['stateReason'].word_wrap
      ]
    when "ConfigurationUpdate"
      updated = []
      if data['type'] == 'Update'
        data['originalUpdatedFields'].each do |k,v|
          unless k == 'alarmConfigurationUpdatedTimestamp'
            updated << "#{k}: #{v} -> #{data['updatedAlarm'][k]}"
          end
        end
      end        
      rows << [
        item.timestamp.localtime, 
        data['type'],
        updated.join("\n").word_wrap
      ]
    end
  end
  
  return rows
end

#alarm_state(metric_alarms) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/cfnguardian/display_formatter.rb', line 133

def alarm_state(metric_alarms)
  rows = []
  
  metric_alarms.each do |ma|      
    if ma.state_value == 'ALARM'
      state_value = ma.state_value.to_s.red
    elsif ma.state_value == 'INSUFFICIENT_DATA'
      state_value = ma.state_value.to_s.yellow
    else
      state_value = ma.state_value.to_s.green
    end
    
    rows << [
      ma.alarm_name, 
      state_value, 
      ma.state_updated_timestamp.localtime,
      ma.actions_enabled ? 'ENABLED'.green : 'DISABLED'.red
    ]
  end
  # sort by state_value
  return rows.sort_by {|r| r[3]}
end

#alarmsObject



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
# File 'lib/cfnguardian/display_formatter.rb', line 12

def alarms()
  resp = []
  
  @alarms.each do |alarm|
    alarm_name = CfnGuardian::CloudWatch.get_alarm_name(alarm)
    use_anomaly_detection = alarm.anomaly_detection == true

    rows = [
      ['ResourceId', alarm.resource_id],
      ['ResourceHash', alarm.resource_hash],
      ['ResourceName', alarm.resource_name],
      ['Enabled', alarm.enabled],
      ['MetricName', alarm.metric_name],
      ['Dimensions', alarm.dimensions],
      # An anomaly detection alarm uses ThresholdMetricId/StandardDeviation instead of a static Threshold.
      ['Threshold', use_anomaly_detection ? nil : alarm.threshold],
      ['Period', alarm.period],
      ['EvaluationPeriods', alarm.evaluation_periods],
      ['ComparisonOperator', alarm.comparison_operator],
      ['Statistic', alarm.statistic],
      ['ActionsEnabled', alarm.actions_enabled],
      ['DatapointsToAlarm', alarm.datapoints_to_alarm],
      ['ExtendedStatistic', alarm.extended_statistic],
      ['EvaluateLowSampleCountPercentile', alarm.evaluate_low_sample_count_percentile],
      ['Unit', alarm.unit],
      ['AlarmAction', alarm.alarm_action],
      ['OkActionDisabled', alarm.ok_action_disabled],
      ['TreatMissingData', alarm.treat_missing_data],
      ['AnomalyDetection', use_anomaly_detection ? alarm.anomaly_detection : nil],
      ['StandardDeviation', use_anomaly_detection ? (alarm.standard_deviation || 2) : nil]
    ]

    rows.select! {|row| !row[1].nil?}
    
    resp << {
      title: "#{alarm.group}::#{alarm.name}".green + "\n" + alarm_name.green,
      rows: rows
    }
  end
  
  return resp
end

#compare_alarms(metric_alarms) ⇒ Object



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
# File 'lib/cfnguardian/display_formatter.rb', line 55

def compare_alarms(metric_alarms)      
  resp = []
  
  @alarms.each do |alarm|
    alarm_name = CfnGuardian::CloudWatch.get_alarm_name(alarm)
    metric_alarm = metric_alarms.find {|ma| ma.alarm_name.include? alarm_name}
    use_anomaly_detection = alarm.anomaly_detection == true
    deployed_anomaly_detection = anomaly_detection_deployed?(metric_alarm)

    # A real deployed anomaly detection alarm has no top-level MetricName/Statistic/
    # Period/Unit/Dimensions - CloudWatch only populates those nested inside the raw
    # metric's MetricStat (see #deployed_metric_stat). Fall back to the top-level fields
    # when the deployed alarm isn't a metric-math alarm at all (e.g. local config wants
    # anomaly detection but the deployed alarm is still a plain static alarm).
    metric_stat = deployed_metric_stat(metric_alarm)
    if metric_stat
      deployed_metric_name = metric_stat.metric.metric_name
      deployed_dimensions = (metric_stat.metric.dimensions || []).map {|dim| {dim.name.to_sym => dim.value}}.inject(:merge)
      deployed_period = metric_stat.period
      deployed_statistic = metric_stat.stat
      deployed_unit = metric_stat.unit
    else
      deployed_metric_name = metric_alarm.metric_name
      deployed_dimensions = (metric_alarm.dimensions || []).map {|dim| {dim.name.to_sym => dim.value}}.inject(:merge)
      deployed_period = metric_alarm.period
      deployed_statistic = metric_alarm.statistic
      deployed_unit = metric_alarm.unit
    end

    # An anomaly detection alarm's MetricStat.Stat holds whichever of Statistic/
    # ExtendedStatistic cfn-guardian generated (see stacks/resources.rb#add_alarm), so
    # compare that combined value here and suppress the separate ExtendedStatistic row
    # below - the same way Threshold is already suppressed for anomaly alarms.
    local_statistic = use_anomaly_detection ? (alarm.extended_statistic || alarm.statistic) : alarm.statistic

    rows = [
      ['ResourceId', alarm.resource_id, alarm.resource_id],
      ['ResourceHash', alarm.resource_hash, alarm.resource_hash],
      ['ResourceName', alarm.resource_name, alarm.resource_name],
      ['Enabled', alarm.enabled, true],
      ['MetricName', alarm.metric_name, deployed_metric_name],
      ['Dimensions', alarm.dimensions, deployed_dimensions],
      # A correctly deployed anomaly detection alarm has no static Threshold (it uses
      # ThresholdMetricId/Metrics instead), so comparing Threshold here would always show
      # as different. Compare AnomalyDetection/StandardDeviation below instead.
      ['Threshold', use_anomaly_detection ? nil : alarm.threshold.to_f, use_anomaly_detection ? nil : metric_alarm.threshold],
      ['Period', alarm.period, deployed_period],
      ['EvaluationPeriods', alarm.evaluation_periods, metric_alarm.evaluation_periods],
      ['ComparisonOperator', alarm.comparison_operator, metric_alarm.comparison_operator],
      ['Statistic', local_statistic, deployed_statistic],
      ['ActionsEnabled', alarm.actions_enabled, metric_alarm.actions_enabled],
      ['DatapointsToAlarm', alarm.datapoints_to_alarm, metric_alarm.datapoints_to_alarm],
      ['ExtendedStatistic', use_anomaly_detection ? nil : alarm.extended_statistic, use_anomaly_detection ? nil : metric_alarm.extended_statistic],
      ['EvaluateLowSampleCountPercentile', alarm.evaluate_low_sample_count_percentile, metric_alarm.evaluate_low_sample_count_percentile],
      ['Unit', alarm.unit, deployed_unit],
      ['TreatMissingData', alarm.treat_missing_data, metric_alarm.treat_missing_data],
      ['AlarmAction', alarm.alarm_action, alarm.alarm_action],
      ['OkActionDisabled', alarm.ok_action_disabled]
    ]

    if use_anomaly_detection || deployed_anomaly_detection
      rows << ['AnomalyDetection', use_anomaly_detection, deployed_anomaly_detection]
      rows << ['StandardDeviation', use_anomaly_detection ? (alarm.standard_deviation || 2).to_f : nil, deployed_standard_deviation(metric_alarm)]
    end

    rows.select! {|row| !row[1].nil?}.each {|row| colour_compare_row(row)}
    
    if has_config_difference?(rows)
      resp << {
        title: "#{alarm.group}::#{alarm.name}".green + "\n" + alarm_name.green,
        rows: rows
      }
    end
  end
  
  return resp
end