Class: Puppet::GoogleAPI::Compute::Instances

Inherits:
Object
  • Object
show all
Defined in:
lib/puppet/google_api/compute.rb

Instance Method Summary collapse

Constructor Details

#initialize(api, compute) ⇒ Instances

Returns a new instance of Instances.



14
15
16
17
# File 'lib/puppet/google_api/compute.rb', line 14

def initialize(api, compute)
  @api     = api
  @compute = compute
end

Instance Method Details

#add_instance_to_s_to(instance) ⇒ Object



19
20
21
22
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
87
88
89
90
# File 'lib/puppet/google_api/compute.rb', line 19

def add_instance_to_s_to(instance)
  # Add a custom method to an AutoParse generated set of data that will
  # return something meaningful when turned into a string; this is careful
  # to try and set itself correctly for human consumption.
  #
  # If only the upstream library did the right thing out of the box, eh?
  def instance.to_s
    text = {
      name:   name,
      status: status.downcase + (status_message ? " #{status_message}" : '')
    }
    description and text.merge!(description: description)
    tags.items.empty? or text.merge!(tags: tags.items.join(', '))

    unless .items.empty?
      content = .items.inject({}) do |hash, item|
        value = if item.value.length > 40 then
                  item.value[0,37] + '...'
                else
                  item.value
                end

        hash[item.key] = value
        hash
      end

      text.merge!(metadata: Puppet::GoogleAPI.hash_to_human_s(content))
    end

    # @todo danielp 2013-09-16: these are both URLs pointing to the actual
    # instance; we should fetch the content from them -- with full auth,
    # since that is required to see them -- and display a more
    # human-meaningful response.  (Possibly the object, possibly just the
    # name...)
    text.merge!(type: machine_type, kernel: kernel)
    image and text.merge!(image: image)

    # Networking details...
    #
    # @todo danielp 2013-09-16: this doesn't extract any of the available
    # data about those interfaces -- are they public, what is the external
    # IP, etc. at least the later is probably going to be highly desired
    # by some users.  Worst luck, though, the definitions are complex and
    # can support more than one access type per nic...
    text.merge!(router: can_ip_forward)
    unless network_interfaces.empty?
      data = network_interfaces.map do |int|
        [int.name, int.network_ip]
      end

      text.merge!(networks: Puppet::GoogleAPI.hash_to_human_s(Hash[data]))
    end

    unless disks.empty?
      data = disks.sort_by {|disk| disk.index }.map do |disk|
        [
          disk.device_name,
          [
            disk.type.downcase,
            disk.mode.downcase,
            disk.boot ? 'boot' : nil
          ].compact.join(' ')
        ]
      end

      text.merge!(disks: Puppet::GoogleAPI.hash_to_human_s(Hash[data]))
    end

    # Now, turn that map into human-focused output
    Puppet::GoogleAPI.hash_to_human_s(text)
  end
end

#aggregated_list(project) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/puppet/google_api/compute.rb', line 108

def aggregated_list(project)
  pages = @api.execute(@compute.instances.aggregated_list, project: project)
  # Our collection is a map, keyed by zone and value being an array of
  # instance records.  We need to flatten this by merging the values if we
  # get duplicate keys (eg: because we have more than one page of machines
  # in a single zone, or because a zone instance list happens to contain a
  # page boundary.)
  instances = Hash.new {|hash, key| hash[key] = [] }
  pages.each do |page|
    # *sigh*  there is *no* other mechanism to get the dynamic list of
    # keys, so we turn it into a hash.  Since we want the class not the
    # hash version of the value, we have to indirect like this.
    page.items.to_hash.keys.each do |zone|
      # Instances will return an empty array if the list is empty, even
      # though the returned data contains only the various warning bits
      # and pieces.
      instances[zone] += page.items[zone].instances
    end
  end

  instances.values.flatten.each {|i| add_instance_to_s_to(i) }

  instances
end

#create(project, zone, name, type, options) ⇒ Object



133
134
135
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
# File 'lib/puppet/google_api/compute.rb', line 133

