ruby-grafana-reporter 0.3.0 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +337 -170
  3. data/bin/ruby-grafana-reporter +5 -5
  4. data/lib/VERSION.rb +3 -2
  5. data/lib/grafana/abstract_datasource.rb +149 -0
  6. data/lib/grafana/dashboard.rb +1 -3
  7. data/lib/grafana/errors.rb +20 -5
  8. data/lib/grafana/grafana.rb +52 -57
  9. data/lib/grafana/grafana_alerts_datasource.rb +57 -0
  10. data/lib/grafana/grafana_annotations_datasource.rb +56 -0
  11. data/lib/grafana/grafana_property_datasource.rb +37 -0
  12. data/lib/grafana/graphite_datasource.rb +72 -0
  13. data/lib/grafana/image_rendering_datasource.rb +44 -0
  14. data/lib/grafana/influxdb_datasource.rb +70 -0
  15. data/lib/grafana/panel.rb +10 -4
  16. data/lib/grafana/prometheus_datasource.rb +67 -0
  17. data/lib/grafana/sql_datasource.rb +70 -0
  18. data/lib/grafana/unsupported_datasource.rb +7 -0
  19. data/lib/grafana/variable.rb +27 -21
  20. data/lib/grafana/webrequest.rb +71 -0
  21. data/lib/grafana_reporter/abstract_query.rb +478 -0
  22. data/lib/grafana_reporter/abstract_report.rb +152 -18
  23. data/lib/grafana_reporter/abstract_table_format_strategy.rb +34 -0
  24. data/lib/grafana_reporter/alerts_table_query.rb +43 -0
  25. data/lib/grafana_reporter/annotations_table_query.rb +42 -0
  26. data/lib/grafana_reporter/application/application.rb +28 -25
  27. data/lib/grafana_reporter/application/webservice.rb +80 -39
  28. data/lib/grafana_reporter/asciidoctor/adoc_plain_table_format_strategy.rb +25 -0
  29. data/lib/grafana_reporter/asciidoctor/alerts_table_include_processor.rb +92 -0
  30. data/lib/grafana_reporter/asciidoctor/annotations_table_include_processor.rb +91 -0
  31. data/lib/grafana_reporter/asciidoctor/help.rb +336 -313
  32. data/lib/grafana_reporter/asciidoctor/panel_image_block_macro.rb +78 -0
  33. data/lib/grafana_reporter/asciidoctor/panel_image_inline_macro.rb +80 -0
  34. data/lib/grafana_reporter/asciidoctor/panel_property_inline_macro.rb +74 -0
  35. data/lib/grafana_reporter/asciidoctor/panel_query_table_include_processor.rb +99 -0
  36. data/lib/grafana_reporter/asciidoctor/panel_query_value_inline_macro.rb +93 -0
  37. data/lib/grafana_reporter/asciidoctor/processor_mixin.rb +50 -0
  38. data/lib/grafana_reporter/asciidoctor/report.rb +41 -82
  39. data/lib/grafana_reporter/asciidoctor/show_environment_include_processor.rb +46 -0
  40. data/lib/grafana_reporter/asciidoctor/show_help_include_processor.rb +35 -0
  41. data/lib/grafana_reporter/asciidoctor/sql_table_include_processor.rb +94 -0
  42. data/lib/grafana_reporter/asciidoctor/sql_value_inline_macro.rb +90 -0
  43. data/lib/grafana_reporter/asciidoctor/value_as_variable_include_processor.rb +90 -0
  44. data/lib/grafana_reporter/configuration.rb +26 -8
  45. data/lib/grafana_reporter/console_configuration_wizard.rb +109 -67
  46. data/lib/grafana_reporter/csv_table_format_strategy.rb +23 -0
  47. data/lib/grafana_reporter/demo_report_wizard.rb +104 -0
  48. data/lib/grafana_reporter/erb/demo_report_builder.rb +46 -0
  49. data/lib/grafana_reporter/erb/report.rb +36 -0
  50. data/lib/grafana_reporter/erb/report_jail.rb +21 -0
  51. data/lib/grafana_reporter/errors.rb +57 -0
  52. data/lib/grafana_reporter/logger/{two_way_logger.rb → two_way_delegate_logger.rb} +1 -1
  53. data/lib/grafana_reporter/panel_image_query.rb +25 -0
  54. data/lib/grafana_reporter/panel_property_query.rb +22 -0
  55. data/lib/grafana_reporter/query_value_query.rb +61 -0
  56. data/lib/grafana_reporter/report_webhook.rb +39 -0
  57. data/lib/ruby_grafana_extension.rb +8 -0
  58. data/lib/{ruby-grafana-reporter.rb → ruby_grafana_reporter.rb} +1 -3
  59. metadata +49 -38
  60. data/lib/grafana/abstract_panel_query.rb +0 -22
  61. data/lib/grafana/abstract_query.rb +0 -132
  62. data/lib/grafana/abstract_sql_query.rb +0 -51
  63. data/lib/grafana/panel_image_query.rb +0 -52
  64. data/lib/grafana_reporter/asciidoctor/alerts_table_query.rb +0 -101
  65. data/lib/grafana_reporter/asciidoctor/annotations_table_query.rb +0 -96
  66. data/lib/grafana_reporter/asciidoctor/errors.rb +0 -40
  67. data/lib/grafana_reporter/asciidoctor/extensions/alerts_table_include_processor.rb +0 -92
  68. data/lib/grafana_reporter/asciidoctor/extensions/annotations_table_include_processor.rb +0 -91
  69. data/lib/grafana_reporter/asciidoctor/extensions/panel_image_block_macro.rb +0 -69
  70. data/lib/grafana_reporter/asciidoctor/extensions/panel_image_inline_macro.rb +0 -68
  71. data/lib/grafana_reporter/asciidoctor/extensions/panel_property_inline_macro.rb +0 -61
  72. data/lib/grafana_reporter/asciidoctor/extensions/panel_query_table_include_processor.rb +0 -78
  73. data/lib/grafana_reporter/asciidoctor/extensions/panel_query_value_inline_macro.rb +0 -73
  74. data/lib/grafana_reporter/asciidoctor/extensions/processor_mixin.rb +0 -20
  75. data/lib/grafana_reporter/asciidoctor/extensions/show_environment_include_processor.rb +0 -43
  76. data/lib/grafana_reporter/asciidoctor/extensions/show_help_include_processor.rb +0 -30
  77. data/lib/grafana_reporter/asciidoctor/extensions/sql_table_include_processor.rb +0 -70
  78. data/lib/grafana_reporter/asciidoctor/extensions/sql_value_inline_macro.rb +0 -66
  79. data/lib/grafana_reporter/asciidoctor/extensions/value_as_variable_include_processor.rb +0 -88
  80. data/lib/grafana_reporter/asciidoctor/panel_first_value_query.rb +0 -36
  81. data/lib/grafana_reporter/asciidoctor/panel_image_query.rb +0 -28
  82. data/lib/grafana_reporter/asciidoctor/panel_property_query.rb +0 -44
  83. data/lib/grafana_reporter/asciidoctor/panel_table_query.rb +0 -40
  84. data/lib/grafana_reporter/asciidoctor/query_mixin.rb +0 -312
  85. data/lib/grafana_reporter/asciidoctor/sql_first_value_query.rb +0 -42
  86. data/lib/grafana_reporter/asciidoctor/sql_table_query.rb +0 -44
