Class: VagrantPlugins::S3MultiDownloader::MetadataHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-s3-multidownloader/metadata_handler.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ui) ⇒ MetadataHandler

Returns a new instance of MetadataHandler.



10
11
12
13
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 10

def initialize(ui)
  @ui = ui
  @logger = Log4r::Logger.new("vagrant::s3-multidownloader::metadata")
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 8

def logger
  @logger
end

#uiObject (readonly)

Returns the value of attribute ui.



8
9
10
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 8

def ui
  @ui
end

Instance Method Details

#download_metadata(url, destination, client, bucket, key) ⇒ Object

Download and parse a metadata.json file



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 35

def (url, destination, client, bucket, key)
  @ui.info("Downloading metadata from S3: #{url}")

  # Use the client directly to download the metadata file
  client.get_object(
    response_target: destination,
    bucket: bucket,
    key: key
  )

  # Parse the metadata
  begin
     = JSON.parse(File.read(destination))
    return 
  rescue JSON::ParserError => e
    @ui.error("Failed to parse metadata.json: #{e.message}")
    return nil
  rescue StandardError => e
    @ui.error("Error processing metadata.json: #{e.message}")
    return nil
  end
end

#find_provider_url(version_data, provider_name = nil) ⇒ Object

Find the provider URL in a version



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 118

def find_provider_url(version_data, provider_name = nil)
  return nil unless version_data && version_data.key?('providers') && version_data['providers'].is_a?(Array)

  providers = version_data['providers']

  # If provider_name is specified, find that specific provider
  if provider_name && !provider_name.empty?
    provider = providers.find { |p| p['name'] == provider_name }
    if provider && provider.key?('url')
      @ui.detail("Found URL for provider #{provider_name}: #{provider['url']}")
      return provider['url']
    end
  end

  # Otherwise, just return the first provider with a URL
  providers.each do |provider|
    if provider.key?('url')
      @ui.detail("Using provider #{provider['name']}: #{provider['url']}")
      return provider['url']
    end
  end

  nil
end

#find_version_in_metadata(metadata, version = nil) ⇒ Object

Find a specific version in the metadata



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
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
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 59

def (, version = nil)
  return nil unless  && .key?('versions') && ['versions'].is_a?(Array)

  available_versions = ['versions']
  @ui.detail("Available versions: #{available_versions.map { |v| v['version'] }.join(', ')}")

  if version
    # This handles both exact version number and version constraints
    if version.include?('>') || version.include?('<') || version.include?('~>')
      @ui.detail("Detected version constraint: #{version}")
      # Parse the constraint and find the highest satisfying version
      begin
        require 'vagrant/util/template_renderer'
        version_constraint = Gem::Requirement.new(version)

        # Find all versions that satisfy the constraint
        satisfying_versions = available_versions.select do |v|
          begin
            version_number = Gem::Version.new(v['version'])
            version_constraint.satisfied_by?(version_number)
          rescue
            false
          end
        end

        if satisfying_versions.empty?
          @ui.warn("No versions matching constraint #{version} found in metadata")
          return nil
        end

        # Select the highest version that satisfies the constraint
        selected_version = satisfying_versions.sort_by { |v| Gem::Version.new(v['version']) rescue Gem::Version.new('0.0.0') }.last
        @ui.success("Selected version #{selected_version['version']} for constraint #{version}")
        return selected_version
      rescue => e
        @ui.error("Error parsing version constraint: #{e.message}")
        # Fall back to exact match
        @ui.warn("Falling back to exact version match")
      end
    end

    # Find the requested version (exact match)
    requested_version = available_versions.find { |v| v['version'] == version }
    if requested_version
      @ui.success("Found requested version: #{version}")
      return requested_version
    else
      @ui.warn("Requested version #{version} not found in metadata")
      return nil
    end
  else
    # No specific version requested, use the latest version
    latest_version = available_versions.sort_by { |v| Gem::Version.new(v['version']) rescue Gem::Version.new('0.0.0') }.last
    @ui.detail("Using latest version: #{latest_version['version']}")
    return latest_version
  end
end

#get_requested_version(env) ⇒ Object

Extract version from the environment if available



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 16

def get_requested_version(env)
  return nil if !env || !env[:machine] || !env[:machine].config || !env[:machine].config.vm

  if env[:machine].config.vm.box_version
    version = env[:machine].config.vm.box_version
    @ui.detail("Found box_version in Vagrantfile: #{version}")
    return version
  end

  nil
end

#metadata_url?(url) ⇒ Boolean

Check if the URL points to a metadata.json file

Returns:

  • (Boolean)


29
30
31
32
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 29

def (url)
  return false unless url
  url.to_s.end_with?('metadata.json')
end

#process_metadata_file(metadata_path) ⇒ Object

Process a metadata file to ensure all S3 URLs are properly formatted



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
# File 'lib/vagrant-s3-multidownloader/metadata_handler.rb', line 144

def ()
  @ui.info("Processing metadata.json file for S3 URLs")
  begin
    # Read and parse the metadata.json file
     = JSON.parse(File.read())

    # Check if the metadata has versions
    if .key?('versions') && ['versions'].is_a?(Array)
      @ui.detail("Found #{metadata['versions'].size} versions in metadata")

      # Update all S3 URLs in the metadata to ensure they'll be handled correctly
      ['versions'].each_with_index do |version, index|
        if version.key?('providers') && version['providers'].is_a?(Array)
          version['providers'].each do |provider|
            if provider.key?('url') && provider['url'].to_s.start_with?('s3://')
              @ui.detail("Found S3 URL in metadata: #{provider['url']}")
              # No need to modify the URL as the plugin already handles s3:// URLs
            end
          end
        end
      end

      # Write the updated metadata back to the file
      File.open(, 'w') do |file|
        file.write(JSON.pretty_generate())
      end

      @ui.detail("Metadata processing complete")
      return 
    else
      @ui.detail("No versions found in metadata.json")
      return nil
    end
  rescue JSON::ParserError => e
    @ui.error("Failed to parse metadata.json: #{e.message}")
    return nil
  rescue StandardError => e
    @ui.error("Error processing metadata.json: #{e.message}")
    return nil
  end
end