def create(project, zone, name, type, options)
  params = {project: project, zone: zone}
  body   = {name: name, metadata: {items: []}}

  if machine_type = @api.compute.machine_types.get(project, zone, type)
    body[:machineType] = machine_type.self_link
  else
    raise "machine type #{type} not found in project #{project} zone #{zone}"
  end

  case options[:image]
  when /^https?:/i
    # The rest of the system will error-check the URL you supplied.
    body[:image] = options[:image]

  when String
    image = nil
    ([project] + options[:image_search]).each do |where|
      image = @api.compute.images.get(where, options[:image])
      break if image
    end

    image or
      raise "unable to find the image '#{options[:image]}' for #{project}"

    body[:image] = image.self_link

  else
    raise "the boot image must be either a full HTTP URL, or an image name"
  end

  # @todo danielp 2013-09-17: we don't support network configuration
  # outside this fixed-in-place default.  Good luck.
  body[:networkInterfaces] = [{
      # @todo danielp 2013-09-17: this just assumes the network exists.
      # Eventually we need to fix that to allow some real network config,
      # and also to error-check this fetch.
      network: @api.compute.networks.get(project, 'default').self_link,
      # @todo danielp 2013-09-17: right now, we forcibly expose everything
      # to the outside world.  In the longer term that should change (as
      # best practice is to put *only* your front-end nodes on the
      # Internet), but that requires (a) network configuration input, and
      # (b) solving the problem of how to install Puppet on that node...
      accessConfigs: [
        {type: 'ONE_TO_ONE_NAT', name: 'external nat'}
      ]
  }]

  if options[:login]
    # @todo danielp 2013-09-18: I suspect that if you store your SSH
    # public key in PEM format, bad things follow from this line!
    keydata = Pathname(options[:key]).sub_ext('.pub').read
    value = "#{options[:login]}:#{keydata}"

    # Why didn't the just use a regular JSON object for this?  *sigh*
    body[:metadata][:items] << {key: 'sshKeys', value: value}
  end

  result = @api.execute(@compute.instances.insert, params, body).first
  while options[:wait] and result.status != 'DONE'
    # I wonder if I should show some sort of progress bar...
    sleep 1
    result = @api.compute.zone_operations.get(project, zone, result.name)
  end

  return result
end

#delete(project, zone, name, options) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
# File 'lib/puppet/google_api/compute.rb', line 201

def delete(project, zone, name, options)
  params = {project: project, zone: zone, instance: name}
  result = @api.execute(@compute.instances.delete, params).first
  while options[:wait] and result.status != 'DONE'
    # I wonder if I should show some sort of progress bar...
    sleep 1
    result = @api.compute.zone_operations.get(project, zone, result.name)
  end

  return result
end

#get(project, zone, name) ⇒ Object



92
93
94
95
96
97
# File 'lib/puppet/google_api/compute.rb', line 92

def get(project, zone, name)
  args = {project: project, zone: zone, instance: name}
  @api.execute(@compute.instances.get, args).first
rescue
  nil
end

#list(project, zone) ⇒ Object



99
100
101
102
103
104
105
106
# File 'lib/puppet/google_api/compute.rb', line 99

def list(project, zone)
  instances = @api.execute(@compute.instances.list, project: project, zone: zone)
  # Turn our collection of pages into a single, flat collection; we don't
  # need any of the additional data in the containers.
  instances = instances.map {|i| i.items }.flatten
  instances.each {|i| add_instance_to_s_to(i) }
  instances
end

#set_metadata(project, zone, name, fingerprint, metadata, options) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/puppet/google_api/compute.rb', line 213

def (project, zone, name, fingerprint, , options)
  params = {project: project, zone: zone, instance: name}
  body = {
    fingerprint: [fingerprint].pack('m'),
    items: .inject([]) do |array, (key, value)|
      array << {key: key, value: value}
    end
  }

  result = @api.execute(@compute.instances., params, body).first
  while options[:wait] and result.status != 'DONE'
    # I wonder if I should show some sort of progress bar...
    sleep 1
    result = @api.compute.zone_operations.get(project, zone, result.name)
  end

  return result
end