@@ -1,88 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative 'processor_mixin'
4
-
5
- module GrafanaReporter
6
- module Asciidoctor
7
- module Extensions
8
- # Implements the hook
9
- # include::grafana_value_as_variable[<options>]
10
- #
11
- # Returns an attribute definition in asciidoctor format. This is needed if you want to refer to values of
12
- # a grafana query within a variable in asciidoctor. As this works without this function for the
13
- # `IncludeProcessor`s values, it will not work for all the other processors.
14
- #
15
- # This method is just a proxy for all other hooks and will forward parameters accordingly.
16
- #
17
- # Example:
18
- #
19
- # include:grafana_value_as_variable[call="grafana_sql_value:1",variable_name="my_variable",sql="SELECT 'looks good'",<any_other_option>]
20
- #
21
- # This will call the {SqlValueInlineMacro} with `datasource_id` set to `1` and store the result in the
22
- # variable. The resulting asciidoctor variable definition will be created as:
23
- #
24
- # :my_variable: looks good
25
- #
26
- # and can be refered to in your document easily as
27
- #
28
- # {my_variable}
29
- #
30
- # == Supported options
31
- # +call+ - regular call to the reporter hook (*mandatory*)
32
- #
33
- # +variable_name+ - name of the variable, to which the result shall be assigned (*mandatory*)
34
- class ValueAsVariableIncludeProcessor < ::Asciidoctor::Extensions::IncludeProcessor
35
- include ProcessorMixin
36
-
37
- # :nodoc:
38
- def handles?(target)
39
- target.start_with? 'grafana_value_as_variable'
40
- end
41
-
42
- # :nodoc:
43
- def process(doc, reader, target, attrs)
44
- return if @report.cancel
45
-
46
- # do NOT increase step, as this is done by sub processor
47
- # @report.next_step
48
-
49
- call_attr = attrs.delete('call')
50
- call, target = call_attr.split(':') if call_attr
51
- attribute = attrs.delete('variable_name')
52
- @report.logger.debug("Processing ValueAsVariableIncludeProcessor (call: #{call}, target: #{target},"\
53
- " variable_name: #{attribute}, attrs: #{attrs})")
54
- if !call || !attribute
55
- @report.logger.error('ValueAsVariableIncludeProcessor: Missing mandatory attribute \'call\' or '\
56
- '\'variable_name\'.')
57
- return reader
58
- end
59
-
60
- # TODO: remove dirty hack to allow the document as parameter for other processors
61
- def doc.document
62
- self
63
- end
64
-
65
- # TODO: properly show error messages also in document
66
- ext = doc.extensions.find_inline_macro_extension(call) if doc.extensions.inline_macros?
67
- if !ext
68
- @report.logger.error('ValueAsVariableIncludeProcessor: Could not find inline macro extension for '\
69
- "'#{call}'.")
70
- else
71
- @report.logger.debug('ValueAsVariableIncludeProcessor: Calling sub-method.')
72
- item = ext.process_method.call(doc, target, attrs)
73
- if !item.text.to_s.empty?
74
- result = ":#{attribute}: #{item.text}"
75
- @report.logger.debug("ValueAsVariableIncludeProcessor: Adding '#{result}' to document.")
76
- reader.unshift_line(result)
77
- else
78
- @report.logger.debug("ValueAsVariableIncludeProcessor: Not adding variable '#{attribute}'"\
79
- ' as query result was empty.')
80
- end
81
- end
82
-
83
- reader
84
- end
85
- end
86
- end
87
- end
88
- end
@@ -1,36 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative 'sql_first_value_query'
4
-
5
- module GrafanaReporter
6
- module Asciidoctor
7
- # (see SqlFirstValueQuery)
8
- #
9
- # The SQL query as well as the datasource configuration are thereby captured from a
10
- # {Grafana::Panel}.
11
- class PanelFirstValueQuery < SqlFirstValueQuery
12
- include QueryMixin
13
-
14
- # (see PanelTableQuery#initialize)
15
- def initialize(panel, query_letter)
16
- super(nil, nil)
17
- @panel = panel
18
- @query_letter = query_letter
19
- extract_dashboard_variables(@panel.dashboard)
20
- end
21
-
22
- # (see PanelTableQuery#pre_process)
23
- def pre_process(grafana)
24
- @sql = @panel.query(@query_letter)
25
- # resolve datasource name
26
- @datasource = @panel.field('datasource')
27
- @datasource_id = grafana.datasource_id(@datasource)
28
- super(grafana)
29
- @from = translate_date(@from, @variables['grafana-report-timestamp'], false, @variables['from_timezone'] ||
30
- @variables['grafana_default_from_timezone'])
31
- @to = translate_date(@to, @variables['grafana-report-timestamp'], true, @variables['to_timezone'] ||
32
- @variables['grafana_default_to_timezone'])
33
- end
34
- end
35
- end
36
- end
@@ -1,28 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module GrafanaReporter
4
- module Asciidoctor
5
- # This class is used to create an image out of a {Grafana::Panel}.
6
- class PanelImageQuery < Grafana::PanelImageQuery
7
- include QueryMixin
8
-
9
- # Sets the proper render variables.
10
- def pre_process(grafana)
11
- super
12
- @from = translate_date(@from, @variables['grafana-report-timestamp'], false, @variables['from_timezone'] ||
13
- @variables['grafana_default_from_timezone'])
14
- @to = translate_date(@to, @variables['grafana-report-timestamp'], true, @variables['to_timezone'] ||
15
- @variables['grafana_default_to_timezone'])
16
- # TODO: ensure that in case of timezones are specified, that they are also forwarded to the image renderer
17
- # rename "render-" variables
18
- @variables = @variables.each_with_object({}) { |(k, v), h| h[k.gsub(/^render-/, '')] = v }
19
- end
20
-
21
- # Returns the body of the http query, which contains the raw image.
22
- def post_process
23
- super
24
- @result = @result.body
25
- end
26
- end
27
- end
28
- end
@@ -1,44 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module GrafanaReporter
4
- module Asciidoctor
5
- # This class is used to query properties from a {Grafana::Panel}, such as +description+,
6
- # +title+ etc.
7
- class PanelPropertyQuery < ::Grafana::AbstractPanelQuery
8
- include QueryMixin
9
-
10
- # @param panel [Grafana::Panel] panel object, for which the property shall be retrieved
11
- # @param property [String] queried property, e.g. +title+
12
- def initialize(panel, property)
13
- super(panel)
14
- @property = property
15
- end
16
-
17
- # Overrides the default method, as the query does not have to run against a SQL table,
18
- # but rather against the panel model.
19
- # @param grafana [Grafana::Grafana] grafana instance against which the panel property is queried
20
- # @return [String] fetched property
21
- def execute(grafana)
22
- return @result unless @result.nil?
23
-
24
- pre_process(grafana)
25
- @result = panel.field(@property)
26
- post_process
27
- @result
28
-
29
- # TODO: handle text (markdown and similar) properly
30
- end
31
-
32
- # Prepare query. Mainly here nothing special has to take place.
33
- def pre_process(_grafana)
34
- @from = nil
35
- @to = nil
36
- end
37
-
38
- # Replaces variables in the property field, if any are available.
39
- def post_process
40
- @result = replace_variables(@result, grafana_variables)
41
- end
42
- end
43
- end
44
- end
@@ -1,40 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative 'sql_table_query'
4
-
5
- module GrafanaReporter
6
- module Asciidoctor
7
- # (see SqlTableQuery)
8
- #
9
- # The SQL query as well as the datasource configuration are thereby captured from a
10
- # {Grafana::Panel}.
11
- class PanelTableQuery < SqlTableQuery
12
- include QueryMixin
13
-
14
- # @param panel [Grafana::Panel] panel which contains the query
15
- # @param query_letter [String] letter of the query within the panel, which shall be used, e.g. +C+
16
- def initialize(panel, query_letter)
17
- super(nil, nil)
18
- @panel = panel
19
- @query_letter = query_letter
20
- extract_dashboard_variables(@panel.dashboard)
21
- end
22
-
23
- # Retrieves the SQL query and the configured datasource from the panel.
24
- # @see Grafana::AbstractSqlQuery#pre_process
25
- # @param grafana [Grafana::Grafana] grafana instance against which the query shall be executed
26
- # @return [void]
27
- def pre_process(grafana)
28
- @sql = @panel.query(@query_letter)
29
- # resolve datasource name
30
- @datasource = @panel.field('datasource')
31
- @datasource_id = grafana.datasource_id(@datasource)
32
- super(grafana)
33
- @from = translate_date(@from, @variables['grafana-report-timestamp'], false, @variables['from_timezone'] ||
34
- @variables['grafana_default_from_timezone'])
35
- @to = translate_date(@to, @variables['grafana-report-timestamp'], true, @variables['to_timezone'] ||
36
- @variables['grafana_default_to_timezone'])
37
- end
38
- end
39
- end
40
- end
@@ -1,312 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module GrafanaReporter
4
- module Asciidoctor
5
- # This mixin contains several common methods, which can be used within the queries.
6
- module QueryMixin
7
- # Merges the given hashes to the current object by using the {Grafana::AbstractQuery#merge_variables} method.
8
- # It respects the priorities of the hashes and the object and allows only valid variables to be passed.
9
- # @param document_hash [Hash] variables from report template level
10
- # @param item_hash [Hash] variables from item configuration level, i.e. specific call, which may override document
11
- # @return [void]
12
- def merge_hash_variables(document_hash, item_hash)
13
- sel_doc_items = document_hash.select do |k, _v|
14
- k =~ /^var-/ || k == 'grafana-report-timestamp' || k =~ /grafana_default_(?:from|to)_timezone/
15
- end
16
- merge_variables(sel_doc_items.each_with_object({}) { |(k, v), h| h[k] = ::Grafana::Variable.new(v) })
17
-
18
- sel_items = item_hash.select do |k, _v|
19
- k =~ /^var-/ || k =~ /^render-/ || k =~ /filter_columns|format|replace_values_.*|transpose|column_divider|
20
- row_divider|from_timezone|to_timezone/x
21
- end
22
- merge_variables(sel_items.each_with_object({}) { |(k, v), h| h[k] = ::Grafana::Variable.new(v) })
23
-
24
- self.timeout = item_hash['timeout'] || document_hash['grafana-default-timeout'] || timeout
25
- self.from = item_hash['from'] || document_hash['from'] || from
26
- self.to = item_hash['to'] || document_hash['to'] || to
27
- end
28
-
29
- # Formats the SQL results returned from grafana to an easier to use format.
30
- #
31
- # The result is being formatted as stated below:
32
- #
33
- # {
34
- # :header => [column_title_1, column_title_2],
35
- # :content => [
36
- # [row_1_column_1, row_1_column_2],
37
- # [row_2_column_1, row_2_column_2]
38
- # ]
39
- # }
40
- # @param raw_result [Hash] query result hash from grafana
41
- # @return [Hash] sql result formatted as stated above
42
- def preformat_sql_result(raw_result)
43
- results = {}
44
- results.default = []
45
-
46
- JSON.parse(raw_result)['results'].each_value do |query_result|
47
- if query_result.key?('error')
48
- results[:header] = results[:header] << ['SQL Error']
49
- results[:content] = [[query_result['error']]]
50
-
51
- elsif query_result['tables']
52
- query_result['tables'].each do |table|
53
- results[:header] = results[:header] << table['columns'].map { |header| header['text'] }
54
- results[:content] = table['rows']
55
- end
56
-
57
- end
58
- end
59
-
60
- results
61
- end
62
-
63
- # Transposes the given result.
64
- #
65
- # NOTE: Only the +:content+ of the given result hash is transposed. The +:header+ is ignored.
66
- #
67
- # @param result [Hash] preformatted sql hash, (see {#preformat_sql_result})
68
- # @param transpose_variable [Grafana::Variable] true, if the result hash shall be transposed
69
- # @return [Hash] transposed query result
70
- def transpose(result, transpose_variable)
71
- return result unless transpose_variable
72
- return result unless transpose_variable.raw_value == 'true'
73
-
74
- result[:content] = result[:content].transpose
75
-
76
- result
77
- end
78
-
79
- # Filters columns out of the query result.
80
- #
81
- # Multiple columns may be filtered. Therefore the column titles have to be named in the
82
- # {Grafana::Variable#raw_value} and have to be separated by +,+ (comma).
83
- # @param result [Hash] preformatted sql hash, (see {#preformat_sql_result})
84
- # @param filter_columns_variable [Grafana::Variable] column names, which shall be removed in the query result
85
- # @return [Hash] filtered query result
86
- def filter_columns(result, filter_columns_variable)
87
- return result unless filter_columns_variable
88
-
89
- filter_columns = filter_columns_variable.raw_value
90
- filter_columns.split(',').each do |filter_column|
91
- pos = result[:header][0].index(filter_column)
92
-
93
- unless pos.nil?
94
- result[:header][0].delete_at(pos)
95
- result[:content].each { |row| row.delete_at(pos) }
96
- end
97
- end
98
-
99
- result
100
- end
101
-
102
- # Uses the {Kernel#format} method to format values in the query results.
103
- #
104
- # The formatting will be applied separately for every column. Therefore the column formats have to be named
105
- # in the {Grafana::Variable#raw_value} and have to be separated by +,+ (comma). If no value is specified for
106
- # a column, no change will happen.
107
- # @param result [Hash] preformatted sql hash, (see {#preformat_sql_result})
108
- # @param formats [Grafana::Variable] formats, which shall be applied to the columns in the query result
109
- # @return [Hash] formatted query result
110
- # TODO: make sure that caught errors are also visible in logger
111
- def format_columns(result, formats)
112
- return result unless formats
113
-
114
- formats.text.split(',').each_index do |i|
115
- format = formats.text.split(',')[i]
116
- next if format.empty?
117
-
118
- result[:content].map do |row|
119
- next unless row.length > i
120
-
121
- begin
122
- row[i] = format % row[i] if row[i]
123
- rescue StandardError => e
124
- row[i] = e.message
125
- end
126
- end
127
- end
128
- result
129
- end
130
-
131
- # Used to replace values in a query result according given configurations.
132
- #
133
- # The given variables will be applied to an appropriate column, depending
134
- # on the naming of the variable. The variable name ending specifies the column,
135
- # e.g. a variable named +replace_values_2+ will be applied to the second column.
136
- #
137
- # The {Grafana::Variable#text} needs to contain the replace specification.
138
- # Multiple replacements can be specified by separating them with +,+. If a
139
- # literal comma is needed, it can be escaped with a backslash: +\\,+.
140
- #
141
- # The rule will be separated from the replacement text with a colon +:+.
142
- # If a literal colon is wanted, it can be escaped with a backslash: +\\:+.
143
- #
144
- # Examples:
145
- # - Basic string replacement
146
- # MyTest:ThisValue
147
- # will replace all occurences of the text 'MyTest' with 'ThisValue'.
148
- # - Number comparison
149
- # <=10:OK
150
- # will replace all values smaller or equal to 10 with 'OK'.
151
- # - Regular expression
152
- # ^[^ ]\\+ (\d+)$:\1 is the answer
153
- # will replace all values matching the pattern, e.g. 'answerToAllQuestions 42' to
154
- # '42 is the answer'. Important to know: the regular expressions always have to start
155
- # with +^+ and end with +$+, i.e. the expression itself always has to match
156
- # the whole content in one field.
157
- # @param result [Hash] preformatted query result (see {#preformat_sql_result}.
158
- # @param configs [Array<Grafana::Variable>] one variable for replacing values in one column
159
- # @return [Hash] query result with replaced values
160
- # TODO: make sure that caught errors are also visible in logger
161
- def replace_values(result, configs)
162
- return result if configs.empty?
163
-
164
- configs.each do |key, formats|
165
- cols = key.split('_')[2..-1].map(&:to_i)
166
-
167
- formats.text.split(/(?<!\\),/).each_index do |j|
168
- format = formats.text.split(/(?<!\\),/)[j]
169
-
170
- arr = format.split(/(?<!\\):/)
171
- raise MalformedReplaceValuesStatementError, format if arr.length != 2
172
-
173
- k = arr[0]
174
- v = arr[1]
175
- k.gsub!(/\\([:,])/, '\1')
176
- v.gsub!(/\\([:,])/, '\1')
177
- result[:content].map do |row|
178
- (row.length - 1).downto 0 do |i|
179
- if cols.include?(i + 1) || cols.empty?
180
-
181
- # handle regular expressions
182
- if k.start_with?('^') && k.end_with?('$')
183
- begin
184
- row[i] = row[i].to_s.gsub(/#{k}/, v) if row[i].to_s =~ /#{k}/
185
- rescue StandardError => e
186
- row[i] = e.message
187
- end
188
-
189
- # handle value comparisons
190
- elsif (match = k.match(/^ *(?<operator>[<>]=?|<>|=) *(?<number>[+-]?\d+(?:\.\d+)?)$/))
191
- skip = false
192
- begin
193
- val = Float(row[i])
194
- rescue StandardError
195
- # value cannot be converted to number, simply ignore it as the comparison does not fit here
196
- skip = true
197
- end
198
-
199
- unless skip
200
- begin
201
- op = match[:operator].gsub(/^=$/, '==').gsub(/^<>$/, '!=')
202
- if val.public_send(op.to_sym, Float(match[:number]))
203
- row[i] = if v.include?('\\1')
204
- v.gsub(/\\1/, row[i].to_s)
205
- else
206
- v
207
- end
208
- end
209
- rescue StandardError => e
210
- row[i] = e.message
211
- end
212
- end
213
-
214
- # handle as normal comparison
215
- elsif row[i].to_s == k
216
- row[i] = v
217
- end
218
- end
219
- end
220
- end
221
- end
222
- end
223
-
224
- result
225
- end
226
-
227
- # Used to translate the relative date strings used by grafana, e.g. +now-5d/w+ to the
228
- # correct timestamp. Reason is that grafana does this in the frontend, which we have
229
- # to emulate here for the reporter.
230
- #
231
- # Additionally providing this function the +report_time+ assures that all queries
232
- # rendered within one report will use _exactly_ the same timestamp in those relative
233
- # times, i.e. there shouldn't appear any time differences, no matter how long the
234
- # report is running.
235
- # @param orig_date [String] time string provided by grafana, usually +from+ or +to+.
236
- # @param report_time [Grafana::Variable] report start time
237
- # @param is_to_time [Boolean] true, if the time should be calculated for +to+, false if it shall be
238
- # calculated for +from+
239
- # @param timezone [Grafana::Variable] timezone to use, if not system timezone
240
- # @return [String] translated date as timestamp string
241
- def translate_date(orig_date, report_time, is_to_time, timezone = nil)
242
- report_time ||= Variable.new(Time.now.to_s)
243
- return (DateTime.parse(report_time.raw_value).to_time.to_i * 1000).to_s unless orig_date
244
- return orig_date if orig_date =~ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
245
- return orig_date if orig_date =~ /^\d+$/
246
-
247
- # replace grafana from and to values using now, now-2d etc.
248
- date_splitted = orig_date.match(%r{^(?<now>now)(?:-(?<sub_count>\d+)?(?<sub_unit>[smhdwMy]?))?(?:/(?<fit>[smhdwMy]))?$})
249
- raise TimeRangeUnknownError, orig_date unless date_splitted
250
-
251
- date = DateTime.parse(report_time.raw_value)
252
- # TODO: allow from_translated or similar in ADOC template
253
- date = date.new_offset(timezone.raw_value) if timezone
254
-
255
- # substract specified time
256
- count = 1
257
- count = date_splitted[:sub_count].to_i if date_splitted[:sub_count]
258
- case date_splitted[:sub_unit]
259
- when 's'
260
- date = (date.to_time - (count * 1)).to_datetime
261
- when 'm'
262
- date = (date.to_time - (count * 60)).to_datetime
263
- when 'h'
264
- date = (date.to_time - (count * 60 * 60)).to_datetime
265
- when 'd'
266
- date = date.prev_day(count)
267
- when 'w'
268
- date = date.prev_day(count * 7)
269
- when 'M'
270
- date = date.prev_month(count)
271
- when 'y'
272
- date = date.prev_year(count)
273
- end
274
-
275
- # fit to specified time frame
276
- case date_splitted[:fit]
277
- when 's'
278
- date = DateTime.new(date.year, date.month, date.day, date.hour, date.min, date.sec, date.zone)
279
- date = (date.to_time + 1).to_datetime if is_to_time
280
- when 'm'
281
- date = DateTime.new(date.year, date.month, date.day, date.hour, date.min, 0, date.zone)
282
- date = (date.to_time + 60).to_datetime if is_to_time
283
- when 'h'
284
- date = DateTime.new(date.year, date.month, date.day, date.hour, 0, 0, date.zone)
285
- date = (date.to_time + 60 * 60).to_datetime if is_to_time
286
- when 'd'
287
- date = DateTime.new(date.year, date.month, date.day, 0, 0, 0, date.zone)
288
- date = date.next_day(1) if is_to_time
289
- when 'w'
290
- date = DateTime.new(date.year, date.month, date.day, 0, 0, 0, date.zone)
291
- date = if date.wday.zero?
292
- date.prev_day(7)
293
- else
294
- date.prev_day(date.wday - 1)
295
- end
296
- date = date.next_day(7) if is_to_time
297
- when 'M'
298
- date = DateTime.new(date.year, date.month, 1, 0, 0, 0, date.zone)
299
- date = date.next_month if is_to_time
300
- when 'y'
301
- date = DateTime.new(date.year, 1, 1, 0, 0, 0, date.zone)
302
- date = date.next_year if is_to_time
303
- end
304
-
305
- # step back one second, if this is the 'to' time
306
- date = (date.to_time - 1).to_datetime if is_to_time
307
-
308
- (Time.at(date.to_time.to_i).to_i * 1000).to_s
309
- end
310
- end
311
- end
312
- end