|
| 1 | +require 'pathname' |
| 2 | +require 'open-uri' |
| 3 | +require 'json' |
| 4 | + |
| 5 | +module Elastic |
| 6 | + CURRENT_PATH = Pathname(File.expand_path(__dir__)) |
| 7 | + class << self |
| 8 | + def download_artifacts(version) |
| 9 | + json_filename = CURRENT_PATH.join('tmp/artifacts.json') |
| 10 | + |
| 11 | + # Create ./tmp if it doesn't exist |
| 12 | + Dir.mkdir(CURRENT_PATH.join('tmp'), 0700) unless File.directory?(CURRENT_PATH.join('tmp')) |
| 13 | + |
| 14 | + # Download json file with package information for version: |
| 15 | + json_url = "https://artifacts-api.elastic.co/v1/versions/#{version}" |
| 16 | + download_file!(json_url, json_filename) |
| 17 | + |
| 18 | + # Parse the downloaded JSON |
| 19 | + begin |
| 20 | + artifacts = JSON.parse(File.read(json_filename)) |
| 21 | + rescue StandardError => e |
| 22 | + STDERR.puts "[!] Couldn't read JSON file #{json_filename}" |
| 23 | + exit 1 |
| 24 | + end |
| 25 | + |
| 26 | + # Either find the artifacts for the exact same build hash from the current running cluster or |
| 27 | + # use the first one from the list of builds: |
| 28 | + build_hash_artifact = artifacts['version']['builds'].first |
| 29 | + zip_url = build_hash_artifact.dig('projects', 'elasticsearch', 'packages').select { |k, _| k =~ /rest-resources-zip/ }.map { |_, v| v['url'] }.first |
| 30 | + |
| 31 | + # Dig into the elasticsearch packages, search for the rest-resources-zip package and return the URL: |
| 32 | + build_hash_artifact.dig('projects', 'elasticsearch', 'packages').select { |k, _| k =~ /rest-resources-zip/ }.map { |_, v| v['url'] }.first |
| 33 | + |
| 34 | + # Download the zip file |
| 35 | + filename = CURRENT_PATH.join("tmp/#{zip_url.split('/').last}") |
| 36 | + download_file!(zip_url, filename) |
| 37 | + |
| 38 | + spec = CURRENT_PATH.join('tmp/rest-api-spec') |
| 39 | + FileUtils.remove_dir(spec) if File.directory?(spec) |
| 40 | + |
| 41 | + puts "Unzipping file #{filename}" |
| 42 | + `unzip -o #{filename} -d tmp/` |
| 43 | + `rm #{filename}` |
| 44 | + puts "Artifacts downloaded in ./tmp, build hash #{@build_hash}" |
| 45 | + File.write(CURRENT_PATH.join('tmp/rest-api-spec/build_hash'), @build_hash) |
| 46 | + end |
| 47 | + |
| 48 | + def download_file!(url, filename) |
| 49 | + puts "Downloading #{filename} from #{url}" |
| 50 | + File.open(filename, "w") do |downloaded_file| |
| 51 | + URI.open(url, "rb") do |artifact_file| |
| 52 | + downloaded_file.write(artifact_file.read) |
| 53 | + end |
| 54 | + end |
| 55 | + puts "Successfully downloaded #{filename}" |
| 56 | + |
| 57 | + unless File.exist?(filename) |
| 58 | + warn "[!] Couldn't download #{filename}" |
| 59 | + exit 1 |
| 60 | + end |
| 61 | + rescue StandardError => e |
| 62 | + abort e.message |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments