Class: Builderator::Model::Images

Inherits:
Base
  • Object
show all
Defined in:
lib/builderator/model/images.rb

Overview

EC2 AMI Resources

Constant Summary collapse

LIMIT =
24
PROPERTIES =
%w(image_location state owner_id public architecture image_type
name description root_device_type virtualization_type
hypervisor)

Instance Attribute Summary

Attributes inherited from Base

#resources

Instance Method Summary collapse

Methods inherited from Base

#find, #initialize, #reject, #select, #unused

Constructor Details

This class inherits a constructor from Builderator::Model::Base

Instance Method Details

#fetchObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/builderator/model/images.rb', line 20

def fetch
  @resources = {}.tap do |i|
    Util.ec2.describe_images(:filters => [
      {
        :name => 'state',
        :values => %w(available)
      }
    ], :owners => %w(self)).each do |page|
      page.images.each do |image|
        properties = Util.from_tags(image.tags)
        properties['creation_date'] = DateTime.iso8601(image.creation_date)
        PROPERTIES.each { |pp| properties[pp] = image[pp.to_sym] }

        i[image.image_id] = {
          :id => image.image_id,
          :properties => properties,
          :snapshots => image.block_device_mappings.map { |b| b.ebs.snapshot_id rescue nil }.reject(&:nil?),
          :parent => properties.fetch('parent_ami', '(undefined)')
        }
      end
    end
  end
end

#in_use(options = {}) ⇒ Object



79
80
81
82
83
84
85
86
# File 'lib/builderator/model/images.rb', line 79

def in_use(options = {})
  {}.tap do |used|
    used.merge!(select(Model.instances.images))
    used.merge!(select(Model.launch_configs.images))
    used.merge!(latest(options))
    used.merge!(select(used.values.map { |i| i[:parent] }))
  end
end

#latest(options = {}) ⇒ Object



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
# File 'lib/builderator/model/images.rb', line 48

def latest(options = {})
  {}.tap do |latest|
    ## Group images
    group_by = options.fetch('group-by', [])
    groups = {}.tap do |g|
      break { 'all' => resources.values } if group_by.empty?

      resources.each do |_, image|
        (g[group_by.map do |gg|
          image[:properties].fetch(gg.to_s, '(unknown)')
        end.join(':')] ||= []) << image
      end
    end

    ## Sort each grouping
    sort_by = options.fetch('sort-by', 'creation_date')
    groups.each do |_, group|
      group.sort! { |a, b| b[:properties][sort_by] <=> a[:properties][sort_by] }
    end

    ## Slice to `keep` length
    keep = options.fetch('keep', 5)
    groups.each do |_, group|
      group.slice!(keep..-1)
    end

    ## Reduce
    groups.values.flatten.each { |i| latest[i[:id]] = i }
  end
end

#snapshotsObject



44
45
46
# File 'lib/builderator/model/images.rb', line 44

def snapshots
  resources.values.map { |i| i[:snapshots] }.flatten
end