Class: Maze::Client::BitBarClientUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/maze/client/bb_client_utils.rb

Constant Summary collapse

BB_READY_FILE =
'bb.ready'
BB_KILL_FILE =
'bb.kill'
BB_USER_PREFIX =
'BB_USER_'
BB_KEY_PREFIX =
'BB_KEY_'

Class Method Summary collapse

Class Method Details

.dashboard_capabilitiesHash

Determines capabilities used to organise sessions in the BitBar dashboard.

Returns:

  • (Hash)

    A hash containing the capabilities.



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
# File 'lib/maze/client/bb_client_utils.rb', line 138

def dashboard_capabilities

  # Determine project name
  if ENV['BUILDKITE']
    $logger.info 'Using BUILDKITE_PIPELINE_SLUG for BitBar project name'
    project = ENV['BUILDKITE_PIPELINE_SLUG']
  else
    # Attempt to use the current git repo
    output, status = Maze::Runner.run_command('git rev-parse --show-toplevel')
    if status == 0
      project = File.basename(output[0].strip)
    else
      $logger.warn 'Unable to determine project name, consider running Maze Runner from within a Git repository'
      project = 'Unknown'
    end
  end

  # Test run
  if ENV['BUILDKITE']
    bk_retry = ENV['BUILDKITE_RETRY_COUNT']
    retry_string = if !bk_retry.nil? && bk_retry.to_i > 0
                     " (#{bk_retry})"
                   else
                     ''
                   end
    test_run = "#{ENV['BUILDKITE_BUILD_NUMBER']} - #{ENV['BUILDKITE_LABEL']}#{retry_string}"
  else
    test_run = Maze.run_uuid
  end

  $logger.info "BitBar project name: #{project}"
  $logger.info "BitBar test run: #{test_run}"
  {
    'bitbar:options' => {
      bitbar_project: project,
      bitbar_testrun: test_run
    }
  }
end

.date_to_milliseconds(date_string) ⇒ Object



223
224
225
226
227
228
229
230
231
232
# File 'lib/maze/client/bb_client_utils.rb', line 223

def date_to_milliseconds(date_string)
  begin
    date_format = "%Y-%m-%d"
    parsed_date = DateTime.strptime(date_string, date_format)
    milliseconds = (parsed_date.to_time.to_f * 1000).to_i
    milliseconds
  rescue ArgumentError
    raise "Invalid date format. Please use YYYY-MM-DD."
  end
end

.get_ids(api_key, project_name = nil) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/maze/client/bb_client_utils.rb', line 179

def get_ids(api_key, project_name = nil)
  base_url = 'https://cloud.bitbar.com/api/me/projects?limit=100'
  url = project_name ? "#{base_url}&filter=name_eq_#{project_name}" : base_url

  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri.request_uri)
  request.basic_auth(api_key, '')

  begin
    response = http.request(request)
    raise "HTTP request failed with code #{response.code}" unless response.is_a?(Net::HTTPSuccess)
    json_body_data = JSON.parse(response.body)['data']
    json_body_data.map { |project| [project['id'], project['name']] }
  rescue JSON::ParserError
    raise 'Failed to parse JSON response'
  rescue StandardError => e
    raise "An error occurred: #{e.message}"
  end
end

.get_unsuccessful_runs(api_key, project_id, date) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/maze/client/bb_client_utils.rb', line 202

def get_unsuccessful_runs(api_key, project_id, date)
  new_date = date_to_milliseconds(date)
  url = URI.parse("https://cloud.bitbar.com/api/me/projects/#{project_id}/runs?filter=successRatio_eq_0.0;d_createTime_on_#{new_date}")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(url.request_uri)
  request.basic_auth(api_key, '')

  begin
    response = http.request(request)
    raise "HTTP request failed with code #{response.code}" unless response.is_a?(Net::HTTPSuccess)
    JSON.parse(response.body)['data']
  rescue JSON::ParserError
    raise 'Failed to parse JSON response'
  rescue StandardError => e
    raise "An error occurred: #{e.message}"
  end
end

.start_local_tunnel(sb_local, username, access_key) ⇒ Object

Starts the BitBar local tunnel

Parameters:

  • sb_local (String)

    path to the SBSecureTunnel binary

  • username (String)

    Username to start the tunnel with

  • access_key (String)

    access key



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/maze/client/bb_client_utils.rb', line 97

