Class: Utils::Analytics::Influx Private

Inherits:
Object
  • Object
show all
Includes:
Output::Mixin
Defined in:
utils/analytics/influx.rb

Overview

This class is part of a private API. This class may only be used in the Homebrew/brew repository. Third parties should avoid using this class if possible, as it may be removed or changed without warning.

Query and format the analytics stored in InfluxDB.

Constant Summary collapse

FIRST_INFLUXDB_ANALYTICS_DATE =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

Date.new(2023, 03, 27).freeze
STANDARD_PREFIXES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%w[/opt/homebrew /usr/local /home/linuxbrew/.linuxbrew].freeze

Instance Method Summary collapse

Methods included from Output::Mixin

#issue_reporting_message, #odebug, #odeprecated, #odie, #odisabled, #ofail, #oh1, #oh1_title, #ohai, #ohai_title, #onoe, #opoo, #opoo_once, #opoo_outside_github_actions, #opoo_without_github_actions_annotation, #pretty_cannot_install, #pretty_deprecated, #pretty_disabled, #pretty_duration, #pretty_install_status, #pretty_installed, #pretty_uninstalled, #pretty_unmarked, #pretty_upgradable, #pretty_warning

Instance Method Details

#each_influx_record(query, &_block) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • query (String)
  • _block (T.proc.params(record: T::Hash[String, T.untyped]).void)


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
# File 'utils/analytics/influx.rb', line 53

def each_influx_record(query, &_block)
  require "json"
  require "tempfile"
  require "utils/analytics"
  require "utils/popen"

  request = {
    host:     URI.parse(Utils::Analytics::INFLUX_HOST).host,
    org:      Utils::Analytics::INFLUX_ORG,
    database: Utils::Analytics::INFLUX_BUCKET,
    query:,
  }.to_json

  Tempfile.create("influxdb-query-stderr") do |stderr_file|
    Utils.popen([venv_python.to_s, influxdb_query_script.to_s], "r+b", { err: stderr_file.path }) do |pipe|
      pipe.write request
      pipe.close_write
      pipe.each_line { |line| yield JSON.parse(line) }
    end

    next if $CHILD_STATUS.success?

    stderr = stderr_file.read
    if stderr.include?("unauthenticated")
      odie "Could not authenticate with InfluxDB! Please check your `$HOMEBREW_INFLUXDB_TOKEN`!"
    end
    odie "InfluxDB query failed:\n#{stderr}"
  end
end

#format_os_version_dimension(dimension) ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



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
# File 'utils/analytics/influx.rb', line 339

def format_os_version_dimension(dimension)
  return if dimension.blank?

  require "macos_version"
  require "utils/analytics"

  wsl = dimension.end_with?(Utils::Analytics::WSL_SUFFIX)
  dimension = dimension.delete_suffix(Utils::Analytics::WSL_SUFFIX)
  dimension = dimension.gsub(/^Intel ?/, "")
                       .gsub(/^macOS ?/, "")
                       .gsub(/ \(.+\)$/, "")

  begin
    macos_version = ::MacOSVersion.new(dimension)
    release_version = macos_version.release_version
    os_name = (macos_version < "10.12") ? "OS X" : "macOS"
    if (release_name = macos_version.release_name)
      return "#{os_name} #{release_name} (#{release_version})"
    end

    return "#{os_name} #{release_version}"
  rescue MacOSVersion::Error
    nil
  end

  formatted_dimension = case dimension
  when /Ubuntu(-Server)? (14|16|18|20|22|24)\.04/ then "Ubuntu #{Regexp.last_match(2)}.04 LTS"
  when /Ubuntu(-Server)? (\d+\.\d+).\d ?(LTS)?/
    "Ubuntu #{Regexp.last_match(2)} #{Regexp.last_match(3)}".strip
  when %r{Debian GNU/Linux (\d+)} then "Debian #{Regexp.last_match(1)}"
  when /CentOS (\w+) (\d+)/ then "CentOS #{Regexp.last_match(1)} #{Regexp.last_match(2)}"
  when /Fedora Linux (\d+)[.\d]*/ then "Fedora Linux #{Regexp.last_match(1)}"
  when /KDE neon .*?([\d.]+)/ then "KDE neon #{Regexp.last_match(1)}"
  when /Amazon Linux (\d+)\.[.\d]*/ then "Amazon Linux #{Regexp.last_match(1)}"
  when /^Armbian\S*(?: OS)? (\d+)\.0?(\d+)\S*(?: (\w+))?/
    "Armbian #{Regexp.last_match(1)}.#{Regexp.last_match(2)} #{Regexp.last_match(3)&.downcase}".strip
  when /Fedora Linux Rawhide[.\dn]*/ then "Fedora Linux Rawhide"
  when /Red Hat Enterprise Linux CoreOS (\d+\.\d+)[-.\d]*/
    "Red Hat Enterprise Linux CoreOS #{Regexp.last_match(1)}"
  when /([A-Za-z ]+)\s+(\d+)\.\d{8}[.\d]*/ then "#{Regexp.last_match(1)} #{Regexp.last_match(2)}"
  else dimension
  end

  Utils::Analytics.with_wsl_suffix_if_needed(formatted_dimension, wsl:)
