1
0
Fork 0
mirror of https://github.com/fog/fog.git synced 2022-11-09 13:51:43 -05:00

Merge fog 1.0.0 from upstream, and update namespace changes across the HP provider for storage and compute services.

This commit is contained in:
Rupak Ganguly 2011-10-17 15:25:07 -04:00
commit 7e1a287e4d
1656 changed files with 35158 additions and 7204 deletions

3
.gitignore vendored
View file

@ -4,9 +4,10 @@
*.sw?
.bundle
.DS_Store
docs/_site/*
coverage
doc/*
docs/_site/*
docs/about/supported_services.markdown
Gemfile.lock
rdoc
pkg

View file

@ -12,10 +12,10 @@ fog is the Ruby cloud computing library, top to bottom:
Now type 'fog' to try stuff, confident that fog will let you know what to do. Here is an example of wading through server creation for Amazon Elastic Compute Cloud:
>> server = AWS.servers.create
>> server = Compute[:aws].servers.create
ArgumentError: image_id is required for this operation
>> server = AWS.servers.create(:image_id => 'ami-5ee70037')
>> server = Compute[:aws].servers.create(:image_id => 'ami-5ee70037')
<Fog::AWS::EC2::Server [...]>
>> server.destroy # cleanup after yourself or regret it, trust me
@ -26,7 +26,7 @@ Now type 'fog' to try stuff, confident that fog will let you know what to do. He
A high level interface to each cloud is provided through collections, such as `images` and `servers`.
You can see a list of available collections by calling `collections` on the connection object. You can try it out using the `fog` command:
>> AWS.collections
>> Compute[:aws].collections
[:addresses, :directories, ..., :volumes, :zones]
Some collections are available across multiple providers:
@ -84,7 +84,7 @@ You can see a list of available requests by calling #requests on the connection
For instance, ec2 provides methods related to reserved instances that don't have any models (yet). Here is how you can lookup your reserved instances:
$ fog
>> AWS[:ec2].describe_reserved_instances
>> Compute[:aws].describe_reserved_instances
#<Excon::Response [...]>
It will return an {excon}[http://github.com/geemus/excon] response, which has `body`, `headers` and `status`. Both return nice hashes.
@ -117,7 +117,7 @@ Wonder how you can get a lovely fog shirt? Look no further!
* Blue shirts go to people who have contributed indirectly, great examples are writing blog posts or giving lightning talks.
* Grey shirts and a follow from @fog go to people who have made it on to the {contributors list}[https://github.com/geemus/fog/contributors] by submitting code.
* Black shirts go to people who have made it on to the {collaborators list}[https://github.com/api/v2/json/repos/show/geemus/fog/collaborators] by coercing geemus into adding them (geemus is currently the only member of this list).
* Black shirts go to people who have made it on to the {collaborators list}[https://github.com/api/v2/json/repos/show/geemus/fog/collaborators] by coercing geemus into adding them.
== Additional Resources

136
Rakefile
View file

@ -1,7 +1,7 @@
require 'rubygems'
require 'bundler/setup'
require 'date'
require 'lib/fog'
require File.dirname(__FILE__) + '/lib/fog'
#############################################################################
#
@ -46,6 +46,15 @@ end
task :default => :test
namespace :test do
task :dynect do
[false].each do |mock|
sh("export FOG_MOCK=#{mock} && bundle exec shindont tests/dns/requests/dynect")
#sh("export FOG_MOCK=#{mock} && bundle exec shindont tests/dns/models/")
end
end
end
task :examples do
sh("export FOG_MOCK=false && bundle exec shindont examples")
# some don't provide mocks so we'll leave this out for now
@ -53,8 +62,7 @@ task :examples do
end
task :test do # => :examples do
Rake::Task[:mock_tests].invoke
Rake::Task[:real_tests].invoke
Rake::Task[:mock_tests].invoke && Rake::Task[:examples].invoke && Rake::Task[:real_tests].invoke
end
def tests(mocked)
@ -88,6 +96,31 @@ task :real_tests do
tests(false)
end
task :nuke do
Fog.providers.each do |provider|
next if ['Vmfusion'].include?(provider)
begin
compute = Fog::Compute.new(:provider => provider)
for server in compute.servers
Formatador.display_line("[#{provider}] destroying server #{server.identity}")
server.destroy rescue nil
end
rescue
end
begin
dns = Fog::DNS.new(:provider => provider)
for zone in dns.zones
for record in zone.records
record.destroy rescue nil
end
Formatador.display_line("[#{provider}] destroying zone #{zone.identity}")
zone.destroy rescue nil
end
rescue
end
end
end
desc "Generate RCov test coverage and open in your browser"
task :coverage do
require 'rcov'
@ -116,7 +149,6 @@ end
#############################################################################
task :release => :build do
Rake::Task[:changelog].invoke
unless `git branch` =~ /^\* master$/
puts "You must be on the master branch to release!"
exit!
@ -170,6 +202,20 @@ task :changelog do
changelog << ('=' * changelog[0].length)
changelog << ''
require 'multi_json'
github_repo_data = MultiJson.decode(Excon.get('http://github.com/api/v2/json/repos/show/geemus/fog').body)
data = github_repo_data['repository'].reject {|key, value| !['forks', 'open_issues', 'watchers'].include?(key)}
github_collaborator_data = MultiJson.decode(Excon.get('http://github.com/api/v2/json/repos/show/geemus/fog/collaborators').body)
data['collaborators'] = github_collaborator_data['collaborators'].length
rubygems_data = MultiJson.decode(Excon.get('https://rubygems.org/api/v1/gems/fog.json').body)
data['downloads'] = rubygems_data['downloads']
stats = []
for key in data.keys.sort
stats << "'#{key}' => #{data[key]}"
end
changelog << "Stats! { #{stats.join(', ')} }"
changelog << ''
last_sha = `cat changelog.txt | head -1`.split(' ').last
shortlog = `git shortlog #{last_sha}..HEAD`
changes = {}
@ -196,8 +242,15 @@ task :changelog do
for committer, commits in committers.to_a.sort {|x,y| y[1] <=> x[1]}
if [
'Aaron Suggs',
'Brian Hartsock',
'Christopher Oliver',
'Dylan Egan',
'geemus',
'Henry Addison',
'Lincoln Stoll',
'Luqman Amjad',
'nightshade427',
'Patrick Debois',
'Wesley Beary'
].include?(committer)
next
@ -221,15 +274,17 @@ task :changelog do
file.write("\n\n")
file.write(old_changelog)
end
`echo "#{changelog.join("\n")}" | pbcopy`
p 'changelog copied to clipboard'
end
task :docs do
Rake::Task[:supported_services_docs].invoke
Rake::Task[:upload_fog_io].invoke
Rake::Task[:upload_rdoc].invoke
# connect to storage provider
Fog.credential = :geemus
storage = Fog::Storage.new(:provider => 'AWS')
directory = storage.directories.new(:key => 'fog.io')
# write base index with redirect to new version
directory.files.create(
:body => redirecter('latest'),
@ -241,6 +296,71 @@ task :docs do
Formatador.display_line
end
task :supported_services_docs do
support, shared = {}, []
for key, values in Fog.services
unless values.length == 1
shared |= [key]
values.each do |value|
support[value] ||= {}
support[value][key] = '+'
end
else
value = values.first
support[value] ||= {}
support[value][:other] ||= []
support[value][:other] << key
end
end
shared.sort! {|x,y| x.to_s <=> y.to_s}
columns = [:provider] + shared + [:other]
data = []
for key in support.keys.sort {|x,y| x.to_s <=> y.to_s}
data << { :provider => key }.merge!(support[key])
end
table = ''
table << "<table border='1'>\n"
table << " <tr>"
for column in columns
table << "<th>#{column}</th>"
end
table << "</tr>\n"
for datum in data
table << " <tr>"
for column in columns
if value = datum[column]
case value
when Array
table << "<td>#{value.join(', ')}</td>"
when '+'
table << "<td style='text-align: center;'>#{value}</td>"
else
table << "<th>#{value}</th>"
end
else
table << "<td></td>"
end
end
table << "</tr>\n"
end
table << "</table>\n"
File.open('docs/about/supported_services.markdown', 'w') do |file|
file.puts <<-METADATA
---
layout: default
title: Supported Services
---
METADATA
file.puts(table)
end
end
task :upload_fog_io do
# connect to storage provider
Fog.credential = :geemus
@ -327,4 +447,4 @@ def redirecter(path)
</body>
</html>
HTML
end
end

17
bin/fog
View file

@ -5,7 +5,11 @@ require 'yaml'
Fog.credential = ARGV.first ? ARGV.first.to_sym : nil
Fog.mock! if ENV['FOG_MOCK']
if Fog.credentials.empty?
Fog::Errors.missing_credentials
begin
Fog::Errors.missing_credentials
rescue Fog::Errors::LoadError => error
abort error.message
end
end
require 'fog/bin'
@ -19,7 +23,10 @@ end
if ARGV.length > 1
puts(instance_eval(ARGV[1..-1].join(' ')).to_json)
require 'multi_json'
result = instance_eval(ARGV[1..-1].join(' '))
puts(MultiJson.encode(result))
else
@ -36,6 +43,12 @@ else
Formatador.display_line(":#{Fog.credential} provides #{providers}")
providers = Fog.providers
# FIXME: hacks until we can `include Fog` in bin
CDN = Fog::CDN
Compute = Fog::Compute
DNS = Fog::DNS
Storage = Fog::Storage
catch(:IRB_EXIT) { @irb.eval_input }
end

File diff suppressed because it is too large Load diff

View file

@ -61,6 +61,7 @@
<li><a href="/about/getting_started.html">Getting Started</a></li>
<li><a href="/about/press.html">Press</a></li>
<li><a href="/about/structure.html">Structure</a></li>
<li><a href="/about/supported_services.html">Supported Services</a></li>
<li><a href="/about/users.html">Users</a></li>
</ul>

View file

@ -24,7 +24,7 @@ Now in order to play with our data we need to setup a storage connection.
storage = Fog::Storage.new({
:local_root => '~/fog',
:provider => 'Local',
:provider => 'Local'
})
`storage` will now contain our storage object, configured to use the Local provider from our specified directory.
@ -33,7 +33,7 @@ Now in order to play with our data we need to setup a storage connection.
Now that you have cleared the preliminaries you are ready to start storing data. Storage providers in fog segregate files into `directories` to make it easier to organize things. So lets create a directory so we can see that in action.
directory = Fog::Storage.directories.create(
directory = storage.directories.create(
:key => 'data'
)

View file

@ -5,6 +5,18 @@ title: Press
Mentions and blog posts from elsewhere in reverse chronological order by day (and alphasorted for same days).
**September 13th, 2011**
* [Libvirt support for fog](http://jedi.be/blog/2011/09/13/libvirt-fog-provider/)
**August 1st, 2011**
* [Using EBS Snapshots with Fog](http://www.mediamolecule.com/lab/article/using_ebs_snapshots_with_fog/)
**June 21st, 2011**
* [Mocking fog When Using It With Carrierwave](http://www.engineyard.com/blog/2011/mocking-fog-when-using-it-with-carrierwave/)
**June 14th, 2011**
* [Backing Up Your Data With Fog](http://larrywright.me/blog/articles/221-backing-up-your-data-with-fog)

View file

@ -35,7 +35,7 @@ With that in hand we are ready to start making EC2 calls!
## Servers the EC2 way
Creating a server on EC2 is very easy if you are willing to accept the defaults (the smallest server size, using Ubuntu 10.04 LTS).
Creating a server on EC2 is very easy if you are willing to accept the defaults (the smallest server size, using Ubuntu 10.04 LTS). NOTE: the default EC2 image uses the 'ubuntu' username, rather than 'root' like other services.
server = connection.servers.create
@ -81,6 +81,10 @@ Rackspace has <a href="http://www.rackspacecloud.com/cloud_hosting_products/serv
:rackspace_api_key => RACKSPACE_API_KEY
})
If you work with the European cloud from Rackspace you have to add the following:
:rackspace_auth_url => "lon.auth.api.rackspacecloud.com"
We will skip over learning how to do this the 'Rackspace Way' and instead jump right to using bootstrap to get their smallest Ubuntu 10.04 LTS server.
server = connection.servers.bootstrap

View file

@ -66,7 +66,7 @@ You can add more specifics if you need to, but reasonable defaults make it just
## No Zerigo? No Problem
If you already have an account with another service you can just as easily use this same code with different credentials. fog currently supports <a href="http://aws.amazon.com/route53/">AWS Route 53</a>, <a href="http://bluebox.net">Blue Box</a>, <a href="http://dnsimple.com">DNSimple</a>, <a href="http://www.linode.com">Linode</a>, <a href="http://www.slicehost.com">Slicehost</a> and <a href="http://www.zerigo.com/managed-dns">Zerigo</a>; so you can have your pick. As an example you can connect to AWS instead of Zerigo:
If you already have an account with another service you can just as easily use this same code with different credentials. fog currently supports <a href="http://aws.amazon.com/route53/">AWS Route 53</a>, <a href="http://bluebox.net">Blue Box</a>, <a href="http://dnsimple.com">DNSimple</a>, <a href="http://www.linode.com">Linode</a>, <a href="http://www.rackspace.com">Rackspace</a>, <a href="http://www.slicehost.com">Slicehost</a> and <a href="http://www.zerigo.com/managed-dns">Zerigo</a>; so you can have your pick. As an example you can connect to AWS instead of Zerigo:
dns = Fog::DNS.new({
:provider => 'AWS',

View file

@ -17,10 +17,10 @@ With a rapidly expanding community and codebase the advantages of fog just keep
Now type 'fog' to try stuff, confident that fog will let you know what to do. Here is an example of wading through server creation for Amazon Elastic Compute Cloud:
>> server = AWS.servers.create
>> server = Compute[:aws].servers.create
ArgumentError: image_id is required for this operation
>> server = AWS.servers.create(:image_id => 'ami-5ee70037')
>> server = Compute[:aws].servers.create(:image_id => 'ami-5ee70037')
<Fog::AWS::EC2::Server [...]>
>> server.destroy # cleanup after yourself or regret it, trust me

View file

@ -85,29 +85,29 @@ Now you've got a bunch of files in S3: your resume, some code samples,
and maybe some pictures of your cat doing funny stuff. Since this is
all of vital importance, you need to back it up.
# copy each file to local disk
directory.files.each do |s3_file|
File.open(s3_file.key, 'w') do |local_file|
local_file.write(s3_file.body)
end
end
# copy each file to local disk
directory.files.each do |s3_file|
File.open(s3_file.key, 'w') do |local_file|
local_file.write(s3_file.body)
end
end
One caveat: it's way more efficient to do this:
# do two things per file
directory.files.each do |file|
do_one_thing(file)
do_another_thing(file)
end
# do two things per file
directory.files.each do |file|
do_one_thing(file)
do_another_thing(file)
end
than it is to do this:
# do two things per file
directory.files.each do |file|
do_one_thing(file)
end.each do |file|
do_another_thing(file)
end
# do two things per file
directory.files.each do |file|
do_one_thing(file)
end.each do |file|
do_another_thing(file)
end
The reason is that the list of files might be large. Really
large. Eat-all-your-RAM-and-ask-for-more large. Therefore, every time
@ -145,6 +145,10 @@ Rackspace has <a href="http://www.rackspacecloud.com/cloud_hosting_products/file
:rackspace_api_key => RACKSPACE_API_KEY
})
If you work with the European cloud from Rackspace you have to add the following:
:rackspace_auth_url => "lon.auth.api.rackspacecloud.com"
Then create, save, destroy as per fog-for-AWS. The `:public => true` option when creating directories (see above) is important for Rackspace; your folder and files won't be shared to Rackspace's CDN and hence your users without it. Similarly the `:public =&gt; true` on files is important for AWS and Google or they will be private.
## Local Storage

View file

@ -9,9 +9,12 @@ Shindo.tests('compute examples', 'compute') do
# iterate over all the providers
Fog.providers.each do |provider|
# FIXME: implement expected shared compute stuff for these providers as well
next if ['Bluebox', 'Brightbox', 'Ecloud', 'GoGrid', 'Linode', 'NewServers', 'Ninefold', 'Slicehost', 'StormOnDemand', 'VirtualBox', 'Voxel'].include?(provider)
provider = eval(provider) # convert from string to object
# skip if provider does not have storage
# skip if provider does not have compute
next unless provider.respond_to?(:services) && provider.services.include?(:compute)
tests(provider, provider.to_s.downcase) do
@ -46,10 +49,15 @@ Shindo.tests('compute examples', 'compute') do
end
# scp a directory to a server
Dir.mkdir('/tmp/lorem')
file = ::File.new('/tmp/lorem/lorem.txt', 'w')
file.write(File.read(lorem_path))
lorem_dir = File.join([File.dirname(__FILE__), '..', 'tests'])
tests("@server.scp('#{lorem_dir}', '/tmp/lorem', :recursive => true)").succeeds do
@server.scp(lorem_dir, '/tmp/lorem', :recursive => true)
end
File.delete('/tmp/lorem/lorem.txt')
Dir.rmdir('/tmp/lorem')
# destroy the server
tests('@server.destroy').succeeds do

View file

@ -35,9 +35,9 @@ Shindo.tests('dns examples', 'dns') do
# type is the type of record to create
tests('@record = @zone.records.create').succeeds do
@record = @zone.records.create(
:ip => '1.2.3.4',
:name => 'www.fogdnsexamples.com',
:type => 'A'
:value => '1.2.3.4',
:name => 'www.fogdnsexamples.com',
:type => 'A'
)
end

View file

@ -6,14 +6,14 @@ Gem::Specification.new do |s|
## If your rubyforge_project name is different, then edit it and comment out
## the sub! line in the Rakefile
s.name = 'hpfog'
s.version = '0.0.9' # fog base 0.8.2
s.date = '2011-09-21'
s.version = '0.0.10' # fog base 1.0.0
s.date = '2011-10-17'
#s.rubyforge_project = 'fog'
## Make sure your summary is short. The description may be as long
## as you like.
s.summary = "brings clouds to you"
s.description = "The Ruby cloud services library."
s.description = "The Ruby cloud services library. Supports all major cloud providers including AWS, Rackspace, Linode, Blue Box, StormOnDemand, and many others. Full support for most AWS services including EC2, S3, CloudWatch, SimpleDB, ELB, and RDS."
## List the primary authors. If there are a bunch of authors, it's probably
## better to set the email to an email list or something. If you don't have
@ -42,12 +42,13 @@ Gem::Specification.new do |s|
## List your runtime dependencies here. Runtime dependencies are those
## that are needed for an end user to actually USE your code.
s.add_dependency('builder')
s.add_dependency('excon', '~>0.6.1')
s.add_dependency('formatador', '>=0.1.3')
s.add_dependency('json')
s.add_dependency('excon', '~>0.7.3')
s.add_dependency('formatador', '~>0.2.0')
s.add_dependency('multi_json', '~>1.0.3')
s.add_dependency('mime-types')
s.add_dependency('net-ssh', '>=2.1.3')
s.add_dependency('nokogiri', '>=1.4.4')
s.add_dependency('net-scp', '~>1.0.4')
s.add_dependency('net-ssh', '~>2.1.4')
s.add_dependency('nokogiri', '~>1.5.0')
s.add_dependency('ruby-hmac')
## List your development dependencies here. Development dependencies are
@ -55,9 +56,10 @@ Gem::Specification.new do |s|
s.add_development_dependency('jekyll')
s.add_development_dependency('rake')
s.add_development_dependency('rdoc')
s.add_development_dependency('rspec', '1.3.1')
s.add_development_dependency('shindo', '0.3.4')
s.add_development_dependency('virtualbox', '0.8.3')
s.add_development_dependency('rspec', '~>1.3.1')
s.add_development_dependency('shindo', '~>0.3.4')
s.add_development_dependency('virtualbox', '~>0.9.1')
# s.add_development_dependency('ruby-libvirt','~>0.4.0')
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec,tests}/*`.split("\n")

View file

@ -3,7 +3,7 @@ require File.join(File.dirname(__FILE__), 'fog', 'core')
module Fog
unless const_defined?(:VERSION)
VERSION = '0.8.2'
VERSION = '1.0.0'
end
end

View file

@ -1,22 +1,25 @@
require 'fog/core'
require 'fog/core/parser'
require 'openssl' # For RSA key pairs
require(File.expand_path(File.join(File.dirname(__FILE__), 'core')))
module Fog
module AWS
extend Fog::Provider
service(:cdn, 'cdn/aws')
service(:compute, 'compute/aws')
service(:cloud_formation, 'aws/cloud_formation')
service(:dns, 'dns/aws')
service(:elb, 'aws/elb')
service(:iam, 'aws/iam')
service(:rds, 'aws/rds')
service(:ses, 'aws/ses')
service(:simpledb, 'aws/simpledb')
service(:storage, 'storage/aws')
service(:auto_scaling, 'aws/auto_scaling', 'AutoScaling')
service(:cdn, 'aws/cdn', 'CDN')
service(:compute, 'aws/compute', 'Compute')
service(:cloud_formation, 'aws/cloud_formation', 'CloudFormation')
service(:cloud_watch, 'aws/cloud_watch', 'CloudWatch')
service(:dns, 'aws/dns', 'DNS')
service(:elasticache, 'aws/elasticache', 'Elasticache')
service(:elb, 'aws/elb', 'ELB')
service(:iam, 'aws/iam', 'IAM')
service(:rds, 'aws/rds', 'RDS')
service(:ses, 'aws/ses', 'SES')
service(:simpledb, 'aws/simpledb', 'SimpleDB')
service(:sns, 'aws/sns', 'SNS')
service(:sqs, 'aws/sqs', 'SQS')
service(:storage, 'aws/storage', 'Storage')
def self.indexed_param(key, values)
params = {}
@ -43,7 +46,9 @@ module Fog
end
def self.escape(string)
string.gsub( /([^-a-zA-Z0-9_.~]+)/n ) { |match| '%' + match.unpack( 'H2' * match.size ).join( '%' ).upcase }
string.gsub(/([^a-zA-Z0-9_.\-~]+)/) {
"%" + $1.unpack("H2" * $1.bytesize).join("%").upcase
}
end
def self.signed_params(params, options = {})
@ -70,6 +75,10 @@ module Fog
class Mock
def self.arn(vendor, account_id, path, region = nil)
"arn:aws:#{vendor}:#{region}:#{account_id}:#{path}"
end
def self.availability_zone(region)
"#{region}#{Fog::Mock.random_selection('abcd', 1)}"
end
@ -78,6 +87,11 @@ module Fog
sprintf("%0.10f", rand / 100).to_f
end
def self.console_output
# "[ 0.000000] Linux version 2.6.18-xenU-ec2-v1.2 (root@domU-12-31-39-07-51-82) (gcc version 4.1.2 20070626 (Red Hat 4.1.2-13)) #2 SMP Wed Aug 19 09:04:38 EDT 2009"
Base64.decode64("WyAwLjAwMDAwMF0gTGludXggdmVyc2lvbiAyLjYuMTgteGVuVS1lYzItdjEu\nMiAocm9vdEBkb21VLTEyLTMxLTM5LTA3LTUxLTgyKSAoZ2NjIHZlcnNpb24g\nNC4xLjIgMjAwNzA2MjYgKFJlZCBIYXQgNC4xLjItMTMpKSAjMiBTTVAgV2Vk\nIEF1ZyAxOSAwOTowNDozOCBFRFQgMjAwOQ==\n")
end
def self.dns_name_for(ip_address)
"ec2-#{ip_address.gsub('.','-')}.compute-1.amazonaws.com"
end
@ -161,6 +175,12 @@ module Fog
request_id << Fog::Mock.random_hex(12)
request_id.join('-')
end
class << self
alias :reserved_instances_id :request_id
alias :reserved_instances_offering_id :request_id
alias :sqs_message_id :request_id
alias :sqs_sender_id :request_id
end
def self.reservation_id
"r-#{Fog::Mock.random_hex(8)}"
@ -173,7 +193,6 @@ module Fog
def self.volume_id
"vol-#{Fog::Mock.random_hex(8)}"
end
end
end
end

225
lib/fog/aws/auto_scaling.rb Normal file
View file

@ -0,0 +1,225 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
module Fog
module AWS
class AutoScaling < Fog::Service
class IdentifierTaken < Fog::Errors::Error; end
class ResourceInUse < Fog::Errors::Error; end
class ValidationError < Fog::Errors::Error; end
requires :aws_access_key_id, :aws_secret_access_key
recognizes :host, :path, :port, :scheme, :persistent, :region
request_path 'fog/aws/requests/auto_scaling'
request :create_auto_scaling_group
request :create_launch_configuration
request :delete_auto_scaling_group
request :delete_launch_configuration
request :delete_policy
request :delete_scheduled_action
request :describe_adjustment_types
request :describe_auto_scaling_groups
request :describe_auto_scaling_instances
request :describe_launch_configurations
request :describe_metric_collection_types
request :describe_policies
request :describe_scaling_activities
request :describe_scaling_process_types
request :describe_scheduled_actions
request :disable_metrics_collection
request :enable_metrics_collection
request :execute_policy
request :put_scaling_policy
request :put_scheduled_update_group_action
request :resume_processes
request :set_desired_capacity
request :set_instance_health
request :suspend_processes
request :terminate_instance_in_auto_scaling_group
request :update_auto_scaling_group
model_path 'fog/aws/models/auto_scaling'
model :activity
collection :activities
model :configuration
collection :configurations
model :group
collection :groups
model :instance
collection :instances
class Real
# Initialize connection to AutoScaling
#
# ==== Notes
# options parameter must include values for :aws_access_key_id and
# :aws_secret_access_key in order to create a connection
#
# ==== Examples
# as = AutoScaling.new(
# :aws_access_key_id => your_aws_access_key_id,
# :aws_secret_access_key => your_aws_secret_access_key
# )
#
# ==== Parameters
# * options<~Hash> - config arguments for connection. Defaults to {}.
#
# ==== Returns
# * AutoScaling object with connection to AWS.
def initialize(options={})
require 'fog/core/parser'
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
@connection_options = options[:connection_options] || {}
options[:region] ||= 'us-east-1'
@host = options[:host] || case options[:region]
when 'ap-northeast-1'
'autoscaling.ap-northeast-1.amazonaws.com'
when 'ap-southeast-1'
'autoscaling.ap-southeast-1.amazonaws.com'
when 'eu-west-1'
'autoscaling.eu-west-1.amazonaws.com'
when 'us-east-1'
'autoscaling.us-east-1.amazonaws.com'
when 'us-west-1'
'autoscaling.us-west-1.amazonaws.com'
else
raise ArgumentError, "Unknown region: #{options[:region].inspect}"
end
@path = options[:path] || '/'
@port = options[:port] || 443
@persistent = options[:persistent] || false
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload
@connection.reset
end
private
def request(params)
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body = AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,
:hmac => @hmac,
:host => @host,
:path => @path,
:port => @port,
:version => '2010-08-01'
}
)
begin
response = @connection.request({
:body => body,
:expects => 200,
:idempotent => idempotent,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:host => @host,
:method => 'POST',
:parser => parser
})
rescue Excon::Errors::HTTPStatusError => error
if match = error.message.match(/<Code>(.*)<\/Code>.*<Message>(.*)<\/Message>/)
case match[1]
when 'AlreadyExists'
#raise Fog::AWS::AutoScaling::IdentifierTaken.new(match[2])
raise Fog::AWS::AutoScaling::IdentifierTaken.slurp(error, match[2])
when 'ResourceInUse'
raise Fog::AWS::AutoScaling::ResourceInUse.slurp(error, match[2])
when 'ValidationError'
raise Fog::AWS::AutoScaling::ValidationError.slurp(error, match[2])
else
raise Fog::Compute::AWS::Error.slurp(error, "#{match[1]} => #{match[2]}")
end
else
raise
end
end
response
end
end
class Mock
def self.data
@data ||= Hash.new do |hash, region|
owner_id = Fog::AWS::Mock.owner_id
hash[region] = Hash.new do |region_hash, key|
region_hash[key] = {
:adjustment_types => [
'ChangeInCapacity',
'ExactCapacity',
'PercentChangeInCapacity'
],
:auto_scaling_groups => {},
:health_states => ['Healthy', 'Unhealthy'],
:launch_configurations => {},
:metric_collection_types => {
:granularities => [ '1Minute' ],
:metrics => [
'GroupMinSize',
'GroupMaxSize',
'GroupDesiredCapacity',
'GroupInServiceInstances',
'GroupPendingInstances',
'GroupTerminatingInstances',
'GroupTotalInstances'
],
},
:process_types => [
'AZRebalance',
'AlarmNotification',
'HealthCheck',
'Launch',
'ReplaceUnhealthy',
'ScheduledActions',
'Terminate'
]
}
end
end
end
def self.reset
@data = nil
end
def initialize(options={})
@aws_access_key_id = options[:aws_access_key_id]
@region = options[:region] || 'us-east-1'
unless ['ap-northeast-1', 'ap-southeast-1', 'eu-west-1', 'us-east-1', 'us-west-1'].include?(@region)
raise ArgumentError, "Unknown region: #{@region.inspect}"
end
end
def data
self.class.data[@region][@aws_access_key_id]
end
def reset_data
self.class.data[@region].delete(@aws_access_key_id)
end
end
end
end
end

View file

@ -1,20 +1,28 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
require 'fog/cdn'
module Fog
module AWS
class CDN < Fog::Service
module CDN
class AWS < Fog::Service
requires :aws_access_key_id, :aws_secret_access_key
recognizes :host, :path, :port, :scheme, :version, :persistent
recognizes :provider # remove post deprecation
model_path 'fog/cdn/models/aws'
model_path 'fog/aws/cdn/models'
request_path 'fog/cdn/requests/aws'
request_path 'fog/aws/requests/cdn'
request 'delete_distribution'
request 'delete_streaming_distribution'
request 'get_distribution'
request 'get_distribution_list'
request 'get_invalidation_list'
request 'get_streaming_distribution'
request 'get_streaming_distribution_list'
request 'post_distribution'
request 'post_streaming_distribution'
request 'post_invalidation'
request 'put_distribution_config'
request 'put_streaming_distribution_config'
class Mock
@ -33,13 +41,6 @@ module Fog
end
def initialize(options={})
unless options.delete(:provider)
location = caller.first
warning = "[yellow][WARN] Fog::AWS::CDN.new is deprecated, use Fog::CDN.new(:provider => 'AWS') instead[/]"
warning << " [light_black](" << location << ")[/] "
Formatador.display_line(warning)
end
require 'mime/types'
@aws_access_key_id = options[:aws_access_key_id]
@region = options[:region]
@ -79,27 +80,19 @@ module Fog
# ==== Returns
# * cdn object with connection to aws.
def initialize(options={})
unless options.delete(:provider)
location = caller.first
warning = "[yellow][WARN] Fog::AWS::CDN.new is deprecated, use Fog::CDN.new(:provider => 'AWS') instead[/]"
warning << " [light_black](" << location << ")[/] "
Formatador.display_line(warning)
end
require 'fog/core/parser'
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@hmac = Fog::HMAC.new('sha1', @aws_secret_access_key)
@host = options[:host] || 'cloudfront.amazonaws.com'
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@version = options[:version] || '2010-11-01'
unless options.has_key?(:persistent)
options[:persistent] = true
end
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent])
@connection_options = options[:connection_options] || {}
@hmac = Fog::HMAC.new('sha1', @aws_secret_access_key)
@host = options[:host] || 'cloudfront.amazonaws.com'
@path = options[:path] || '/'
@persistent = options[:persistent] || true
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@version = options[:version] || '2010-11-01'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload

View file

@ -1,3 +1,5 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
module Fog
module AWS
class CloudFormation < Fog::Service
@ -43,12 +45,13 @@ module Fog
# * CloudFormation object with connection to AWS.
def initialize(options={})
require 'fog/core/parser'
require 'json'
require 'multi_json'
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
@connection_options = options[:connection_options] || {}
options[:region] ||= 'us-east-1'
@host = options[:host] || case options[:region]
when 'ap-northeast-1'
@ -64,10 +67,11 @@ module Fog
else
raise ArgumentError, "Unknown region: #{options[:region].inspect}"
end
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent])
@path = options[:path] || '/'
@persistent = options[:persistent] || false
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload
@ -80,7 +84,7 @@ module Fog
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body = AWS.signed_params(
body = Fog::AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,

114
lib/fog/aws/cloud_watch.rb Normal file
View file

@ -0,0 +1,114 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
module Fog
module AWS
class CloudWatch < Fog::Service
requires :aws_access_key_id, :aws_secret_access_key
recognizes :region, :host, :path, :port, :scheme, :persistent
request_path 'fog/aws/requests/cloud_watch'
request :list_metrics
request :get_metric_statistics
request :put_metric_data
model_path 'fog/aws/models/cloud_watch'
model :metric
collection :metrics
model :metric_statistic
collection :metric_statistics
class Mock
def initialize(options={})
end
end
class Real
# Initialize connection to Cloudwatch
#
# ==== Notes
# options parameter must include values for :aws_access_key_id and
# :aws_secret_access_key in order to create a connection
#
# ==== Examples
# elb = CloudWatch.new(
# :aws_access_key_id => your_aws_access_key_id,
# :aws_secret_access_key => your_aws_secret_access_key
# )
#
# ==== Parameters
# * options<~Hash> - config arguments for connection. Defaults to {}.
# * region<~String> - optional region to use, in ['eu-west-1', 'us-east-1', 'us-west-1', 'ap-southeast-1', 'ap-northeast-1']
#
# ==== Returns
# * CloudWatch object with connection to AWS.
def initialize(options={})
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
@connection_options = options[:connection_options] || {}
options[:region] ||= 'us-east-1'
@host = options[:host] || case options[:region]
when 'ap-northeast-1'
'monitoring.ap-northeast-1.amazonaws.com'
when 'ap-southeast-1'
'monitoring.ap-southeast-1.amazonaws.com'
when 'eu-west-1'
'monitoring.eu-west-1.amazonaws.com'
when 'us-east-1'
'monitoring.us-east-1.amazonaws.com'
when 'us-west-1'
'monitoring.us-west-1.amazonaws.com'
else
raise ArgumentError, "Unknown region: #{options[:region].inspect}"
end
@path = options[:path] || '/'
@persistent = options[:persistent] || false
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload
@connection.reset
end
private
def request(params)
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body = AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,
:hmac => @hmac,
:host => @host,
:path => @path,
:port => @port,
:version => '2010-08-01'
}
)
response = @connection.request({
:body => body,
:expects => 200,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:idempotent => idempotent,
:host => @host,
:method => 'POST',
:parser => parser
})
end
end
end
end
end

View file

@ -1,12 +1,14 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
require 'fog/compute'
module Fog
module AWS
class Compute < Fog::Service
module Compute
class AWS < Fog::Service
requires :aws_access_key_id, :aws_secret_access_key
recognizes :endpoint, :region, :host, :path, :port, :scheme, :persistent
recognizes :provider # remove post deprecation
model_path 'fog/compute/models/aws'
model_path 'fog/aws/models/compute'
model :address
collection :addresses
model :flavor
@ -25,21 +27,28 @@ module Fog
collection :tags
model :volume
collection :volumes
model :spot_request
collection :spot_requests
request_path 'fog/compute/requests/aws'
request_path 'fog/aws/requests/compute'
request :allocate_address
request :associate_address
request :attach_volume
request :authorize_security_group_ingress
request :cancel_spot_instance_requests
request :create_image
request :create_key_pair
request :create_placement_group
request :create_security_group
request :create_snapshot
request :create_spot_datafeed_subscription
request :create_tags
request :create_volume
request :delete_key_pair
request :delete_security_group
request :delete_placement_group
request :delete_snapshot
request :delete_spot_datafeed_subscription
request :delete_tags
request :delete_volume
request :deregister_image
@ -49,10 +58,14 @@ module Fog
request :describe_instances
request :describe_reserved_instances
request :describe_key_pairs
request :describe_placement_groups
request :describe_regions
request :describe_reserved_instances_offerings
request :describe_security_groups
request :describe_snapshots
request :describe_spot_datafeed_subscription
request :describe_spot_instance_requests
request :describe_spot_price_history
request :describe_tags
request :describe_volumes
request :detach_volume
@ -60,11 +73,14 @@ module Fog
request :get_console_output
request :get_password_data
request :import_key_pair
request :modify_image_attributes
request :modify_image_attribute
request :modify_instance_attribute
request :modify_snapshot_attribute
request :purchase_reserved_instances_offering
request :reboot_instances
request :release_address
request :register_image
request :request_spot_instances
request :revoke_security_group_ingress
request :run_instances
request :terminate_instances
@ -73,6 +89,16 @@ module Fog
request :monitor_instances
request :unmonitor_instances
# deprecation
class Real
def modify_image_attributes(*params)
Fog::Logger.warning("modify_image_attributes is deprecated, use modify_image_attribute instead [light_black](#{caller.first})[/]")
modify_image_attribute(*params)
end
end
class Mock
def self.data
@ -84,14 +110,16 @@ module Fog
:addresses => {},
:images => {},
:instances => {},
:reserved_instances => {},
:key_pairs => {},
:limits => { :addresses => 5 },
:owner_id => owner_id,
:security_groups => {
'default' => {
'groupDescription' => 'default group',
'groupName' => 'default',
'ipPermissions' => [
'groupDescription' => 'default group',
'groupName' => 'default',
'ipPermissionsEgress' => [],
'ipPermissions' => [
{
'groups' => [{'groupName' => 'default', 'userId' => owner_id}],
'fromPort' => -1,
@ -114,7 +142,7 @@ module Fog
'ipRanges' => []
}
],
'ownerId' => owner_id
'ownerId' => owner_id
}
},
:snapshots => {},
@ -130,15 +158,6 @@ module Fog
end
def initialize(options={})
unless options.delete(:provider)
location = caller.first
warning = "[yellow][WARN] Fog::AWS::Compute.new is deprecated, use Fog::Compute.new(:provider => 'AWS') instead[/]"
warning << " [light_black](" << location << ")[/] "
Formatador.display_line(warning)
end
require 'fog/compute/parsers/aws/basic'
@aws_access_key_id = options[:aws_access_key_id]
@region = options[:region] || 'us-east-1'
@ -204,19 +223,13 @@ module Fog
# ==== Returns
# * EC2 object with connection to aws.
def initialize(options={})
unless options.delete(:provider)
location = caller.first
warning = "[yellow][WARN] Fog::AWS::Compute.new is deprecated, use Fog::Compute.new(:provider => 'AWS') instead[/]"
warning << " [light_black](" << location << ")[/] "
Formatador.display_line(warning)
end
require 'fog/core/parser'
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
@region = options[:region] ||= 'us-east-1'
@connection_options = options[:connection_options] || {}
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
@region = options[:region] ||= 'us-east-1'
if @endpoint = options[:endpoint]
endpoint = URI.parse(@endpoint)
@ -239,11 +252,12 @@ module Fog
else
raise ArgumentError, "Unknown region: #{options[:region].inspect}"
end
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@path = options[:path] || '/'
@persistent = options[:persistent] || false
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
end
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent])
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload
@ -256,7 +270,7 @@ module Fog
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body = AWS.signed_params(
body = Fog::AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,
@ -264,7 +278,7 @@ module Fog
:host => @host,
:path => @path,
:port => @port,
:version => '2010-08-31'
:version => '2011-05-15'
}
)
@ -281,10 +295,10 @@ module Fog
rescue Excon::Errors::HTTPStatusError => error
if match = error.message.match(/<Code>(.*)<\/Code><Message>(.*)<\/Message>/)
raise case match[1].split('.').last
when 'NotFound'
Fog::AWS::Compute::NotFound.slurp(error, match[2])
when 'NotFound', 'Unknown'
Fog::Compute::AWS::NotFound.slurp(error, match[2])
else
Fog::AWS::Compute::Error.slurp(error, "#{match[1]} => #{match[2]}")
Fog::Compute::AWS::Error.slurp(error, "#{match[1]} => #{match[2]}")
end
else
raise error

View file

@ -1,18 +1,20 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
require 'fog/dns'
module Fog
module AWS
class DNS < Fog::Service
module DNS
class AWS < Fog::Service
requires :aws_access_key_id, :aws_secret_access_key
recognizes :host, :path, :port, :scheme, :version, :persistent
recognizes :provider # remove post deprecation
model_path 'fog/dns/models/aws'
model_path 'fog/aws/models/dns'
model :record
collection :records
model :zone
collection :zones
request_path 'fog/dns/requests/aws'
request_path 'fog/aws/requests/dns'
request :create_hosted_zone
request :get_hosted_zone
request :delete_hosted_zone
@ -38,13 +40,6 @@ module Fog
end
def initialize(options={})
unless options.delete(:provider)
location = caller.first
warning = "[yellow][WARN] Fog::AWS::DNS.new is deprecated, use Fog::DNS.new(:provider => 'AWS') instead[/]"
warning << " [light_black](" << location << ")[/] "
Formatador.display_line(warning)
end
require 'mime/types'
@aws_access_key_id = options[:aws_access_key_id]
@region = options[:region]
@ -83,27 +78,20 @@ module Fog
# ==== Returns
# * dns object with connection to aws.
def initialize(options={})
unless options.delete(:provider)
location = caller.first
warning = "[yellow][WARN] Fog::AWS::DNS.new is deprecated, use Fog::DNS.new(:provider => 'DNS') instead[/]"
warning << " [light_black](" << location << ")[/] "
Formatador.display_line(warning)
end
require 'fog/core/parser'
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@hmac = Fog::HMAC.new('sha1', @aws_secret_access_key)
@host = options[:host] || 'route53.amazonaws.com'
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@version = options[:version] || '2010-10-01'
unless options.has_key?(:persistent)
options[:persistent] = true
end
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent])
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@connection_options = options[:connection_options] || {}
@hmac = Fog::HMAC.new('sha1', @aws_secret_access_key)
@host = options[:host] || 'route53.amazonaws.com'
@path = options[:path] || '/'
@persistent = options[:persistent] || true
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@version = options[:version] || '2010-10-01'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload

127
lib/fog/aws/elasticache.rb Normal file
View file

@ -0,0 +1,127 @@
module Fog
module AWS
class Elasticache < Fog::Service
class IdentifierTaken < Fog::Errors::Error; end
class InvalidInstance < Fog::Errors::Error; end
requires :aws_access_key_id, :aws_secret_access_key
recognizes :region, :host, :path, :port, :scheme, :persistent
request_path 'fog/aws/requests/elasticache'
request :create_cache_cluster
request :delete_cache_cluster
request :describe_cache_clusters
request :modify_cache_cluster
request :reboot_cache_cluster
request :create_cache_parameter_group
request :delete_cache_parameter_group
request :describe_cache_parameter_groups
request :modify_cache_parameter_group
request :reset_cache_parameter_group
request :describe_engine_default_parameters
request :describe_cache_parameters
request :create_cache_security_group
request :delete_cache_security_group
request :describe_cache_security_groups
request :authorize_cache_security_group_ingress
request :revoke_cache_security_group_ingress
request :describe_events
model_path 'fog/aws/models/elasticache'
model :cluster
collection :clusters
model :security_group
collection :security_groups
model :parameter_group
collection :parameter_groups
class Mock
def initalize(options={})
Fog::Mock.not_implemented
end
end
class Real
def initialize(options={})
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
options[:region] ||= 'us-east-1'
@host = options[:host] || case options[:region]
when 'us-east-1'
'elasticache.us-east-1.amazonaws.com'
#TODO: Support other regions
else
raise ArgumentError, "Unknown region: #{options[:region].inspect}"
end
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new(
"#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent]
)
end
def reload
@connection.reset
end
private
def request(params)
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body = Fog::AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,
:hmac => @hmac,
:host => @host,
:path => @path,
:port => @port,
:version => '2011-07-15'
}
)
begin
response = @connection.request({
:body => body,
:expects => 200,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:idempotent => idempotent,
:host => @host,
:method => 'POST',
:parser => parser
})
rescue Excon::Errors::HTTPStatusError => error
if match = error.message.match(/<Code>(.*)<\/Code>/m)
case match[1]
when 'CacheSecurityGroupNotFound', 'CacheParameterGroupNotFound',
'CacheClusterNotFound'
raise Fog::AWS::Elasticache::NotFound
when 'CacheSecurityGroupAlreadyExists'
raise Fog::AWS::Elasticache::IdentifierTaken
when 'InvalidParameterValue'
raise Fog::AWS::Elasticache::InvalidInstance
else
raise
end
else
raise
end
end
response
end
end
end
end
end

View file

@ -1,9 +1,12 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
module Fog
module AWS
class ELB < Fog::Service
class IdentifierTaken < Fog::Errors::Error; end
class InvalidInstance < Fog::Errors::Error; end
class Throttled < Fog::Errors::Error; end
requires :aws_access_key_id, :aws_secret_access_key
recognizes :region, :host, :path, :port, :scheme, :persistent
@ -23,7 +26,7 @@ module Fog
request :disable_availability_zones_for_load_balancer
request :enable_availability_zones_for_load_balancer
request :register_instances_with_load_balancer
#request :set_load_balancer_listener_ssl_certificate
request :set_load_balancer_listener_ssl_certificate
request :set_load_balancer_policies_of_listener
model_path 'fog/aws/models/elb'
@ -36,10 +39,43 @@ module Fog
class Mock
def initialize(options={})
Fog::Mock.not_implemented
def self.data
@data ||= Hash.new do |hash, region|
owner_id = Fog::AWS::Mock.owner_id
hash[region] = Hash.new do |region_hash, key|
region_hash[key] = {
:owner_id => owner_id,
:load_balancers => {}
}
end
end
end
def self.dns_name(name, region)
"#{name}-#{Fog::Mock.random_hex(8)}.#{region}.elb.amazonaws.com"
end
def self.reset
@data = nil
end
def initialize(options={})
@aws_access_key_id = options[:aws_access_key_id]
@region = options[:region] || 'us-east-1'
unless ['ap-northeast-1', 'ap-southeast-1', 'eu-west-1', 'us-east-1', 'us-west-1'].include?(@region)
raise ArgumentError, "Unknown region: #{@region.inspect}"
end
end
def data
self.class.data[@region][@aws_access_key_id]
end
def reset_data
self.class.data[@region].delete(@aws_access_key_id)
end
end
class Real
@ -67,6 +103,7 @@ module Fog
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@connection_options = options[:connection_options] || {}
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
options[:region] ||= 'us-east-1'
@ -84,10 +121,11 @@ module Fog
else
raise ArgumentError, "Unknown region: #{options[:region].inspect}"
end
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent])
@path = options[:path] || '/'
@persistent = options[:persistent] || false
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload
@ -100,7 +138,7 @@ module Fog
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body = AWS.signed_params(
body = Fog::AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,
@ -111,34 +149,35 @@ module Fog
:version => '2011-04-05'
}
)
begin
response = @connection.request({
:body => body,
:expects => 200,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:idempotent => idempotent,
:host => @host,
:method => 'POST',
:parser => parser
})
rescue Excon::Errors::HTTPStatusError => error
if match = error.message.match(/<Code>(.*)<\/Code>/m)
case match[1]
when 'LoadBalancerNotFound'
raise Fog::AWS::ELB::NotFound
when 'DuplicateLoadBalancerName'
raise Fog::AWS::ELB::IdentifierTaken
when 'InvalidInstance'
raise Fog::AWS::ELB::InvalidInstance
else
raise
end
response = @connection.request({
:body => body,
:expects => 200,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:idempotent => idempotent,
:host => @host,
:method => 'POST',
:parser => parser
})
rescue Excon::Errors::HTTPStatusError => error
if match = error.message.match(/<Code>(.*)<\/Code>(?:.*<Message>(.*)<\/Message>)?/m)
case match[1]
when 'CertificateNotFound'
raise Fog::AWS::IAM::NotFound.slurp(error, match[2])
when 'LoadBalancerNotFound'
raise Fog::AWS::ELB::NotFound.slurp(error, match[2])
when 'DuplicateLoadBalancerName'
raise Fog::AWS::ELB::IdentifierTaken.slurp(error, match[2])
when 'InvalidInstance'
raise Fog::AWS::ELB::InvalidInstance.slurp(error, match[2])
when 'Throttling'
raise Fog::AWS::ELB::Throttled.slurp(error, match[2])
else
raise
end
else
raise
end
response
end
end
end

View file

@ -1,17 +1,27 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'aws'))
module Fog
module AWS
class IAM < Fog::Service
class EntityAlreadyExists < Fog::AWS::IAM::Error; end
class KeyPairMismatch < Fog::AWS::IAM::Error; end
class LimitExceeded < Fog::AWS::IAM::Error; end
class MalformedCertificate < Fog::AWS::IAM::Error; end
class ValidationError < Fog::AWS::IAM::Error; end
requires :aws_access_key_id, :aws_secret_access_key
recognizes :host, :path, :port, :scheme, :persistent
request_path 'fog/aws/requests/iam'
request :add_user_to_group
request :create_access_key
request :create_account_alias
request :create_group
request :create_user
request :create_login_profile
request :create_user
request :delete_access_key
request :delete_account_alias
request :delete_group
request :delete_group_policy
request :delete_login_profile
@ -19,14 +29,17 @@ module Fog
request :delete_signing_certificate
request :delete_user
request :delete_user_policy
request :get_group
request :get_group_policy
request :get_login_profile
request :get_server_certificate
request :get_user
request :get_user_policy
request :get_group
request :list_access_keys
request :list_account_aliases
request :list_group_policies
request :list_groups
request :list_groups_for_user
request :list_group_policies
request :list_server_certificates
request :list_signing_certificates
request :list_user_policies
@ -37,17 +50,41 @@ module Fog
request :update_access_key
request :update_group
request :update_login_profile
request :update_user
request :update_server_certificate
request :update_signing_certificate
request :update_user
request :upload_server_certificate
request :upload_signing_certificate
class Mock
def initialize(options={})
Fog::Mock.not_implemented
def self.data
@data ||= Hash.new do |hash, key|
hash[key] = {
:owner_id => Fog::AWS::Mock.owner_id,
:server_certificates => {}
}
end
end
def self.reset
@data = nil
end
def self.server_certificate_id
Fog::Mock.random_hex(16)
end
def initialize(options={})
@aws_access_key_id = options[:aws_access_key_id]
end
def data
self.class.data[@aws_access_key_id]
end
def reset_data
self.class.data.delete(@aws_access_key_id)
end
end
class Real
@ -71,16 +108,18 @@ module Fog
# * IAM object with connection to AWS.
def initialize(options={})
require 'fog/core/parser'
require 'json'
require 'multi_json'
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@connection_options = options[:connection_options] || {}
@hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
@host = options[:host] || 'iam.amazonaws.com'
@path = options[:path] || '/'
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent])
@host = options[:host] || 'iam.amazonaws.com'
@path = options[:path] || '/'
@persistent = options[:persistent] || false
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end
def reload
@ -93,7 +132,7 @@ module Fog
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body = AWS.signed_params(
body = Fog::AWS.signed_params(
params,
{
:aws_access_key_id => @aws_access_key_id,
@ -105,17 +144,35 @@ module Fog
}
)
response = @connection.request({
:body => body,
:expects => 200,
:idempotent => idempotent,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:host => @host,
:method => 'POST',
:parser => parser
})
begin
response = @connection.request({
:body => body,
:expects => 200,
:idempotent => idempotent,
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:host => @host,
:method => 'POST',
:parser => parser
})
response
rescue Excon::Errors::HTTPStatusError => error
if match = error.message.match(/<Code>(.*)<\/Code>(?:.*<Message>(.*)<\/Message>)?/m)
case match[1]
when 'CertificateNotFound', 'NoSuchEntity'
raise Fog::AWS::IAM::NotFound.slurp(error, match[2])
when 'EntityAlreadyExists', 'KeyPairMismatch', 'LimitExceeded', 'MalformedCertificate', 'ValidationError'
raise Fog::AWS::IAM.const_get(match[1]).slurp(error, match[2])
else
raise Fog::AWS::IAM::Error.slurp(error, "#{match[1]} => #{match[2]}") if match[1]
raise
end
else
raise
end
end
response
end
end

View file

@ -0,0 +1,30 @@
require 'fog/aws/models/auto_scaling/activity'
module Fog
module AWS
class AutoScaling
class Activities < Fog::Collection
model Fog::AWS::AutoScaling::Activity
def all
data = []
next_token = nil
loop do
result = connection.describe_scaling_activities('NextToken' => next_token).body['DescribeScalingActivitiesResult']
data += result['Activities']
next_token = result['NextToken']
break if next_token.nil?
end
load(data)
end
def get(identity)
data = connection.describe_scaling_activities('ActivityId' => identity).body['DescribeScalingActivitiesResult']['Activities'].first
new(data) unless data.nil?
end
end
end
end
end

View file

@ -0,0 +1,29 @@
require 'fog/core/model'
module Fog
module AWS
class AutoScaling
class Activity < Fog::Model
identity :id, :aliases => 'ActivityId'
attribute :auto_scaling_group_name, :aliases => 'AutoScalingGroupName'
attribute :cause, :aliases => 'Cause'
attribute :description, :aliases => 'Description'
attribute :end_time, :aliases => 'EndTime'
attribute :progress, :aliases => 'Progress'
attribute :start_time, :aliases => 'StartTime'
attribute :status_code, :aliases => 'StatusCode'
attribute :status_message, :aliases => 'StatusMessage'
def group
connection.groups.get(attributes['AutoScalingGroupName'])
end
def save
raise "Operation not supported"
end
end
end
end
end

View file

@ -0,0 +1,63 @@
require 'fog/core/model'
module Fog
module AWS
class AutoScaling
class Configuration < Fog::Model
identity :id, :aliases => 'LaunchConfigurationName'
attribute :arn, :aliases => 'LaunchConfigurationARN'
attribute :block_device_mappings, :aliases => 'BlockDeviceMappings'
attribute :created_at, :aliases => 'CreatedTime'
attribute :image_id, :aliases => 'ImageId'
#attribute :instance_monitoring, :aliases => 'InstanceMonitoring'
attribute :instance_monitoring, :aliases => 'InstanceMonitoring', :squash => 'Enabled'
attribute :instance_type, :aliases => 'InstanceType'
attribute :kernel_id, :aliases => 'KernelId'
attribute :key_name, :aliases => 'KeyName'
attribute :ramdisk_id, :aliases => 'RamdiskId'
attribute :security_groups, :aliases => 'SecurityGroups'
attribute :user_data, :aliases => 'UserData'
def initialize(attributes={})
#attributes[:availability_zones] ||= %w(us-east-1a us-east-1b us-east-1c us-east-1d)
#attributes['ListenerDescriptions'] ||= [{
# 'Listener' => {'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'http'},
# 'PolicyNames' => []
#}]
#attributes['Policies'] ||= {'AppCookieStickinessPolicies' => [], 'LBCookieStickinessPolicies' => []}
super
end
def ready?
# AutoScaling requests are synchronous
true
end
def save
requires :id
requires :image_id
requires :instance_type
connection.create_launch_configuration(image_id, instance_type, id) #, listeners.map{|l| l.to_params})
# reload instead of merge attributes b/c some attrs (like HealthCheck)
# may be set, but only the DNS name is returned in the create_load_balance
# API call
reload
end
def reload
super
self
end
def destroy
requires :id
connection.delete_launch_configuration(id)
end
end
end
end
end

View file

@ -0,0 +1,35 @@
require 'fog/aws/models/auto_scaling/configuration'
module Fog
module AWS
class AutoScaling
class Configurations < Fog::Collection
model Fog::AWS::AutoScaling::Configuration
# Creates a new launch configuration
def initialize(attributes={})
super
end
def all
data = []
next_token = nil
loop do
result = connection.describe_launch_configurations('NextToken' => next_token).body['DescribeLaunchConfigurationsResult']
data += result['LaunchConfigurations']
next_token = result['NextToken']
break if next_token.nil?
end
load(data)
end
def get(identity)
data = connection.describe_launch_configurations('LaunchConfigurationNames' => identity).body['DescribeLaunchConfigurationsResult']['LaunchConfigurations'].first
new(data) unless data.nil?
end
end
end
end
end

View file

@ -0,0 +1,140 @@
require 'fog/core/model'
module Fog
module AWS
class AutoScaling
class Group < Fog::Model
identity :id, :aliases => 'AutoScalingGroupName'
attribute :arn, :aliases => 'AutoScalingGroupARN'
attribute :availability_zones, :aliases => 'AvailabilityZones'
attribute :created_at, :aliases => 'CreatedTime'
attribute :default_cooldown, :aliases => 'DefaultCooldown'
attribute :desired_capacity, :aliases => 'DesiredCapacity'
attribute :enabled_metrics, :aliases => 'EnabledMetrics'
attribute :health_check_grace_period, :aliases => 'HealthCheckGracePeriod'
attribute :health_check_type, :aliases => 'HealthCheckType'
attribute :instances, :aliases => 'Instances'
attribute :launch_configuration_name, :aliases => 'LaunchConfigurationName'
attribute :load_balancer_names, :aliases => 'LoadBalancerNames'
attribute :max_size, :aliases => 'MaxSize'
attribute :min_size, :aliases => 'MinSize'
attribute :placement_group, :aliases => 'PlacementGroup'
attribute :suspended_processes, :aliases => 'SuspendedProcesses'
attribute :vpc_zone_identifier, :aliases => 'VPCZoneIdentifier'
def initialize(attributes={})
attributes['DefaultCooldown'] ||= 0
attributes['DesiredCapacity'] ||= 0
attributes['EnabledMetrics'] ||= []
attributes['HealthCheckGracePeriod'] ||= 0
attributes['HealthCheckType'] ||= 'EC2'
attributes['Instances'] ||= []
attributes['LoadBalancerNames'] ||= []
attributes['MaxSize'] ||= 0
attributes['MinSize'] ||= 0
attributes['SuspendedProcesses'] ||= []
super
end
def activities
requires :id
data = []
next_token = nil
loop do
result = connection.describe_scaling_activities('AutoScalingGroupName' => id, 'NextToken' => next_token).body['DescribeScalingActivitiesResult']
data += result['Activities']
next_token = result['NextToken']
break if next_token.nil?
end
Fog::AWS::AutoScaling::Activities.new({
:data => data,
:connection => connection,
#:load_balancer => self
})
end
def configuration
requires :launch_configuration_name
connection.configurations.get(launch_configuration_name)
end
def disable_metrics_collection(metrics = {})
requires :id
connection.disable_metrics_collection(id, 'Metrics' => metrics)
reload
end
def enable_metrics_collection(metrics = {})
requires :id
connection.enable_metrics_collection(id, 'Metrics' => metrics)
reload
end
def instances
Fog::AWS::AutoScaling::Instances.new({
:data => attributes['Instances'],
:connection => connection
})
end
def instances_in_service
attributes[:instances].select {|hash| hash['LifecycleState'] == 'InService'}.map {|hash| hash['InstanceId']}
end
def instances_out_service
attributes[:instances].select {|hash| hash['LifecycleState'] == 'OutOfService'}.map {|hash| hash['InstanceId']}
end
def resume_processes(processes = [])
requires :id
connection.resume_processes(id, 'ScalingProcesses' => processes)
reload
end
def suspend_processes(processes = [])
requires :id
connection.suspend_processes(id, 'ScalingProcesses' => processes)
reload
end
def ready?
# Is this useful?
#instances_in_service.length == desired_capacity
#instances_in_service.length >= min_size
true
end
def save
requires :id
requires :availability_zones
requires :launch_configuration_name
requires :max_size
requires :min_size
connection.create_auto_scaling_group(id, availability_zones, launch_configuration_name, max_size, min_size)
reload
end
#def reload
# super
# self
#end
def destroy
requires :id
connection.delete_auto_scaling_group(id)
end
private
def update(options)
requires :id
connection.update_auto_scaling_group(id, options)
reload
end
end
end
end
end

View file

@ -0,0 +1,35 @@
require 'fog/aws/models/auto_scaling/group'
module Fog
module AWS
class AutoScaling
class Groups < Fog::Collection
model Fog::AWS::AutoScaling::Group
# Creates a new auto scaling group.
def initialize(attributes={})
super
end
def all
data = []
next_token = nil
loop do
result = connection.describe_auto_scaling_groups('NextToken' => next_token).body['DescribeAutoScalingGroupsResult']
data += result['AutoScalingGroups']
next_token = result['NextToken']
break if next_token.nil?
end
load(data)
end
def get(identity)
data = connection.describe_auto_scaling_groups('AutoScalingGroupNames' => identity).body['DescribeAutoScalingGroupsResult']['AutoScalingGroups'].first
new(data) unless data.nil?
end
end
end
end
end

View file

@ -0,0 +1,60 @@
require 'fog/core/model'
module Fog
module AWS
class AutoScaling
class Instance < Fog::Model
identity :id, :aliases => 'InstanceId'
attribute :auto_scaling_group_name, :aliases => 'AutoScalingGroupName'
attribute :availability_zone, :aliases => 'AvailabilityZone'
attribute :health_status, :aliases => 'HealthStatus'
attribute :launch_configuration_name, :aliases => 'LaunchConfigurationName'
attribute :life_cycle_state, :aliases => 'LifecycleState'
def initialize(attributes={})
super
end
def group
connection.groups.get(attributes['AutoScalingGroupName'])
end
def configuration
connection.configurations.get(attributes['LaunchConfigurationName'])
end
def set_health(health_status, options)
requires :id
connection.set_instance_health(health_status, id, options)
reload
end
def terminate(should_decrement_desired_capacity)
requires :id
connection.terminate_instance_in_auto_scaling_group(id, should_decrement_desired_capacity)
reload
end
def healthy?
health_status == 'HEALTHY'
end
def ready?
life_cycle_state == 'InService'
end
def reload
super
self
end
#def destroy
# requires :id
# connection.delete_auto_scaling_group(id)
#end
end
end
end
end

View file

@ -0,0 +1,30 @@
require 'fog/aws/models/auto_scaling/instance'
module Fog
module AWS
class AutoScaling
class Instances < Fog::Collection
model Fog::AWS::AutoScaling::Instance
def all
data = []
next_token = nil
loop do
result = connection.describe_auto_scaling_instances('NextToken' => next_token).body['DescribeAutoScalingInstancesResult']
data += result['AutoScalingInstances']
next_token = result['NextToken']
break if next_token.nil?
end
load(data)
end
def get(identity)
data = connection.describe_auto_scaling_instances('InstanceIds' => identity).body['DescribeAutoScalingInstancesResult']['AutoScalingInstances'].first
new(data) unless data.nil?
end
end
end
end
end

View file

@ -0,0 +1,14 @@
require 'fog/core/model'
module Fog
module AWS
class CloudWatch
class Metric < Fog::Model
attribute :name, :aliases => 'MetricName'
attribute :namespace, :aliases => 'Namespace'
attribute :dimensions, :aliases => 'Dimensions'
end
end
end
end

View file

@ -0,0 +1,46 @@
require 'fog/core/model'
module Fog
module AWS
class CloudWatch
class MetricStatistic < Fog::Model
attribute :label, :aliases => 'Label'
attribute :minimum, :aliases => 'Minimum'
attribute :maximum, :aliases => 'Maximum'
attribute :sum, :aliases => 'Sum'
attribute :average, :aliases => 'Average'
attribute :sample_count, :aliases => 'SampleCount'
attribute :timestamp, :aliases => 'Timestamp'
attribute :unit, :aliases => 'Unit'
attribute :metric_name, :aliases => 'MetricName'
attribute :namespace, :aliases => 'Namespace'
attribute :dimensions, :aliases => 'Dimensions'
attribute :value
def save
requires :metric_name
requires :namespace
requires :unit
put_opts = {'MetricName' => metric_name, 'Unit' => unit}
put_opts.merge!('Dimensions' => dimensions) if dimensions
put_opts.merge!('Timestamp' => dimensions) if timestamp
if value
put_opts.merge!('Value' => value)
else
put_opts.merge!('StatisticValues' => {
'Minimum' => minimum,
'Maximum' => maximum,
'Sum' => sum,
'Average' => average,
'SampleCount' => sample_count
})
end
connection.put_metric_data(namespace, [put_opts])
true
end
end
end
end
end

View file

@ -0,0 +1,23 @@
require 'fog/core/collection'
require 'fog/aws/models/cloud_watch/metric_statistic'
module Fog
module AWS
class CloudWatch
class MetricStatistics < Fog::Collection
model Fog::AWS::CloudWatch::MetricStatistic
def all(conditions)
metricName = conditions['MetricName']
namespace = conditions['Namespace']
dimensions = conditions['Dimensions']
get_metric_opts = {"StartTime" => (Time.now-3600).iso8601, "EndTime" => Time.now.iso8601, "Period" => 300}.merge(conditions)
data = connection.get_metric_statistics(get_metric_opts).body['GetMetricStatisticsResult']['Datapoints']
data.collect! { |datum| datum.merge('MetricName' => metricName, 'Namespace' => namespace, 'Dimensions' => dimensions) }
load(data) # data is an array of attribute hashes
end
end
end
end
end

View file

@ -0,0 +1,32 @@
require 'fog/core/collection'
require 'fog/aws/models/cloud_watch/metric'
module Fog
module AWS
class CloudWatch
class Metrics < Fog::Collection
model Fog::AWS::CloudWatch::Metric
def all(conditions={})
data = connection.list_metrics(conditions).body['ListMetricsResult']['Metrics']
load(data) # data is an array of attribute hashes
end
def get(namespace, metric_name, dimensions=nil)
list_opts = {'Namespace' => namespace, 'MetricName' => metric_name}
if dimensions
dimensions_array = dimensions.collect do |name, value|
{'Name' => name, 'Value' => value}
end
# list_opts.merge!('Dimensions' => dimensions_array)
end
if data = connection.list_metrics(list_opts).body['ListMetricsResult']['Metrics'].first
new(data)
end
end
end
end
end
end

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class Address < Fog::Model

View file

@ -1,16 +1,16 @@
require 'fog/core/collection'
require 'fog/compute/models/aws//address'
require 'fog/aws/models/compute/address'
module Fog
module AWS
class Compute
module Compute
class AWS
class Addresses < Fog::Collection
attribute :filters
attribute :server
model Fog::AWS::Compute::Address
model Fog::Compute::AWS::Address
# Used to create an IP address
#
@ -56,7 +56,7 @@ module Fog
def all(filters = filters)
unless filters.is_a?(Hash)
Formatador.display_line("[yellow][WARN] all with #{filters.class} param is deprecated, use all('public-ip' => []) instead[/] [light_black](#{caller.first})[/]")
Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('public-ip' => []) instead [light_black](#{caller.first})[/]")
filters = {'public-ip' => [*filters]}
end
self.filters = filters

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class Flavor < Fog::Model

View file

@ -1,9 +1,9 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/flavor'
require 'fog/aws/models/compute/flavor'
module Fog
module AWS
class Compute
module Compute
class AWS
FLAVORS = [
{ :bits => 0, :cores => 2, :disk => 0, :id => 't1.micro', :name => 'Micro Instance', :ram => 613},
@ -25,7 +25,7 @@ module Fog
class Flavors < Fog::Collection
model Fog::AWS::Compute::Flavor
model Fog::Compute::AWS::Flavor
# Returns an array of all flavors that have been created
#
@ -131,7 +131,7 @@ module Fog
#
def all
load(Fog::AWS::Compute::FLAVORS)
load(Fog::Compute::AWS::FLAVORS)
self
end

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class Image < Fog::Model
@ -13,6 +13,7 @@ module Fog
attribute :description
attribute :location, :aliases => 'imageLocation'
attribute :owner_id, :aliases => 'imageOwnerId'
attribute :owner_alias, :aliases => 'imageOwnerAlias'
attribute :state, :aliases => 'imageState'
attribute :type, :aliases => 'imageType'
attribute :is_public, :aliases => 'isPublic'
@ -36,6 +37,10 @@ module Fog
end
end
def ready?
state == 'available'
end
end
end

View file

@ -1,15 +1,15 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/image'
require 'fog/aws/models/compute/image'
module Fog
module AWS
class Compute
module Compute
class AWS
class Images < Fog::Collection
attribute :filters
model Fog::AWS::Compute::Image
model Fog::Compute::AWS::Image
# Creates a new Amazon machine image
#

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class KeyPair < Fog::Model
@ -52,7 +52,6 @@ module Fog
!!(private_key && ENV.has_key?('HOME'))
end
private
end
end

View file

@ -1,16 +1,16 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/key_pair'
require 'fog/aws/models/compute/key_pair'
module Fog
module AWS
class Compute
module Compute
class AWS
class KeyPairs < Fog::Collection
attribute :filters
attribute :key_name
model Fog::AWS::Compute::KeyPair
model Fog::Compute::AWS::KeyPair
# Used to create a key pair. There are 3 arguments and only name is required. You can generate a new key_pair as follows:
# AWS.key_pairs.create(:name => "test", :fingerprint => "123", :private_key => '234234')
@ -51,7 +51,7 @@ module Fog
def all(filters = filters)
unless filters.is_a?(Hash)
Formatador.display_line("[yellow][WARN] all with #{filters.class} param is deprecated, use all('key-name' => []) instead[/] [light_black](#{caller.first})[/]")
Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('key-name' => []) instead [light_black](#{caller.first})[/]")
filters = {'key-name' => [*filters]}
end
self.filters = filters

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class SecurityGroup < Fog::Model
@ -38,7 +38,7 @@ module Fog
# "Server"=>"AmazonEC2"}
#
def authorize_group_and_owner(group, owner)
def authorize_group_and_owner(group, owner = nil)
requires :name
connection.authorize_security_group_ingress(
@ -130,7 +130,7 @@ module Fog
# "Server"=>"AmazonEC2"}
#
def revoke_group_and_owner(group, owner)
def revoke_group_and_owner(group, owner = nil)
requires :name
connection.revoke_security_group_ingress(

View file

@ -1,15 +1,15 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/security_group'
require 'fog/aws/models/compute/security_group'
module Fog
module AWS
class Compute
module Compute
class AWS
class SecurityGroups < Fog::Collection
attribute :filters
model Fog::AWS::Compute::SecurityGroup
model Fog::Compute::AWS::SecurityGroup
# Creates a new security group
#
@ -57,7 +57,7 @@ module Fog
def all(filters = filters)
unless filters.is_a?(Hash)
Formatador.display_line("[yellow][WARN] all with #{filters.class} param is deprecated, use all('group-name' => []) instead[/] [light_black](#{caller.first})[/]")
Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('group-name' => []) instead [light_black](#{caller.first})[/]")
filters = {'group-name' => [*filters]}
end
self.filters = filters

View file

@ -1,10 +1,10 @@
require 'fog/core/model'
require 'fog/compute/models/server'
module Fog
module AWS
class Compute
module Compute
class AWS
class Server < Fog::Model
class Server < Fog::Compute::Server
extend Fog::Deprecation
deprecate :ip_address, :public_ip_address
@ -12,7 +12,7 @@ module Fog
attr_accessor :architecture
attribute :ami_launch_index, :aliases => 'amiLaunchIndex'
attribute :availability_zone, :aliases => ['availabilityZone', 'placement'], :squash => 'availabilityZone'
attribute :availability_zone, :aliases => 'availabilityZone'
attribute :block_device_mapping, :aliases => 'blockDeviceMapping'
attribute :client_token, :aliases => 'clientToken'
attribute :dns_name, :aliases => 'dnsName'
@ -24,6 +24,8 @@ module Fog
attribute :key_name, :aliases => 'keyName'
attribute :created_at, :aliases => 'launchTime'
attribute :monitoring, :squash => 'state'
attribute :placement_group, :aliases => 'groupName'
attribute :platform, :aliases => 'platform'
attribute :product_codes, :aliases => 'productCodes'
attribute :private_dns_name, :aliases => 'privateDnsName'
attribute :private_ip_address, :aliases => 'privateIpAddress'
@ -35,6 +37,7 @@ module Fog
attribute :state, :aliases => 'instanceState', :squash => 'name'
attribute :state_reason, :aliases => 'stateReason'
attribute :subnet_id, :aliases => 'subnetId'
attribute :tenancy
attribute :tags, :aliases => 'tagSet'
attribute :user_data
@ -44,7 +47,8 @@ module Fog
def initialize(attributes={})
self.groups ||= ["default"] unless attributes[:subnet_id]
self.flavor_id ||= 't1.micro'
self.image_id ||= begin
self.image_id ||= begin
self.username = 'ubuntu'
case attributes[:connection].instance_variable_get(:@region) # Ubuntu 10.04 LTS 64bit (EBS)
when 'ap-northeast-1'
'ami-5e0fa45f'
@ -144,6 +148,8 @@ module Fog
'KeyName' => key_name,
'Monitoring.Enabled' => monitoring,
'Placement.AvailabilityZone' => availability_zone,
'Placement.GroupName' => placement_group,
'Placement.Tenancy' => tenancy,
'RamdiskId' => ramdisk_id,
'SecurityGroup' => groups,
'SubnetId' => subnet_id,
@ -162,50 +168,48 @@ module Fog
data = connection.run_instances(image_id, 1, 1, options)
merge_attributes(data.body['instancesSet'].first)
if self.tags
for key, value in self.tags
connection.tags.create(
:key => key,
:resource_id => self.identity,
:value => value
)
end
end
true
end
def setup(credentials = {})
requires :identity, :public_ip_address, :username
require 'json'
requires :public_ip_address, :username
require 'multi_json'
require 'net/ssh'
commands = [
%{mkdir .ssh},
%{passwd -l #{username}},
%{echo "#{attributes.to_json}" >> ~/attributes.json}
%{echo "#{MultiJson.encode(Fog::JSON.sanitize(attributes))}" >> ~/attributes.json}
]
if public_key
commands << %{echo "#{public_key}" >> ~/.ssh/authorized_keys}
end
# allow some retries over the first 120 seconds because aws is weird
Timeout::timeout(120) do
# wait for aws to be ready
Timeout::timeout(360) do
begin
Timeout::timeout(4) do
Fog::SSH.new(public_ip_address, username, credentials).run(commands)
Timeout::timeout(8) do
Fog::SSH.new(public_ip_address, username, credentials.merge(:timeout => 4)).run('pwd')
end
rescue Errno::ECONNREFUSED
sleep(2)
retry
rescue Net::SSH::AuthenticationFailed, Timeout::Error
retry
end
end
rescue Errno::ECONNREFUSED => e
sleep(1)
retry
end
def ssh(commands)
requires :identity, :public_ip_address, :username
options = {}
options[:key_data] = [private_key] if private_key
Fog::SSH.new(public_ip_address, username, options).run(commands)
end
def scp(local_path, remote_path, upload_options = {})
requires :public_ip_address, :username
scp_options = {}
scp_options[:key_data] = [private_key] if private_key
Fog::SCP.new(public_ip_address, username, scp_options).upload(local_path, remote_path, upload_options)
Fog::SSH.new(public_ip_address, username, credentials).run(commands)
end
def start
@ -214,9 +218,9 @@ module Fog
true
end
def stop
def stop(force = false)
requires :id
connection.stop_instances(id)
connection.stop_instances(id, force)
true
end
@ -246,6 +250,16 @@ module Fog
self.monitoring = new_monitor
end
private
def placement=(new_placement)
if new_placement.is_a?(Hash)
merge_attributes(new_placement)
else
self.attributes[:placement] = new_placement
end
end
end
end

View file

@ -1,15 +1,15 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/server'
require 'fog/aws/models/compute/server'
module Fog
module AWS
class Compute
module Compute
class AWS
class Servers < Fog::Collection
attribute :filters
model Fog::AWS::Compute::Server
model Fog::Compute::AWS::Server
# Creates a new server
#
@ -49,7 +49,7 @@ module Fog
# user_data=nil
# >
#
def initialize(attributes)
self.filters ||= {}
super
@ -57,7 +57,7 @@ module Fog
def all(filters = self.filters)
unless filters.is_a?(Hash)
Formatador.display_line("[yellow][WARN] all with #{filters.class} param is deprecated, use all('instance-id' => []) instead[/] [light_black](#{caller.first})[/]")
Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('instance-id' => []) instead [light_black](#{caller.first})[/]")
filters = {'instance-id' => [*filters]}
end
self.filters = filters

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class Snapshot < Fog::Model

View file

@ -1,16 +1,16 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/snapshot'
require 'fog/aws/models/compute/snapshot'
module Fog
module AWS
class Compute
module Compute
class AWS
class Snapshots < Fog::Collection
attribute :filters
attribute :volume
model Fog::AWS::Compute::Snapshot
model Fog::Compute::AWS::Snapshot
def initialize(attributes)
self.filters ||= { 'RestorableBy' => 'self' }
@ -19,7 +19,7 @@ module Fog
def all(filters = filters, options = {})
unless filters.is_a?(Hash)
Formatador.display_line("[yellow][WARN] all with #{filters.class} param is deprecated, use all('snapshot-id' => []) instead[/] [light_black](#{caller.first})[/]")
Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('snapshot-id' => []) instead [light_black](#{caller.first})[/]")
filters = {'snapshot-id' => [*filters]}
end
self.filters = filters

View file

@ -0,0 +1,93 @@
require 'fog/core/model'
module Fog
module Compute
class AWS
class SpotRequest < Fog::Model
identity :id, :aliases => 'spotInstanceRequestId'
attribute :price, :aliases => 'spotPrice'
attribute :request_type, :aliases => 'type'
attribute :created_at, :aliases => 'createTime'
attribute :instance_count, :aliases => 'instanceCount'
attribute :instance_id, :aliases => 'instanceId'
attribute :state
attribute :valid_from, :aliases => 'validFrom'
attribute :valid_until, :aliases => 'validUntil'
attribute :launch_group, :aliases => 'launchGroup'
attribute :availability_zone_group, :aliases => 'availabilityZoneGroup'
attribute :product_description, :aliases => 'productDescription'
attribute :groups, :aliases => 'LaunchSpecification.SecurityGroup'
attribute :key_name, :aliases => 'LaunchSpecification.KeyName'
attribute :availability_zone, :aliases => 'LaunchSpecification.Placement.AvailabilityZone'
attribute :flavor_id, :aliases => 'LaunchSpecification.InstanceType'
attribute :image_id, :aliases => 'LaunchSpecification.ImageId'
attribute :monitoring, :aliases => 'LaunchSpecification.Monitoring'
attribute :block_device_mapping, :aliases => 'LaunchSpecification.BlockDeviceMapping'
attribute :tags, :aliases => 'tagSet'
attribute :fault, :squash => 'message'
attribute :user_data
attr_writer :username
def initialize(attributes={})
self.groups ||= ["default"]
self.flavor_id ||= 't1.micro'
self.image_id ||= begin
self.username = 'ubuntu'
case attributes[:connection].instance_variable_get(:@region) # Ubuntu 10.04 LTS 64bit (EBS)
when 'ap-northeast-1'
'ami-5e0fa45f'
when 'ap-southeast-1'
'ami-f092eca2'
when 'eu-west-1'
'ami-3d1f2b49'
when 'us-east-1'
'ami-3202f25b'
when 'us-west-1'
'ami-f5bfefb0'
end
end
super
end
def save
requires :image_id, :flavor_id, :price
options = {
'AvailabilityZoneGroup' => availability_zone_group,
'InstanceCount' => instance_count,
'LaunchGroup' => launch_group,
'LaunchSpecification.BlockDeviceMapping' => block_device_mapping,
'LaunchSpecification.KeyName' => key_name,
'LaunchSpecification.Monitoring.Enabled' => monitoring,
'LaunchSpecification.Placement.AvailabilityZone' => availability_zone,
'LaunchSpecification.SecurityGroup' => groups,
'LaunchSpecification.UserData' => user_data,
'Type' => request_type,
'ValidFrom' => valid_from,
'ValidUntil' => valid_until }
options.delete_if {|key, value| value.nil?}
data = connection.request_spot_instances(image_id, flavor_id, price, options).body
spot_instance_request = data['spotInstanceRequestSet'].first
spot_instance_request['launchSpecification'].each do |name,value|
spot_instance_request['LaunchSpecification.' + name[0,1].upcase + name[1..-1]] = value
end
spot_instance_request.merge(:groups => spot_instance_request['LaunchSpecification.GroupSet'])
spot_instance_request.merge(options)
merge_attributes( spot_instance_request )
end
def ready?
state == 'active'
end
end
end
end
end

View file

@ -0,0 +1,48 @@
require 'fog/core/collection'
require 'fog/aws/models/compute/spot_request'
module Fog
module Compute
class AWS
class SpotRequests < Fog::Collection
attribute :filters
model Fog::Compute::AWS::SpotRequest
def initialize(attributes)
self.filters ||= {}
super
end
def all(filters = self.filters)
unless filters.is_a?(Hash)
Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('spot-instance-request-id' => []) instead [light_black](#{caller.first})[/]")
filters = {'spot-instance-request-id' => [*filters]}
end
self.filters = filters
data = connection.describe_spot_instance_requests(filters).body
load(
data['spotInstanceRequestSet'].map do |spot_instance_request|
spot_instance_request['LaunchSpecification.Placement.AvailabilityZone'] = spot_instance_request['launchedAvailabilityZone']
spot_instance_request['launchSpecification'].each do |name,value|
spot_instance_request['LaunchSpecification.' + name[0,1].upcase + name[1..-1]] = value
end
spot_instance_request.merge(:groups => spot_instance_request['LaunchSpecification.GroupSet'])
spot_instance_request
end.flatten
)
end
def get(spot_request_id)
if spot_request_id
self.class.new(:connection => connection).all('spot-instance-request-id' => spot_request_id).first
end
rescue Fog::Errors::NotFound
nil
end
end
end
end
end

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class Tag < Fog::Model
@ -10,7 +10,7 @@ module Fog
attribute :value
attribute :resource_id, :aliases => 'resourceId'
attribute :resource_type, :aliases => 'resourceType'
attribute :resource_type, :aliases => 'resourceType'
def initialize(attributes = {})
super
@ -28,8 +28,6 @@ module Fog
true
end
private
end
end
end

View file

@ -1,15 +1,15 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/tag'
require 'fog/aws/models/compute/tag'
module Fog
module AWS
class Compute
module Compute
class AWS
class Tags < Fog::Collection
attribute :filters
model Fog::AWS::Compute::Tag
model Fog::Compute::AWS::Tag
def initialize(attributes)
self.filters ||= {}

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Compute
module Compute
class AWS
class Volume < Fog::Model
@ -38,7 +38,8 @@ module Fog
def save
raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if identity
requires :availability_zone, :size
requires :availability_zone
requires_one :size, :snapshot_id
data = connection.create_volume(availability_zone, size, snapshot_id).body
new_attributes = data.reject {|key,value| key == 'requestId'}
@ -49,6 +50,11 @@ module Fog
true
end
def server
requires :server_id
connection.servers('instance-id' => server_id)
end
def server=(new_server)
if new_server
attach(new_server)
@ -62,6 +68,15 @@ module Fog
connection.snapshots(:volume => self)
end
def snapshot(description)
requires :id
connection.create_snapshot(id, description)
end
def force_detach
detach(true)
end
private
def attachmentSet=(new_attachment_set)
@ -81,25 +96,15 @@ module Fog
end
end
def detach
def detach(force = false)
@server = nil
self.server_id = nil
unless new_record?
connection.detach_volume(id)
connection.detach_volume(id, 'Force' => force)
reload
end
end
def force_detach
@server = nil
self.server_id = nil
unless new_record?
connection.detach_volume(id, 'Force' => true)
reload
end
end
end
end

View file

@ -1,16 +1,16 @@
require 'fog/core/collection'
require 'fog/compute/models/aws/volume'
require 'fog/aws/models/compute/volume'
module Fog
module AWS
class Compute
module Compute
class AWS
class Volumes < Fog::Collection
attribute :filters
attribute :server
model Fog::AWS::Compute::Volume
model Fog::Compute::AWS::Volume
# Used to create a volume. There are 3 arguments and availability_zone and size are required. You can generate a new key_pair as follows:
# AWS.volumes.create(:availability_zone => 'us-east-1a', :size => 10)
@ -64,7 +64,7 @@ module Fog
def all(filters = filters)
unless filters.is_a?(Hash)
Formatador.display_line("[yellow][WARN] all with #{filters.class} param is deprecated, use all('volume-id' => []) instead[/] [light_black](#{caller.first})[/]")
Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('volume-id' => []) instead [light_black](#{caller.first})[/]")
filters = {'volume-id' => [*filters]}
end
self.filters = filters

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class DNS
module DNS
class AWS
class Record < Fog::Model
extend Fog::Deprecation

View file

@ -1,9 +1,9 @@
require 'fog/core/collection'
require 'fog/dns/models/aws/record'
require 'fog/aws/models/dns/record'
module Fog
module AWS
class DNS
module DNS
class AWS
class Records < Fog::Collection
@ -16,7 +16,7 @@ module Fog
attribute :zone
model Fog::AWS::DNS::Record
model Fog::DNS::AWS::Record
def all(options = {})
requires :zone

View file

@ -1,9 +1,9 @@
require 'fog/core/model'
# require 'fog/dns/models/aws/records'
# require 'fog/aws/models/dns/records'
module Fog
module AWS
class DNS
module DNS
class AWS
class Zone < Fog::Model
@ -23,7 +23,7 @@ module Fog
def records
@records ||= begin
Fog::AWS::DNS::Records.new(
Fog::DNS::AWS::Records.new(
:zone => self,
:connection => connection
)

View file

@ -1,16 +1,16 @@
require 'fog/core/collection'
require 'fog/dns/models/aws/zone'
require 'fog/aws/models/dns/zone'
module Fog
module AWS
class DNS
module DNS
class AWS
class Zones < Fog::Collection
attribute :marker, :aliases => 'Marker'
attribute :max_items, :aliases => 'MaxItems'
model Fog::AWS::DNS::Zone
model Fog::DNS::AWS::Zone
def all(options = {})
options['marker'] ||= marker

View file

@ -0,0 +1,69 @@
require 'fog/core/model'
module Fog
module AWS
class Elasticache
class Cluster < Fog::Model
# simple attributes
identity :id, :aliases => 'CacheClusterId'
attribute :auto_upgrade, :aliases => 'AutoMinorVersionUpgrade'
attribute :status, :aliases => 'CacheClusterStatus'
attribute :node_type, :aliases => 'CacheNodeType'
attribute :engine, :aliases => 'Engine'
attribute :engine_version, :aliases => 'EngineVersion'
attribute :num_nodes, :aliases => 'NumCacheNodes'
attribute :zone, :aliases => 'PreferredAvailabilityZone'
attribute :port, :aliases => 'Port'
attribute :maintenance_window, :aliases => 'PreferredMaintenanceWindow'
# complex attributes
attribute :nodes, :aliases => 'CacheNodes', :type => :array
attribute :parameter_group,
:aliases => 'CacheParameterGroup', :type => :hash
attribute :pending_values,
:aliases => 'PendingModifiedValues', :type => :hash
attribute :create_time,
:aliases => 'CacheClusterCreateTime', :type => :date_time
attribute :security_groups,
:aliases => 'CacheSecurityGroups', :type => :array
attribute :notification_config,
:aliases => 'NotificationConfiguration', :type => :hash
def ready?
status == 'available'
end
def destroy
requires :id
connection.delete_cache_cluster(id)
true
end
def save
requires :id
parameter_group ||= Hash.new
notification_config ||= Hash.new
connection.create_cache_cluster(
id, {
:node_type => node_type,
:security_group_names => security_groups,
:num_nodes => num_nodes,
:auto_minor_version_upgrade => auto_upgrade,
:engine => engine,
:engine_version => engine_version,
:notification_topic_arn => notification_config['TopicArn'],
:port => port,
:preferred_availablility_zone => zone,
:preferred_maintenance_window => maintenance_window,
:parameter_group_name => parameter_group['CacheParameterGroupName'],
}
)
end
end
end
end
end

View file

@ -0,0 +1,31 @@
require 'fog/core/collection'
require 'fog/aws/models/elasticache/cluster'
module Fog
module AWS
class Elasticache
class Clusters < Fog::Collection
model Fog::AWS::Elasticache::Cluster
def all
load(
connection.describe_cache_clusters(
nil, :show_node_info => true
).body['CacheClusters']
)
end
def get(identity, show_node_info = true)
new(
connection.describe_cache_clusters(
identity, :show_node_info => show_node_info
).body['CacheClusters'].first
)
rescue Fog::AWS::Elasticache::NotFound
end
end
end
end
end

View file

@ -0,0 +1,32 @@
require 'fog/core/model'
module Fog
module AWS
class Elasticache
class ParameterGroup < Fog::Model
identity :id, :aliases => 'CacheParameterGroupName'
attribute :description, :aliases => 'Description'
attribute :family, :aliases => 'CacheParameterGroupFamily'
def destroy
requires :id
connection.delete_cache_parameter_group(id)
true
end
def save
requires :id
connection.create_cache_parameter_group(
id,
description = id,
family = 'memcached1.4'
)
end
end
end
end
end

View file

@ -0,0 +1,30 @@
require 'fog/core/collection'
require 'fog/aws/models/elasticache/parameter_group'
module Fog
module AWS
class Elasticache
class ParameterGroups < Fog::Collection
model Fog::AWS::Elasticache::ParameterGroup
def all
load(
connection.describe_cache_parameter_groups.body['CacheParameterGroups']
)
end
def get(identity)
new(
connection.describe_cache_parameter_groups(
identity
).body['CacheParameterGroups'].first
)
rescue Fog::AWS::Elasticache::NotFound
nil
end
end
end
end
end

View file

@ -0,0 +1,52 @@
require 'fog/core/model'
module Fog
module AWS
class Elasticache
class SecurityGroup < Fog::Model
identity :id, :aliases => 'CacheSecurityGroupName'
attribute :description, :aliases => 'Description'
attribute :ec2_groups, :aliases => 'EC2SecurityGroups', :type => :array
attribute :owner_id, :aliases => 'OwnerId'
def ready?
ec2_groups.all?{|ingress| ingress['Status'] == 'authorized'}
end
def destroy
requires :id
connection.delete_cache_security_group(id)
true
end
def save
requires :id
requires :description
connection.create_cache_security_group(id, description)
end
def authorize_ec2_group(group_name, group_owner_id=owner_id)
requires :id
requires :owner_id if group_owner_id.nil?
data = connection.authorize_cache_security_group_ingress(
id, group_name, group_owner_id
)
merge_attributes(data.body['CacheSecurityGroup'])
end
def revoke_ec2_group(group_name, group_owner_id=owner_id)
requires :id
requires :owner_id if group_owner_id.nil?
data = connection.revoke_cache_security_group_ingress(
id, group_name, group_owner_id
)
merge_attributes(data.body['CacheSecurityGroup'])
end
end
end
end
end

View file

@ -0,0 +1,30 @@
require 'fog/core/collection'
require 'fog/aws/models/elasticache/security_group'
module Fog
module AWS
class Elasticache
class SecurityGroups < Fog::Collection
model Fog::AWS::Elasticache::SecurityGroup
def all
load(
connection.describe_cache_security_groups.body['CacheSecurityGroups']
)
end
def get(identity)
new(
connection.describe_cache_security_groups(
identity
).body['CacheSecurityGroups'].first
)
rescue Fog::AWS::Elasticache::NotFound
nil
end
end
end
end
end

View file

@ -10,6 +10,12 @@ module Fog
attribute :protocol, :aliases => 'Protocol'
attribute :ssl_id, :aliases => 'SSLCertificateId'
def initialize(attributes={})
# set defaults, which may be overridden in super
merge_attributes(:policy_names => [], :instance_port => 80, :lb_port => 80, :protocol => 'HTTP')
super
end
def save
requires :load_balancer, :instance_port, :lb_port, :protocol
connection.create_load_balancer_listeners(load_balancer.id, [to_params])

View file

@ -17,9 +17,9 @@ module Fog
end
private
# Munge an array of ListernerDescription hashes like:
# Munge an array of ListenerDescription hashes like:
# {'Listener' => listener, 'PolicyNames' => []}
# to an array of listeners withi a PolicyNames key
# to an array of listeners with a PolicyNames key
def munged_data
data.map {|description|
description['Listener'].merge('PolicyNames' => description['PolicyNames'])

View file

@ -14,11 +14,14 @@ module Fog
attribute :source_group, :aliases => 'SourceSecurityGroup'
def initialize(attributes={})
attributes[:availability_zones] ||= %w(us-east-1a us-east-1b us-east-1c us-east-1d)
attributes['ListenerDescriptions'] ||= [{
'Listener' => {'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'http'},
'PolicyNames' => []
}]
attributes[:availability_zones] ||= attributes['AvailabilityZones'] || %w(us-east-1a us-east-1b us-east-1c us-east-1d)
unless attributes['ListenerDescriptions']
new_listener = Fog::AWS::ELB::Listener.new
attributes['ListenerDescriptions'] = [{
'Listener' => new_listener.to_params,
'PolicyNames' => new_listener.policy_names
}]
end
attributes['Policies'] ||= {'AppCookieStickinessPolicies' => [], 'LBCookieStickinessPolicies' => []}
super
end

View file

@ -1,4 +1,5 @@
require 'fog/core/model'
require 'fog/core/current_machine'
module Fog
module AWS
@ -43,6 +44,16 @@ module Fog
authorize_ingress({'CIDRIP' => cidrip})
end
# Add the current machine to the RDS security group.
def authorize_me
authorize_ip_address(Fog::CurrentMachine.ip_address)
end
# Add the ip address to the RDS security group.
def authorize_ip_address(ip)
authorize_cidrip("#{ip}/32")
end
def authorize_ingress(opts)
data = connection.authorize_db_security_group_ingress(id, opts).body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']
merge_attributes(data)

View file

@ -25,26 +25,24 @@ module Fog
attribute :preferred_backup_window, :aliases => 'PreferredBackupWindow'
attribute :preferred_maintenance_window, :aliases => 'PreferredMaintenanceWindow'
attribute :db_name, :aliases => 'DBName'
attribute :db_security_groups, :aliases => 'DBSecurityGroups'
attribute :db_security_groups, :aliases => 'DBSecurityGroups', :type => :array
attribute :db_parameter_groups, :aliases => 'DBParameterGroups'
attribute :backup_retention_period, :aliases => 'BackupRetentionPeriod', :type => :integer
attribute :license_model, :aliases => 'LicenseModel'
attr_accessor :password, :parameter_group_name, :security_group_names, :port
def initialize(attributes={})
self.flavor_id ||= 'db.m1.small'
super
end
def create_read_replica(replica_id, options={})
connection.create_db_instance_read_replica(replica_id, id, options)
options[:security_group_names] ||= options['DBSecurityGroups']
params = self.class.new(options).attributes_to_params
connection.create_db_instance_read_replica(replica_id, id, params)
connection.servers.get(replica_id)
end
def ready?
state == 'available'
end
def destroy(snapshot_identifier=nil)
requires :id
connection.delete_db_instance(id, snapshot_identifier, snapshot_identifier.nil?)
@ -55,50 +53,58 @@ module Fog
connection.reboot_db_instance(id)
true
end
def snapshots
requires :id
connection.snapshots(:server => self)
end
def modify(immediately, options)
data = connection.modify_db_instance(id, immediately, options)
options[:security_group_names] ||= options['DBSecurityGroups']
params = self.class.new(options).attributes_to_params
data = connection.modify_db_instance(id, immediately, params)
merge_attributes(data.body['ModifyDBInstanceResult']['DBInstance'])
true
true
end
def save
requires :engine
requires :allocated_storage
requires :master_username
requires :password
self.flavor_id ||= 'db.m1.small'
data = connection.create_db_instance(id, attributes_to_params)
merge_attributes(data.body['CreateDBInstanceResult']['DBInstance'])
true
end
# Converts attributes to a parameter hash suitable for requests
def attributes_to_params
options = {
'AllocatedStorage' => allocated_storage,
'AutoMinorVersionUpgrade' => auto_minor_version_upgrade,
'BackupRetentionPeriod' => backup_retention_period,
'DBName' => db_name,
'DBParameterGroupName' => parameter_group_name,
'DBParameterGroupName' => parameter_group_name || attributes['DBParameterGroupName'],
'DBSecurityGroups' => security_group_names,
'DBInstanceIdentifier' => id,
'AvailabilityZone' => availability_zone,
'DBInstanceClass' => flavor_id,
'Port' => port,
'Port' => port || attributes['Port'],
'Engine' => engine,
'EngineVersion' => engine_version,
'MasterUsername' => master_username,
'MasterUserPassword' => password,
'MasterUserPassword' => password || attributes['MasterUserPassword'],
'PreferredMaintenanceWindow' => preferred_maintenance_window,
'PreferredBackupWindow' => preferred_backup_window,
'MultiAZ' => multi_az
'MultiAZ' => multi_az,
'LicenseModel' => license_model
}
options.delete_if {|key, value| value.nil?}
data = connection.create_db_instance(id, options)
merge_attributes(data.body['CreateDBInstanceResult']['DBInstance'])
true
end
end
end
end

View file

@ -1,13 +1,13 @@
require 'fog/core/collection'
require 'fog/storage/models/aws/directory'
require 'fog/aws/models/storage/directory'
module Fog
module AWS
class Storage
module Storage
class AWS
class Directories < Fog::Collection
model Fog::AWS::Storage::Directory
model Fog::Storage::AWS::Directory
def all
data = connection.get_service.body['Buckets']

View file

@ -1,9 +1,9 @@
require 'fog/core/model'
require 'fog/storage/models/aws/files'
require 'fog/aws/models/storage/files'
module Fog
module AWS
class Storage
module Storage
class AWS
class Directory < Fog::Model
@ -39,7 +39,7 @@ module Fog
def files
@files ||= begin
Fog::AWS::Storage::Files.new(
Fog::Storage::AWS::Files.new(
:directory => self,
:connection => connection
)
@ -86,9 +86,7 @@ module Fog
if @acl
options['x-amz-acl'] = @acl
end
if @location
options['LocationConstraint'] = @location
end
options['LocationConstraint'] = @location || self.connection.region
connection.put_bucket(key, options)
true
end

View file

@ -1,8 +1,8 @@
require 'fog/core/model'
module Fog
module AWS
class Storage
module Storage
class AWS
class File < Fog::Model
@ -46,9 +46,9 @@ module Fog
@directory
end
def copy(target_directory_key, target_file_key)
def copy(target_directory_key, target_file_key, options = {})
requires :directory, :key
connection.copy_object(directory.key, key, target_directory_key, target_file_key)
connection.copy_object(directory.key, key, target_directory_key, target_file_key, options)
target_directory = connection.directories.new(:key => target_directory_key)
target_directory.files.get(target_file_key)
end
@ -92,9 +92,9 @@ module Fog
requires :directory, :key
if connection.get_object_acl(directory.key, key).body['AccessControlList'].detect {|grant| grant['Grantee']['URI'] == 'http://acs.amazonaws.com/groups/global/AllUsers' && grant['Permission'] == 'READ'}
if directory.key.to_s =~ /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/
"https://#{directory.key}.s3.amazonaws.com/#{key}"
"https://#{directory.key}.s3.amazonaws.com/#{Fog::AWS.escape(key)}"
else
"https://s3.amazonaws.com/#{directory.key}/#{key}"
"https://s3.amazonaws.com/#{directory.key}/#{Fog::AWS.escape(key)}"
end
else
nil
@ -104,7 +104,7 @@ module Fog
def save(options = {})
requires :body, :directory, :key
if options != {}
Formatador.display_line("[yellow][WARN] options param is deprecated, use acl= instead[/] [light_black](#{caller.first})[/]")
Fog::Logger.warning("options param is deprecated, use acl= instead [light_black](#{caller.first})[/]")
end
options['x-amz-acl'] ||= @acl if @acl
options['Cache-Control'] = cache_control if cache_control
@ -113,7 +113,7 @@ module Fog
options['Content-MD5'] = content_md5 if content_md5
options['Content-Type'] = content_type if content_type
options['Expires'] = expires if expires
options.merge(metadata)
options.merge!(metadata)
options['x-amz-storage-class'] = storage_class if storage_class
data = connection.put_object(directory.key, key, body, options)
@ -125,7 +125,7 @@ module Fog
def url(expires)
requires :key
collection.get_url(key, expires)
collection.get_https_url(key, expires)
end
private

View file

@ -1,11 +1,13 @@
require 'fog/core/collection'
require 'fog/storage/models/aws/file'
require 'fog/aws/models/storage/file'
module Fog
module AWS
class Storage
module Storage
class AWS
class Files < Fog::Collection
extend Fog::Deprecation
deprecate :get_url, :get_https_url
attribute :common_prefixes, :aliases => 'CommonPrefixes'
attribute :delimiter, :aliases => 'Delimiter'
@ -15,7 +17,7 @@ module Fog
attribute :max_keys, :aliases => ['MaxKeys', 'max-keys']
attribute :prefix, :aliases => 'Prefix'
model Fog::AWS::Storage::File
model Fog::Storage::AWS::File
def all(options = {})
requires :directory
@ -70,15 +72,20 @@ module Fog
when /<Code>NoSuchKey<\/Code>/
nil
when /<Code>NoSuchBucket<\/Code>/
raise(Fog::AWS::Storage::NotFound.new("Directory #{directory.identity} does not exist."))
raise(Fog::Storage::AWS::NotFound.new("Directory #{directory.identity} does not exist."))
else
raise(error)
end
end
def get_url(key, expires)
def get_http_url(key, expires)
requires :directory
connection.get_object_url(directory.key, key, expires)
connection.get_object_http_url(directory.key, key, expires)
end
def get_https_url(key, expires)
requires :directory
connection.get_object_https_url(directory.key, key, expires)
end
def head(key, options = {})

View file

@ -0,0 +1,28 @@
module Fog
module Parsers
module AWS
module AutoScaling
class Basic < Fog::Parsers::Base
def reset
@response = { 'ResponseMetadata' => {} }
end
def start_element(name, attrs = [])
super
end
def end_element(name)
case name
when 'RequestId'
@response['ResponseMetadata'][name] = value
end
end
end
end
end
end
end

View file

@ -0,0 +1,39 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeAdjustmentTypes < Fog::Parsers::Base
def reset
reset_adjustment_type
@results = { 'AdjustmentTypes' => [] }
@response = { 'DescribeAdjustmentTypesResult' => {}, 'ResponseMetadata' => {} }
end
def reset_adjustment_type
@adjustment_type = {}
end
def end_element(name)
case name
when 'member'
@results['AdjustmentTypes'] << @adjustment_type
reset_adjustment_type
when 'AdjustmentType'
@adjustment_type[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeAdjustmentTypesResponse'
@response['DescribeAdjustmentTypesResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,126 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeAutoScalingGroups < Fog::Parsers::Base
def reset
reset_auto_scaling_group
reset_enabled_metric
reset_instance
reset_suspended_process
@results = { 'AutoScalingGroups' => [] }
@response = { 'DescribeAutoScalingGroupsResult' => {}, 'ResponseMetadata' => {} }
end
def reset_auto_scaling_group
@auto_scaling_group = { 'AvailabilityZones' => [], 'EnabledMetrics' => [], 'Instances' => [], 'LoadBalancerNames' => [], 'SuspendedProcesses' => [] }
end
def reset_enabled_metric
@enabled_metric = {}
end
def reset_instance
@instance = {}
end
def reset_suspended_process
@suspended_process = {}
end
def start_element(name, attrs = [])
super
case name
when 'AvailabilityZones'
@in_availability_zones = true
when 'EnabledMetrics'
@in_enabled_metrics = true
when 'Instances'
@in_instances = true
when 'LoadBalancerNames'
@in_load_balancer_names = true
when 'SuspendedProcesses'
@in_suspended_processes = true
end
end
def end_element(name)
case name
when 'member'
if @in_availability_zones
@auto_scaling_group['AvailabilityZones'] << value
elsif @in_enabled_metrics
@auto_scaling_group['EnabledMetrics'] << @enabled_metric
reset_enabled_metric
elsif @in_instances
@auto_scaling_group['Instances'] << @instance
reset_instance
elsif @in_load_balancer_names
@auto_scaling_group['LoadBalancerNames'] << value
elsif @in_suspended_processes
@auto_scaling_group['SuspendedProcesses'] << @suspended_process
reset_suspended_process
elsif !@in_instances && !@in_policies
@results['AutoScalingGroups'] << @auto_scaling_group
reset_auto_scaling_group
end
when 'AvailabilityZones'
@in_availability_zones = false
when 'Granularity', 'Metric'
@enabled_metric[name] = value
when 'EnabledMetrics'
@in_enabled_metrics = false
when 'LaunchConfigurationName'
if @in_instances
@instance[name] = value
else
@auto_scaling_group[name] = value
end
when 'AvailabilityZone', 'HealthStatus', 'InstanceId', 'LifecycleState'
@instance[name] = value
when 'Instances'
@in_instances = false
when 'LoadBalancerNames'
@in_load_balancer_names = false
when 'ProcessName', 'SuspensionReason'
@suspended_process[name] = value
when 'SuspendedProcesses'
@in_suspended_processes = false
when 'AutoScalingGroupARN', 'AutoScalingGroupName'
@auto_scaling_group[name] = value
when 'CreatedTime'
@auto_scaling_group[name] = Time.parse(value)
when 'DefaultCooldown', 'DesiredCapacity', 'HealthCheckGracePeriod'
@auto_scaling_group[name] = value.to_i
when 'HealthCheckType'
@auto_scaling_group[name] = value
when 'MaxSize', 'MinSize'
@auto_scaling_group[name] = value.to_i
when 'PlacementGroup', 'VPCZoneIdentifier'
@auto_scaling_group[name] = value
when 'NextToken'
@results[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeAutoScalingGroupsResponse'
@response['DescribeAutoScalingGroupsResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,43 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeAutoScalingInstances < Fog::Parsers::Base
def reset
reset_auto_scaling_instance
@results = { 'AutoScalingInstances' => [] }
@response = { 'DescribeAutoScalingInstancesResult' => {}, 'ResponseMetadata' => {} }
end
def reset_auto_scaling_instance
@auto_scaling_instance = {}
end
def end_element(name)
case name
when 'member'
@results['AutoScalingInstances'] << @auto_scaling_instance
reset_auto_scaling_instance
when 'AutoScalingGroupName', 'AvailabilityZone', 'HealthStatus',
'InstanceId', 'LaunchConfigurationName', 'LifecycleState'
@auto_scaling_instance[name] = value
when 'NextToken'
@results[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeAutoScalingInstancesResponse'
@response['DescribeAutoScalingInstancesResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,94 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeLaunchConfigurations < Fog::Parsers::Base
def reset
reset_launch_configuration
reset_block_device_mapping
reset_ebs
@results = { 'LaunchConfigurations' => [] }
@response = { 'DescribeLaunchConfigurationsResult' => {}, 'ResponseMetadata' => {} }
end
def reset_launch_configuration
@launch_configuration = { 'BlockDeviceMappings' => [], 'InstanceMonitoring' => {}, 'SecurityGroups' => [] }
end
def reset_block_device_mapping
@block_device_mapping = {}
end
def reset_ebs
@ebs = {}
end
def start_element(name, attrs = [])
super
case name
when 'BlockDeviceMappings'
@in_block_device_mappings = true
when 'SecurityGroups'
@in_security_groups = true
end
end
def end_element(name)
case name
when 'member'
if @in_block_device_mappings
@launch_configuration['BlockDeviceMappings'] << @block_device_mapping
reset_block_device_mapping
elsif @in_security_groups
@launch_configuration['SecurityGroups'] << value
else
@results['LaunchConfigurations'] << @launch_configuration
reset_launch_configuration
end
when 'DeviceName', 'VirtualName'
@block_device_mapping[name] = value
when 'SnapshotId', 'VolumeSize'
@ebs[name] = value
when 'Ebs'
@block_device_mapping[name] = @ebs
reset_ebs
when 'Enabled'
@launch_configuration['InstanceMonitoring'][name] = (value == 'true')
when 'CreatedTime'
@launch_configuration[name] = Time.parse(value)
when 'ImageId', 'InstanceType', 'KeyName'
@launch_configuration[name] = value
when 'LaunchConfigurationARN', 'LaunchConfigurationName'
@launch_configuration[name] = value
when 'KernelId', 'RamdiskId', 'UserData'
@launch_configuration[name] = value
when 'BlockDeviceMappings'
@in_block_device_mappings = false
when 'LaunchConfigurations'
@in_launch_configurations = false
when 'SecurityGroups'
@in_security_groups = false
when 'NextToken'
@results[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeLaunchConfigurationsResponse'
@response['DescribeLaunchConfigurationsResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,66 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeMetricCollectionTypes < Fog::Parsers::Base
def reset
reset_granularity
reset_metric
@results = { 'Granularities' => [], 'Metrics' => [] }
@response = { 'DescribeMetricCollectionTypesResult' => {}, 'ResponseMetadata' => {} }
end
def reset_granularity
@granularity = {}
end
def reset_metric
@metric = {}
end
def start_element(name, attrs = [])
super
case name
when 'Granularities'
@in_granularities = true
when 'Metrics'
@in_metrics = true
end
end
def end_element(name)
case name
when 'member'
if @in_granularities
@results['Granularities'] << @granularity
reset_granularity
elsif @in_metrics
@results['Metrics'] << @metric
reset_metric
end
when 'Granularity'
@granularity[name] = value
when 'Granularities'
@in_granularities = false
when 'Metric'
@metric[name] = value
when 'Metrics'
@in_metrics = false
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeMetricCollectionTypesResult'
@response[name] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,66 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribePolicies < Fog::Parsers::Base
def reset
reset_scaling_policy
reset_alarm
@results = { 'ScalingPolicies' => [] }
@response = { 'DescribePoliciesResult' => {}, 'ResponseMetadata' => {} }
@in_alarms = false
end
def reset_scaling_policy
@scaling_policy = { 'Alarms' => [] }
end
def reset_alarm
@alarm = {}
end
def start_element(name, attrs = [])
super
case name
when 'Alarms'
@in_alarms = true
end
end
def end_element(name)
case name
when 'AlarmARN', 'AlarmName'
@alarm[name] = value
when 'AdjustmentType', 'AutoScalingGroupName', 'PolicyARN', 'PolicyName'
@scaling_policy[name] = value
when 'Cooldown', 'ScalingAdjustment'
@scaling_policy[name] = value.to_i
when 'NextToken'
@results[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribePoliciesResponse'
@response['DescribePoliciesResult'] = @results
when 'Alarms'
if @in_alarms == true
@scaling_policy['Alarms'] << @alarm
reset_alarm
end
when 'member'
@results['ScalingPolicies'] << @scaling_policy
reset_scaling_policy
end
end
end
end
end
end
end

View file

@ -0,0 +1,47 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeScalingActivities < Fog::Parsers::Base
def reset
reset_activity
@results = { 'Activities' => [] }
@response = { 'DescribeScalingActivitiesResult' => {}, 'ResponseMetadata' => {} }
end
def reset_activity
@activity = {}
end
def end_element(name)
case name
when 'member'
@results['Activities'] << @activity
reset_activity
when 'ActivityId', 'AutoScalingGroupName', 'Cause', 'Description',
'StatusCode', 'StatusMessage'
@activity[name] = value
when 'EndTime', 'StartTime'
@activity[name] = Time.parse(value)
when 'Progress'
@activity[name] = value.to_i
when 'NextToken'
@results[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeScalingActivitiesResponse'
@response['DescribeScalingActivitiesResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,39 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeScalingProcessTypes < Fog::Parsers::Base
def reset
reset_process_type
@results = { 'Processes' => [] }
@response = { 'DescribeScalingProcessTypesResult' => {}, 'ResponseMetadata' => {} }
end
def reset_process_type
@process_type = {}
end
def end_element(name)
case name
when 'member'
@results['Processes'] << @process_type
reset_process_type
when 'ProcessName'
@process_type[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeScalingProcessTypesResponse'
@response['DescribeScalingProcessTypesResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,46 @@
module Fog
module Parsers
module AWS
module AutoScaling
class DescribeScheduledActions < Fog::Parsers::Base
def reset
reset_scheduled_update_group_action
@results = { 'ScheduledUpdateGroupActions' => [] }
@response = { 'DescribeScheduledActionsResult' => {}, 'ResponseMetadata' => {} }
end
def reset_scheduled_update_group_action
@scheduled_update_group_action = {}
end
def end_element(name)
case name
when 'member'
@results['ScheduledUpdateGroupActions'] << @scheduled_update_group_action
reset_scheduled_update_group_action
when 'AutoScalingGroupName', 'ScheduledActionARN', 'ScheduledActionName'
@activity[name] = value
when 'DesiredCapacity', 'MaxSize', 'MinSize'
@scheduled_update_group_action[name] = value.to_i
when 'Time'
@scheduled_update_group_action[name] = Time.parse(value)
when 'NextToken'
@results[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'DescribeScheduledActionsResponse'
@response['DescribeScheduledActionsResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,30 @@
module Fog
module Parsers
module AWS
module AutoScaling
class PutScalingPolicy < Fog::Parsers::Base
def reset
@results = {}
@response = { 'PutScalingPolicyResult' => {}, 'ResponseMetadata' => {} }
end
def end_element(name)
case name
when 'PolicyARN'
@results[name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'PutScalingPolicyResponse'
@response['PutScalingPolicyResult'] = @results
end
end
end
end
end
end
end

View file

@ -0,0 +1,35 @@
module Fog
module Parsers
module AWS
module AutoScaling
class TerminateInstanceInAutoScalingGroup < Fog::Parsers::Base
def reset
@results = { 'Activity' => {} }
@response = { 'TerminateInstanceInAutoScalingGroupResult' => {}, 'ResponseMetadata' => {} }
end
def end_element(name)
case name
when 'ActivityId', 'AutoScalingGroupName', 'Cause',
'Description', 'StatusCode', 'StatusMessage'
@results['Activity'][name] = value
when 'EndTime', 'StartTime'
@results['Activity'][name] = Time.parse(value)
when 'Progress'
@results['Activity'][name] = value.to_i
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'TerminateInstanceInAutoScalingGroupResponse'
@response['TerminateInstanceInAutoScalingGroupResult'] = @results
end
end
end
end
end
end
end

View file

@ -1,7 +1,7 @@
module Fog
module Parsers
module AWS
module CDN
module CDN
module AWS
class Distribution < Fog::Parsers::Base

View file

@ -1,7 +1,7 @@
module Fog
module Parsers
module AWS
module CDN
module CDN
module AWS
class GetDistributionList < Fog::Parsers::Base

View file

@ -0,0 +1,43 @@
module Fog
module Parsers
module CDN
module AWS
class GetInvalidationList < Fog::Parsers::Base
def reset
@invalidation_summary = { }
@response = { 'InvalidationSummary' => [] }
end
def start_element(name, attrs = [])
super
end
def end_element(name)
puts name
case name
when 'InvalidationSummary'
@response['InvalidationSummary'] << @invalidation_summary
@invalidation_summary = {}
when 'Id', 'Status'
@invalidation_summary[name] = @value
when 'IsTruncated'
if @value == 'true'
@response[name] = true
else
@response[name] = false
end
when 'Marker', 'NextMarker'
@response[name] = @value
when 'MaxItems'
@response[name] = @value.to_i
end
end
end
end
end
end
end

View file

@ -0,0 +1,59 @@
module Fog
module Parsers
module CDN
module AWS
class GetStreamingDistributionList < Fog::Parsers::Base
def reset
@distribution_summary = { 'CNAME' => [], 'TrustedSigners' => [] }
@response = { 'StreamingDistributionSummary' => [] }
end
def start_element(name, attrs = [])
super
case name
when 'S3Origin'
@origin = name
@distribution_summary[@origin] = {}
end
end
def end_element(name)
case name
when 'StreamingDistributionSummary'
@response['StreamingDistributionSummary'] << @distribution_summary
@distribution_summary = { 'CNAME' => [], 'TrustedSigners' => [] }
when 'Comment', 'DomainName', 'Id', 'Status'
@distribution_summary[name] = @value
when 'CNAME'
@distribution_summary[name] << @value
when 'DNSName', 'OriginAccessIdentity'
@distribution_summary[@origin][name] = @value
when 'Enabled'
if @value == 'true'
@distribution_summary[name] = true
else
@distribution_summary[name] = false
end
when 'LastModifiedTime'
@distribution_summary[name] = Time.parse(@value)
when 'IsTruncated'
if @value == 'true'
@response[name] = true
else
@response[name] = false
end
when 'Marker', 'NextMarker'
@response[name] = @value
when 'MaxItems'
@response[name] = @value.to_i
end
end
end
end
end
end
end

View file

@ -1,7 +1,7 @@
module Fog
module Parsers
module AWS
module CDN
module CDN
module AWS
class PostInvalidation < Fog::Parsers::Base

View file

@ -0,0 +1,59 @@
module Fog
module Parsers
module CDN
module AWS
class StreamingDistribution < Fog::Parsers::Base
def reset
@response = { 'StreamingDistributionConfig' => { 'CNAME' => [], 'Logging' => {}, 'TrustedSigners' => [] } }
end
def start_element(name, attrs = [])
super
case name
when 'CustomOrigin', 'S3Origin'
@origin = name
@response['StreamingDistributionConfig'][@origin] = {}
end
end
def end_element(name)
case name
when 'AwsAccountNumber'
@response['StreamingDistributionConfig']['TrustedSigners'] << @value
when 'Bucket', 'Prefix'
@response['StreamingDistributionConfig']['Logging'][name] = @value
when 'CNAME'
@response['StreamingDistributionConfig']['CNAME'] << @value
when 'DNSName', 'OriginAccessIdentity', 'OriginProtocolPolicy'
@response['StreamingDistributionConfig'][@origin][name] = @value
when 'DomainName', 'Id', 'Status'
@response[name] = @value
when 'CallerReference', 'Comment', 'DefaultRootObject', 'Origin', 'OriginAccessIdentity'
@response['StreamingDistributionConfig'][name] = @value
when 'Enabled'
if @value == 'true'
@response['StreamingDistributionConfig'][name] = true
else
@response['StreamingDistributionConfig'][name] = false
end
when 'HTTPPort', 'HTTPSPort'
@response['StreamingDistributionConfig'][@origin][name] = @value.to_i
when 'InProgressInvalidationBatches'
@response[name] = @value.to_i
when 'LastModifiedTime'
@response[name] = Time.parse(@value)
when 'Protocol'
@response['StreamingDistributionConfig']['RequireProtocols'] = @value
when 'Self'
@response['StreamingDistributionConfig']['TrustedSigners'] << 'Self'
end
end
end
end
end
end
end

View file

@ -0,0 +1,42 @@
module Fog
module Parsers
module AWS
module CloudWatch
class GetMetricStatistics < Fog::Parsers::Base
def reset
@response = { 'GetMetricStatisticsResult' => {'Datapoints' => []}, 'ResponseMetadata' => {} }
reset_datapoint
end
def reset_datapoint
@datapoint = {}
end
def start_element(name, attrs = [])
super
end
def end_element(name)
case name
when 'Average', 'Maximum', 'Minimum', 'SampleCount', 'Sum'
@datapoint[name] = value.to_f
when 'Unit'
@datapoint[name] = value
when 'Timestamp'
@datapoint[name] = Time.parse value
when 'member'
@response['GetMetricStatisticsResult']['Datapoints'] << @datapoint
reset_datapoint
when 'Label'
@response['GetMetricStatisticsResult'][name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
end
end
end
end
end
end
end

View file

@ -0,0 +1,58 @@
module Fog
module Parsers
module AWS
module CloudWatch
class ListMetrics < Fog::Parsers::Base
def reset
@response = { 'ListMetricsResult' => {'Metrics' => []}, 'ResponseMetadata' => {} }
reset_metric
end
def reset_metric
@metric = {'Dimensions' => []}
end
def reset_dimension
@dimension = {}
end
def start_element(name, attrs = [])
super
case name
when 'Dimensions'
@in_dimensions = true
when 'member'
if @in_dimensions
reset_dimension
end
end
end
def end_element(name)
case name
when 'Name', 'Value'
@dimension[name] = value
when 'Namespace', 'MetricName'
@metric[name] = value
when 'Dimensions'
@in_dimensions = false
when 'NextMarker'
@response['ListMetricsResult'][name] = value
when 'RequestId'
@response['ResponseMetadata'][name] = value
when 'member'
if !@in_dimensions
@response['ListMetricsResult']['Metrics'] << @metric
reset_metric
else
@metric['Dimensions'] << @dimension
end
end
end
end
end
end
end
end

View file

@ -0,0 +1,26 @@
module Fog
module Parsers
module AWS
module CloudWatch
class PutMetricData < Fog::Parsers::Base
def reset
@response = { 'ResponseMetadata' => {} }
end
def start_element(name, attrs = [])
super
end
def end_element(name)
case name
when 'RequestId'
@response['ResponseMetadata'][name] = @value
end
end
end
end
end
end
end

View file

@ -1,7 +1,7 @@
module Fog
module Parsers
module AWS
module Compute
module Compute
module AWS
class AllocateAddress < Fog::Parsers::Base

View file

@ -1,7 +1,7 @@
module Fog
module Parsers
module AWS
module Compute
module Compute
module AWS
class AttachVolume < Fog::Parsers::Base

Some files were not shown because too many files have changed in this diff Show more