Skip to content

Commit

Permalink
Init aliyun.gem
Browse files Browse the repository at this point in the history
  • Loading branch information
Lax committed Dec 1, 2014
0 parents commit 8ca1464
Show file tree
Hide file tree
Showing 11 changed files with 287 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .gitignore
@@ -0,0 +1,22 @@
*.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
*.bundle
*.so
*.o
*.a
mkmf.log
4 changes: 4 additions & 0 deletions Gemfile
@@ -0,0 +1,4 @@
source 'https://rubygems.org'

# Specify gem's dependencies in aliyun.gemspec
gemspec
22 changes: 22 additions & 0 deletions LICENSE.txt
@@ -0,0 +1,22 @@
Copyright (c) 2014 Liu Lantao

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
49 changes: 49 additions & 0 deletions README.md
@@ -0,0 +1,49 @@
# Aliyun

Ruby wrapper of Aliyun API for system adminstrator.

## Installation

Add this line to your application's Gemfile:

gem 'aliyun'

And then execute:

$ bundle

Or install it yourself as:

$ gem install aliyun

## Usage

Example:

require 'rubygems'
require 'aliyun'

options = {
:access_key_id => "_YOUR_API_KEY_",
:access_key_secret => "_YOUR_API_SECRET_",
:endpoint_url => "https://ecs.aliyuncs.com/"
}

service = Aliyun::ECS::Service.new options
parameters = {}

puts service.DescribeRegions parameters

You can create/fetch `access key`/`secret` at [https://i.aliyun.com/access_key](https://i.aliyun.com/access_key)

## Contributing

1. Fork it ( https://github.com/Lax/aliyun/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## Author

* [Liu Lantao](https://github.com/Lax)
2 changes: 2 additions & 0 deletions Rakefile
@@ -0,0 +1,2 @@
require "bundler/gem_tasks"

26 changes: 26 additions & 0 deletions aliyun.gemspec
@@ -0,0 +1,26 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'aliyun/version'

Gem::Specification.new do |spec|
spec.name = "aliyun"
spec.version = Aliyun::VERSION
spec.authors = ["Liu Lantao"]
spec.email = ["liulantao@gmail.com"]
spec.summary = %q{Ruby wrapper of Aliyun API for system administrator}
spec.description = %q{Ruby wrapper of Aliyun API for system administrator.
Current for aliyun API version 2014-05-26
}
spec.homepage = "https://github.com/Lax/aliyun"
spec.license = "MIT"

spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]

spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_dependency "ruby-hmac"
end
14 changes: 14 additions & 0 deletions examples/describe_regions.rb
@@ -0,0 +1,14 @@
require 'rubygems'
require 'aliyun'

$DEBUG=false

options = {:access_key_id => "xxxxxx",
:access_key_secret => "yyyyy",
:endpoint_url => "https://ecs.aliyuncs.com/"}

service = Aliyun::ECS::Service.new options

parameters = {}

puts service.DescribeRegions parameters
3 changes: 3 additions & 0 deletions lib/aliyun.rb
@@ -0,0 +1,3 @@
require "aliyun/version"
require "aliyun/base"
require "aliyun/ecs"
19 changes: 19 additions & 0 deletions lib/aliyun/base.rb
@@ -0,0 +1,19 @@
module Aliyun
ALIYUN_API_ENDPOINT='https://ecs.aliyuncs.com/'
SEPARATOR = "&"
HTTP_METHOD = "GET"

$ENDPOINT_URL = nil
$ACCESS_KEY_ID = nil
$ACCESS_KEY_SECRET = nil

DEFAULT_PARAMETERS = {
:Format=>"JSON",
:Version=>"2014-05-26",
:SignatureMethod=>"HMAC-SHA1",
:SignatureVersion=>"1.0"
}

class AliyunAPIException < RuntimeError
end
end
123 changes: 123 additions & 0 deletions lib/aliyun/ecs.rb
@@ -0,0 +1,123 @@
require 'net/http'
require 'time'
require 'securerandom'
require 'uri'
require 'base64'
require 'hmac-sha1'
require 'json'

module Aliyun
module ECS
class Service
attr_accessor :access_key_id, :access_key_secret
attr_accessor :options
attr_accessor :endpoint_url

def initialize(options={})
self.access_key_id = options[:access_key_id] || $ACCESS_KEY_ID || ""
self.access_key_secret = options[:access_key_secret] || $ACCESS_KEY_SECRET || ""
self.endpoint_url = options[:endpoint_url] || $ENDPOINT_URL || ALIYUN_API_ENDPOINT
self.options = {:AccessKeyId => self.access_key_id}
end

def method_missing(method, *args)
if $DEBUG
puts "Not Found Method: #{method}"
end

if args[0].nil?
raise AliyunAPIException.new "Method missing: #{method}!"
end

call_aliyun_with_parameter(method, args[0])
end

#Dispatch the request with parameter
private
def call_aliyun_with_parameter(method, params)
params = gen_request_parameters method, params
uri = URI(endpoint_url)

uri.query = URI.encode_www_form(params)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == "https")

http.verify_mode = OpenSSL::SSL::VERIFY_NONE
if $DEBUG
puts "Request URI: #{uri.request_uri}"
end

request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)

case response
when Net::HTTPSuccess
return JSON.parse(response.body)
else
raise AliyunAPIException.new "Response code: #{response.code}, message: #{response.body}"
end
end

#generate the parameters
def gen_request_parameters method, params
#add common parameters
params.merge! DEFAULT_PARAMETERS

params.merge! self.options

params[:Action] = method.to_s
params[:TimeStamp] = Time.now.utc.iso8601
params[:SignatureNonce] = SecureRandom.uuid
params[:Signature] = compute_signature params

params
end

#compute the signature of the parameters String
def compute_signature params
if $DEBUG
puts "keys before sorted: #{params.keys}"
end

sorted_keys = params.keys.sort

if $DEBUG
puts "keys after sorted: #{sorted_keys}"
end

canonicalized_query_string = ""

canonicalized_query_string = sorted_keys.map {|key|
"%s=%s" % [safe_encode(key.to_s), safe_encode(params[key])]
}.join(SEPARATOR)

length = canonicalized_query_string.length

string_to_sign = HTTP_METHOD + SEPARATOR + safe_encode('/') + SEPARATOR + safe_encode(canonicalized_query_string)

if $DEBUG
puts "string_to_sign is #{string_to_sign}"
end

signature = calculate_signature access_key_secret+"&", string_to_sign
end

#calculate the signature
def calculate_signature key, string_to_sign
hmac = HMAC::SHA1.new(key)
hmac.update(string_to_sign)
signature = Base64.encode64(hmac.digest).gsub("\n", '')
if $DEBUG
puts "Signature #{signature}"
end
signature
end

#encode the value to aliyun's requirement
def safe_encode value
value = URI.encode_www_form_component(value).gsub(/\+/,'%20').gsub(/\*/,'%2A').gsub(/%7E/,'~')
end
end
end
end
3 changes: 3 additions & 0 deletions lib/aliyun/version.rb
@@ -0,0 +1,3 @@
module Aliyun
VERSION = "0.1.0"
end

0 comments on commit 8ca1464

Please sign in to comment.