def start_local_tunnel(sb_local, username, access_key)
  # Make sure the ready/kill files are already deleted
  File.delete(BB_READY_FILE) if File.exist?(BB_READY_FILE)
  File.delete(BB_KILL_FILE) if File.exist?(BB_KILL_FILE)

  $logger.info 'Starting SBSecureTunnel'
  command = "#{sb_local} --username #{username} --authkey #{access_key} --acceptAllCerts " \
          "--ready #{BB_READY_FILE} --kill #{BB_KILL_FILE}"

  output = start_tunnel_thread(command)

  success = Maze::Wait.new(timeout: 30).until do
    File.exist?(BB_READY_FILE)
  end
  unless success
    $logger.error "Failed: #{output}"
  end
end

.stop_local_tunnelObject

Stops the local tunnel



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/maze/client/bb_client_utils.rb', line 117

def stop_local_tunnel
  FileUtils.touch(BB_KILL_FILE)

  success = Maze::Wait.new(timeout: 30).until do
    @tunnel_thread.nil? || !@tunnel_thread.alive?
  end

  if success
    $logger.info("Shutdown SBSecureTunnel")
  else
    $logger.error("Failed to shutdown SBSecureTunnel!")
  end

  @tunnel_thread = nil
  File.delete(BB_READY_FILE) if File.exist?(BB_READY_FILE)
  File.delete(BB_KILL_FILE) if File.exist?(BB_KILL_FILE)
end

.upload_app(api_key, app, app_id_file = nil, max_attempts = 5) ⇒ Object

Uploads an app to BitBar for later consumption

Parameters:

  • api_key (String)

    The BitBar API key

  • app (String)

    A path to the application file

  • app_id_file (String) (defaults to: nil)

    the file to write the uploaded app url to BitBar

  • max_attempts (Integer) (defaults to: 5)

    the maximum number of attempts to upload the app



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
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
82
83
84
85
86
# File 'lib/maze/client/bb_client_utils.rb', line 23

def upload_app(api_key, app, app_id_file=nil, max_attempts=5)
  uuid_regex = /\A[0-9]+\z/

  if uuid_regex.match? app
    $logger.info "Using pre-uploaded app with ID #{app}"
    app_uuid = app
  else
    upload_proc = Proc.new do |app_path|
      $logger.info "Uploading app: #{app_path}"

      # Upload the app to BitBar
      uri = URI('https://cloud.bitbar.com/api/me/files')
      request = Net::HTTP::Post.new(uri)
      request.basic_auth(api_key, '')
      request.set_form({ 'file' => File.new(app_path, 'rb') }, 'multipart/form-data')

      Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
        http.request(request)
      end
    end

    expanded_app = Maze::Helper.expand_path(app)

    attempts = 0
    app_uuid = nil
    last_error = nil
    while attempts < max_attempts && app_uuid.nil?
      attempts += 1
      begin
        response = upload_proc.call(expanded_app)
        body = JSON.parse(response.body)
        if body.key?('id')
          app_uuid = body['id'].to_s
          $logger.info "Uploaded app ID: #{app_uuid}"
          $logger.info 'You can use this ID to avoid uploading the same app more than once.'
        else
          error_string = "Unexpected response body: #{body}"
          $logger.error error_string
          last_error = RuntimeError.new(error_string)
        end
      rescue JSON::ParserError => error
        last_error = error
        Bugsnag.notify error
        $logger.error "Expected JSON response, received: #{response}"
      rescue => error
        last_error = error
        Bugsnag.notify error
        $logger.error "Unexpected error uploading app: #{error}"
      end
    end

    if app_uuid.nil?
      $logger.error "App upload to BitBar failed after #{attempts} attempts"
      raise last_error
    end
  end

  unless app_id_file.nil?
    $logger.info "Writing uploaded app id to #{app_id_file}"
    File.write(Maze::Helper.expand_path(app_id_file), app_uuid)
  end

  app_uuid
end

.use_local_tunnel?Boolean

Returns:

  • (Boolean)


88
89
90
# File 'lib/maze/client/bb_client_utils.rb', line 88

def use_local_tunnel?
  Maze.config.start_tunnel && !Maze.config.aws_public_ip
end