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.

Defined Under Namespace

Classes: CategoryDimensions

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
CORE_TAP_NAMES =

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.

T.let({ formula: "homebrew/core", cask: "homebrew/cask" }.freeze, T::Hash[Symbol, String])
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
DEFAULT_CATEGORY_DIMENSIONS =

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.

CategoryDimensions.new(
  bucket: :formula_install, dimension_key: :formula, groups: [:package, :tap_name, :options],
).freeze
CATEGORY_DIMENSIONS =

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.

T.let(category_dimensions.freeze, T::Hash[Symbol, CategoryDimensions])

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_incompatible, #pretty_install_status, #pretty_installed, #pretty_removed, #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)


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

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:



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

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 = if macos_version < "10.12"
      "OS X"
    else
      "macOS"
    end
    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+))?/
    release_name = Regexp.last_match(3)&.downcase
    "Armbian #{Regexp.last_match(1)}.#{Regexp.last_match(2)} #{release_name}".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:



81
82
83
# File 'utils/analytics/influx.rb', line 81

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:



86
87
88
# File 'utils/analytics/influx.rb', line 86

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

#package_renames(dimension_key) ⇒ Hash{String => 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:



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'utils/analytics/influx.rb', line 317

def package_renames(dimension_key)
  return {} unless [:formula, :cask].include?(dimension_key)

  require "tap"

  package_renames = {}
  casks = dimension_key == :cask
  Tap.all.select(&:official?).each do |tap|
    (casks ? tap.cask_renames : tap.formula_renames).each do |old_name, new_name|
      package_renames["#{tap.name}/#{old_name}"] = "#{tap.name}/#{new_name}"
    end
    tap.tap_migrations.each do |old_name, new_name|
      package_renames["#{tap.name}/#{old_name}"] = if Utils.full_name?(new_name)
        new_name
      else
        "#{new_name}/#{old_name}"
      end
    end
  end
  package_renames
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:



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

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

  categories.map do |category|
    additional_where = all_core_formulae_json ? " AND tap_name ~ '^homebrew/'" : ""
    dimensions = CATEGORY_DIMENSIONS.fetch(category, DEFAULT_CATEGORY_DIMENSIONS)
    dimension_key = dimensions.dimension_key
    # 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" if category == :homebrew_env_config
    additional_where += " AND on_request = 'true'" if category == :formula_install_on_request

    package_renames = self.package_renames(dimension_key)

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

    json = {
      category:,
      total_items: 0,
      start_date:  Date.today - days_ago.to_i,
      end_date:    Date.today,
      total_count: 0,
      items:       [],
    }

    each_influx_record(query) do |record|
      count = record["count"]
      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)

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

      platform = "#{record["os"]} #{record["arch"]}"
      dimension = case category
      when :homebrew_devcmdrun_developer
        "devcmdrun=#{record["devcmdrun"]} HOMEBREW_DEVELOPER=#{record["developer"]}"
      when :homebrew_os_arch_ci
        ci_suffix = " (CI)" if record["ci"] == "true"
        "#{platform}#{ci_suffix}"
      when :homebrew_prefixes
        prefix = record["prefix"].to_s
        standard = STANDARD_PREFIXES.any? { |std| std.casecmp?(prefix) }
        standard ? prefix : "custom-prefix (#{platform})"
      when :os_versions
        format_os_version_dimension(record["os_name_and_version"])
      when :command_run_options
        sorted_options = record["options"].to_s.split.sort.join(" ")
        "#{record["command"]} #{sorted_options}"
      when :test_bot_test
        test_bot_dimension(record["command"], os: record["os"].to_s, arch: record["arch"].to_s,
                                              passed: record["passed"] == "true")
      else
        record[dimensions.groups.first.to_s]
      end
      next if dimension.blank?

      if dimension_key.is_a?(Symbol) && (core_tap_name = CORE_TAP_NAMES[dimension_key])
        dimension = [record["tap_name"].presence, dimension].compact.join("/")
        seen = Set.new
        while (new_name = package_renames[dimension]) && seen.add?(dimension)
          dimension = new_name
        end

        next if all_core_formulae_json && !dimension.start_with?("#{core_tap_name}/")

        dimension = dimension.delete_prefix("#{core_tap_name}/")
      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.
        options = options.split.include?("--HEAD") ? "--HEAD" : "" if all_core_formulae_json
        dimension = "#{dimension} #{options}"
      end

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

      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
    count_keys = [:count]
    count_keys += [:non_default_count, :set_default_count, :unset_count] if category == :homebrew_env_config
    json[:items] = json[:items].group_by { |item| item[dimension_key] }.map do |_, items|
      items.fetch(0).merge(count_keys.to_h { |key| [key, items.sum { |item| item[key] }] })
    end
    json[:total_items] = json[:items].length

    if all_core_formulae_json
      json[:formulae] = json.delete(:items).group_by { |item| item[dimension_key].split.first }.sort.to_h
      json[:formulae].reject! { |name, _| name.include?("/") }
      json[:formulae].each_value do |items|
        items.sort_by! { |item| -item[:count] }.each do |item|
          item.delete(:number)
          item[:count] = Utils::Analytics.format_count(item[:count])
        end
      end
    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")
        count_keys.each { |key| item[key] = Utils::Analytics.format_count(item[key]) }
        next if category != :homebrew_env_config

        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.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'utils/analytics/influx.rb', line 65

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

#test_bot_dimension(command, os:, arch:, passed:) ⇒ 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:



302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'utils/analytics/influx.rb', line 302

def test_bot_dimension(command, os:, arch:, passed:)
  command_and_package, options = 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.
  return if %w[audit install linkage style test].exclude?(command_and_package.first)
  return if command_and_package.last.to_s.include?("/")
  return if options.intersect?(%w[--tap= --only-dependencies --cached])

  command_line = (command_and_package + options.sort).join(" ")
  result = passed ? "PASSED" : "FAILED"
  "#{command_line} (#{os} #{arch}) (#{result})"
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:



97
98
99
# File 'utils/analytics/influx.rb', line 97

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:



91
92
93
94
# File 'utils/analytics/influx.rb', line 91

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