end

#formula_analytics_root ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



32
33
34
# File 'utils/analytics/influx.rb', line 32

def formula_analytics_root
  HOMEBREW_LIBRARY/"Homebrew/formula-analytics"
end

#influxdb_query_script ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



37
38
39
# File 'utils/analytics/influx.rb', line 37

def influxdb_query_script
  formula_analytics_root/"influxdb-query.py"
end

#query(categories:, days_ago: 30, all_core_formulae_json: false) ⇒ Array<Hash{Symbol => T.untyped}>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • categories (Array<Symbol>)
  • days_ago (Integer) (defaults to: 30)
  • all_core_formulae_json (Boolean) (defaults to: false)

Returns:



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
# File 'utils/analytics/influx.rb', line 87

def query(categories:, days_ago: 30, all_core_formulae_json: false)
  require "utils/analytics"
  require "json"

  odie "`$HOMEBREW_NO_ANALYTICS` is set!" if ENV["HOMEBREW_NO_ANALYTICS"]

  odie "No InfluxDB credentials found in `$HOMEBREW_INFLUXDB_TOKEN`!" unless ENV["HOMEBREW_INFLUXDB_TOKEN"]

  max_days_ago = (Date.today - FIRST_INFLUXDB_ANALYTICS_DATE).to_s.to_i
  if days_ago > max_days_ago
    opoo "Analytics started #{FIRST_INFLUXDB_ANALYTICS_DATE}. `--days-ago` set to maximum value."
    days_ago = max_days_ago
  end
  if days_ago > 365
    opoo "Analytics are only retained for 1 year, setting `--days-ago=365`."
    days_ago = 365
  end

  category_matching_buckets = [:build_error, :cask_install, :command_run, :test_bot_test]

  categories.map do |category|
    additional_where = all_core_formulae_json ? " AND tap_name ~ '^homebrew/(core|cask)$'" : ""
    bucket = if category_matching_buckets.include?(category)
      category
    elsif [:command_run_options, :homebrew_env_config].include?(category)
      :command_run
    else
      :formula_install
    end

    case category
    when :homebrew_devcmdrun_developer
      dimension_key = "devcmdrun_developer"
      groups = [:devcmdrun, :developer]
    when :homebrew_env_config
      dimension_key = "env_config"
      groups = [:env_config, :env_config_state]
      # Events predating the user-set-aware `env_config_state` tag
      # counted brew's own exports as configuration, so drop them.
      additional_where += " AND env_config_state IS NOT NULL"
    when :homebrew_os_arch_ci
      dimension_key = "os_arch_ci"
      groups = [:os, :arch, :ci]
    when :homebrew_prefixes
      dimension_key = "prefix"
      groups = [:prefix, :os, :arch]
    when :homebrew_versions
      dimension_key = "version"
      groups = [:version]
    when :os_versions
      dimension_key = :os_version
      groups = [:os_name_and_version]
    when :command_run
      dimension_key = "command_run"
      groups = [:command]
    when :command_run_options
      dimension_key = "command_run_options"
      groups = [:command, :options, :devcmdrun, :developer]
    when :test_bot_test
      dimension_key = "test_bot_test"
      groups = [:command, :passed, :arch, :os]
    when :cask_install
      dimension_key = :cask
      groups = [:package, :tap_name]
    else
      dimension_key = :formula
      additional_where += " AND on_request = 'true'" if category == :formula_install_on_request
      groups = [:package, :tap_name, :options]
    end

    sql_groups = groups.map { |e| "\"#{e}\"" }.join(",")
    query = <<~EOS
      SELECT #{sql_groups}, COUNT(*) AS "count" FROM "#{bucket}" WHERE time >= now() - INTERVAL '#{days_ago} day'#{additional_where} GROUP BY #{sql_groups}
    EOS

    json = T.let({
      category:,
      total_items: 0,
      start_date:  Date.today - days_ago.to_i,
      end_date:    Date.today,
      total_count: 0,
      items:       [],
    }, T::Hash[Symbol, T.untyped])

    each_influx_record(query) do |record|
      if category == :homebrew_env_config
        state = record["env_config_state"]
        env_config_name = record["env_config"].to_s
        # Drop malformed events from non-standard clients and events
        # for variables Homebrew no longer supports.
        next if %w[unset default non_default].exclude?(state)
        next unless Homebrew::EnvConfig::ENVS.key?(env_config_name.to_sym)

        count = record["count"]
        json[:total_count] += count
        json[:items] << {
          number: nil,
          dimension_key => env_config_name,
          count:,
          non_default_count: (state == "non_default") ? count : 0,
          set_default_count: (state == "default") ? count : 0,
          unset_count:       (state == "unset") ? count : 0,
        }
        next
      end

      dimension = case category
      when :homebrew_devcmdrun_developer
        "devcmdrun=#{record["devcmdrun"]} HOMEBREW_DEVELOPER=#{record["developer"]}"
      when :homebrew_os_arch_ci
        if record["ci"] == "true"
          "#{record["os"]} #{record["arch"]} (CI)"
        else
          "#{record["os"]} #{record["arch"]}"
        end
      when :homebrew_prefixes
        prefix = record["prefix"].to_s
        if STANDARD_PREFIXES.none? { |std| std.casecmp?(prefix) }
          "custom-prefix (#{record["os"]} #{record["arch"]})"
        else
          prefix
        end
      when :os_versions
        format_os_version_dimension(record["os_name_and_version"])
      when :command_run_options
        "#{record["command"]} #{record["options"].to_s.split.sort.join(" ")}"
      when :test_bot_test
        command_and_package, options = record["command"].split.partition { |arg| !arg.start_with?("-") }

        # Cleanup bad data before https://github.com/Homebrew/homebrew-test-bot/pull/1043
        # Can delete this code after 27th April 2025.
        next if %w[audit install linkage style test].exclude?(command_and_package.first)
        next if command_and_package.last.include?("/")
        next if options.include?("--tap=")
        next if options.include?("--only-dependencies")
        next if options.include?("--cached")

        command_and_options = (command_and_package + options.sort).join(" ")
        passed = (record["passed"] == "true") ? "PASSED" : "FAILED"

        "#{command_and_options} (#{record["os"]} #{record["arch"]}) (#{passed})"
      else
        record[groups.first.to_s]
      end
      next if dimension.blank?

      if (tap_name = record["tap_name"].presence) &&
         ((tap_name != "homebrew/cask" && dimension_key == :cask) ||
          (tap_name != "homebrew/core" && dimension_key == :formula))
        dimension = "#{tap_name}/#{dimension}"
      end

      if (all_core_formulae_json || category == :build_error) &&
         (options = record["options"].presence)
        # homebrew/core formulae don't have non-HEAD options but they ended up in our analytics anyway.
        if all_core_formulae_json
          options = options.split.include?("--HEAD") ? "--HEAD" : ""
        end
        dimension = "#{dimension} #{options}"
      end

      dimension = dimension.strip
      next if dimension.match?(/[<>]/)

      count = record["count"]

      json[:total_items] += 1
      json[:total_count] += count

      json[:items] << {
        number: nil,
        dimension_key => dimension,
        count:,
      }
    end

    odie "No data returned" if json[:total_count].zero?

    # Combine identical values
    deduped_items = {}

    json[:items].each do |item|
      key = item[dimension_key]
      if deduped_items.key?(key)
        deduped_items[key][:count] += item[:count]
        if category == :homebrew_env_config
          deduped_items[key][:non_default_count] += item[:non_default_count]
          deduped_items[key][:set_default_count] += item[:set_default_count]
          deduped_items[key][:unset_count] += item[:unset_count]
        end
      else
        deduped_items[key] = item
      end
    end

    json[:items] = deduped_items.values
    json[:total_items] = json[:items].length if category == :homebrew_env_config

    if all_core_formulae_json
      core_formula_items = {}

      json[:items].each do |item|
        item.delete(:number)
        formula_name, = item[dimension_key].split.first
        next if formula_name.include?("/")

        core_formula_items[formula_name] ||= []
        core_formula_items[formula_name] << item
      end
      json.delete(:items)

      core_formula_items.each_value do |items|
        items.sort_by! { |item| -item[:count] }
        items.each do |item|
          item[:count] = Utils::Analytics.format_count(item[:count])
        end
      end

      json[:formulae] = core_formula_items.sort_by { |name, _| name }.to_h
    else
      json[:items].sort_by! do |item|
        if category == :homebrew_env_config
          -item[:non_default_count].to_f / item[:count]
        else
          -item[:count]
        end
      end

      json[:items].each_with_index do |item, index|
        item[:number] = index + 1

        percent = if category == :homebrew_env_config
          (item[:non_default_count].to_f / item[:count]) * 100
        else
          (item[:count].to_f / json[:total_count]) * 100
        end
        item[:percent] = Utils::Analytics.format_percent(percent).delete_suffix(".00")
        item[:count] = Utils::Analytics.format_count(item[:count])
        next if category != :homebrew_env_config

        item[:non_default_count] = Utils::Analytics.format_count(item[:non_default_count])
        item[:set_default_count] = Utils::Analytics.format_count(item[:set_default_count])
        item[:unset_count] = Utils::Analytics.format_count(item[:unset_count])
        item[:default_value] = Homebrew::EnvConfig.default_description(item[dimension_key].to_sym)
      end
    end

    json
  end
end

#setup_python ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'utils/analytics/influx.rb', line 16

def setup_python
  uv = which("uv", ORIGINAL_PATHS)
  odie <<~EOS if uv.nil?
    `uv` is required. Try:
      brew install uv
  EOS

  vendor_python = venv_root.dirname
  vendor_python.children.reject { |path| path == venv_root }.each(&:rmtree) if vendor_python.exist?

  with_env(UV_PROJECT_ENVIRONMENT: venv_root.to_s) do
    SystemCommand.safe_system uv, "sync", "--frozen", "--project", formula_analytics_root, out: :err
  end
end

#venv_python ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



48
49
50
# File 'utils/analytics/influx.rb', line 48

def venv_python
  venv_root/"bin/python"
end

#venv_root ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



42
43
44
45
# File 'utils/analytics/influx.rb', line 42

def venv_root
  python_version = (formula_analytics_root/".python-version").read.chomp
  Pathname.new("~/.brew-formula-analytics/vendor/python").expand_path/python_version
end