fog-aliyun-0.1.0/0000755000175200017520000000000012653673664012616 5ustar rasilrasilfog-aliyun-0.1.0/Rakefile0000644000175200017520000000016512653673664014265 0ustar rasilrasilrequire "bundler/gem_tasks" require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:spec) task :default => :spec fog-aliyun-0.1.0/README.md0000644000175200017520000001747612653673664014114 0ustar rasilrasil# Fog::Aliyun ## Installation Add this line to your application's Gemfile: ```ruby gem 'fog-aliyun' ``` And then execute: ```shell $ bundle ``` Or install it yourself as: ```shell $ gem install fog-aliyun ``` ## Usage Before you can use fog-aliyun, you must require it in your application: ```ruby require 'fog/aliyun' ``` Since it's a bad practice to have your credentials in source code, you should load them from default fog configuration file: ```~/.fog```. This file could look like this: ``` default: :aliyun_accesskey_id: , :aliyun_accesskey_secret: , :aliyun_oss_endpoint: , :aliyun_oss_location: , :aliyun_oss_bucket: ``` ### Connecting to OSS ```ruby conn = Fog::Storage[:aliyun] ``` If you haven't modified your default fog configuration file or you don't want to use it, you can load your credentials by this way: ```ruby opt = { :provider => 'aliyun', :aliyun_accesskey_id => , :aliyun_accesskey_secret => , :aliyun_oss_endpoint => , :aliyun_oss_location => , :aliyun_oss_bucket => , } conn = Fog::Storage.new(opt) ``` ## Fog::Aliyun Abstractions Fog::Aliyun provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel` like interface. ### Request Layer The Fog::Storage object supports a number of methods that wrap individual HTTP requests to the OSS API. To see a list of requests supported by the storage service: conn.requests This returns: ``` [[nil, :copy_object], [nil, :delete_bucket], [nil, :delete_object], [nil, :get_bucket], [nil, :get_object], [nil, :get_object_http_url], [nil, :get_object_https_url], [nil, :head_object], [nil, :put_bucket], [nil, :put_object], [nil, :list_buckets], [nil, :list_objects], [nil, :get_containers], [nil, :get_container], [nil, :delete_container], [nil, :put_container]] ``` #### Example Requests(list_buckets) To request all of buckets: ```ruby conn.list_buckets ``` And this returns like the flowing; ``` [{"Location"=>"oss-cn-beijing", "Name"=>"dt1", "CreationDate"=>"2015-07-30T08:38:02.000Z"}, {"Location"=>"oss-cn-shenzhen", "Name"=>"ruby1", "CreationDate"=>"2015-07-30T02:22:34.000Z"}, {"Location"=>"oss-cn-qingdao", "Name"=>"yuanhang123", "CreationDate"=>"2015-05-18T03:06:31.000Z"}] ``` You can also request in this way; ```ruby conn.list_buckets(:prefix=>"pre") ``` Here is a summary of the optional parameters:
Parameters Description
:prefix The bucket name of the results must start with 'prefix'.It won't filter prefix information if not set
Data Types: String
Defaults:none
:marker The result will start from the marker alphabetically.It wil start from the first if not set.
Data Types: String
Defaults: none
:maxKeys Set the max number of the results. It will set to 100 if not set. The max value of maxKeys is 1000.
Data Types: String
Defaults: 100
To learn more about `Fog::Aliyun` request methods, you can refer to our source code. To learn more about OSS API, refer to [AliYun OSS API](https://docs.aliyun.com/?spm=5176.383663.9.2.jpghde#/pub/oss/api-reference/abstract). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
The remainder of this document details the model abstraction. **Note:** Fog sometimes refers to OSS containers as directories. ## List Directories To retrieve a list of directories: ```ruby dirs = conn.directories ``` This returns a collection of `Fog::Storage::Aliyun::Directory` models: ## Get Directory To retrieve a specific directory: ```ruby dir = dirs.get "dir" ``` This returns a `Fog::Storage::Aliyun::Directory` instance: ## Create Directory To create a directory: ```ruby dirs.create :key => 'backups' ``` ## Delete Directory To delete a directory: ```ruby directory.destroy ``` **Note**: Directory must be empty before it can be deleted. ## Directory URL To get a directory's URL: ```ruby directory.public_url ``` ## List Files To list files in a directory: ```ruby directory.files ``` **Note**: File contents is not downloaded until `body` attribute is called. ## Upload Files To upload a file into a directory: ```ruby file = directory.files.create :key => 'space.jpg', :body => File.open "space.jpg" ``` **Note**: For files larger than 5 GB please refer to the [Upload Large Files](#upload_large_files) section. ## Upload Large Files OSS requires files larger than 5 GB (the OSS default limit) to be uploaded into segments along with an accompanying manifest file. All of the segments must be uploaded to the same container. Segmented files are downloaded like ordinary files. See [Download Files](#download-files) section for more information. ## Download Files The most efficient way to download files from a private or public directory is as follows: ```ruby File.open('downloaded-file.jpg', 'w') do | f | directory.files.get("my_big_file.jpg") do | data, remaining, content_length | f.syswrite data end end ``` This will download and save the file. **Note**: The `body` attribute of file will be empty if a file has been downloaded using this method. If a file object has already been loaded into memory, you can save it as follows: ```ruby File.open('germany.jpg', 'w') {|f| f.write(file_object.body) } ``` **Note**: This method is more memory intensive as the entire object is loaded into memory before saving the file as in the example above. ## File URL To get a file's URL: ```ruby file.public_url ``` ## Copy File Cloud Files supports copying files. To copy files into a container named "trip" with a name of "europe.jpg" do the following: ```ruby file.copy("trip", "europe.jpg") ``` To move or rename a file, perform a copy operation and then delete the old file: ```ruby file.copy("trip", "germany.jpg") file.destroy ``` ## Delete File To delete a file: ```ruby file.destroy ``` ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). fog-aliyun-0.1.0/bin/0000755000175200017520000000000012653673664013366 5ustar rasilrasilfog-aliyun-0.1.0/bin/setup0000644000175200017520000000016312653673664014451 0ustar rasilrasil#!/bin/bash set -euo pipefail IFS=$'\n\t' bundle install # Do any other automated setup that you need to do here fog-aliyun-0.1.0/bin/console0000644000175200017520000000051712653673664014756 0ustar rasilrasil#!/usr/bin/env ruby require "bundler/setup" require "fog/aliyun" # You can add fixtures and/or initialization code here to make experimenting # with your gem easier. You can also use a different console, if you like. # (If you use this, don't forget to add pry to your Gemfile!) # require "pry" # Pry.start require "irb" IRB.start fog-aliyun-0.1.0/LICENSE.txt0000644000175200017520000000206412653673664014443 0ustar rasilrasilThe MIT License (MIT) Copyright (c) 2015 dengqinsi 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. fog-aliyun-0.1.0/lib/0000755000175200017520000000000012653673664013364 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/0000755000175200017520000000000012653673664014137 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/bin/0000755000175200017520000000000012653673664014707 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/bin/aliyun.rb0000644000175200017520000000135612653673664016542 0ustar rasilrasilclass Aliyun < Fog::Bin class << self def class_for(key) case key when :storage Fog::Storage::Aliyun when :compute Fog::Compute::Aliyun else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :storage Fog::Logger.warning("Aliyun[:storage] is not recommended, use Storage[:openstack] for portability") Fog::Storage.new(:provider => 'aliyun') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Aliyun.services end end end fog-aliyun-0.1.0/lib/fog/aliyun.rb0000644000175200017520000000053012653673664015763 0ustar rasilrasilrequire "fog/core" require "fog/json" require "fog/aliyun/version" module Fog module Compute ret = autoload :Aliyun, "fog/aliyun/compute" end module Storage ret = autoload :Aliyun, "fog/aliyun/storage" end module Aliyun extend Fog::Provider service(:compute, "Compute") service(:storage, "Storage") end end fog-aliyun-0.1.0/lib/fog/aliyun/0000755000175200017520000000000012653673664015440 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/aliyun/models/0000755000175200017520000000000012653673664016723 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/aliyun/models/compute/0000755000175200017520000000000012653673664020377 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/aliyun/models/compute/route_entry.rb0000644000175200017520000000276012653673664023310 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class RouteEntry < Fog::Model # "RouteTables"=>{"RouteTable"=>[ # {"CreationTime"=>"2015-08-03T11:23:35Z", "RouteEntrys"=>{"RouteEntry"=>[ # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"172.16.0.0/24"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"172.16.1.0/24"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"172.16.2.0/24"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"100.64.0.0/10"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"10.0.0.0/8"}]}, # "RouteTableId"=>"vtb-2504onoxh", "RouteTableType"=>"System", "VRouterId"=>"vrt-25azmd2wm"}]} identity :cidr_block, :aliases => 'DestinationCidrBlock' attribute :state, :aliases => 'Status' attribute :server_id, :aliases => 'InstanceId' attribute :type, :aliases => 'Type' attribute :route_table_id, :aliases => 'RouteTableId' # def save # requires :cidr_block,:route_table_id # if(cidr_block) end end end endfog-aliyun-0.1.0/lib/fog/aliyun/models/compute/security_groups.rb0000644000175200017520000000144112653673664024172 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/security_group' module Fog module Compute class Aliyun class SecurityGroups < Fog::Collection model Fog::Compute::Aliyun::SecurityGroup def all(options={}) data = Fog::JSON.decode(service.list_security_groups(options).body)['SecurityGroups']['SecurityGroup'] load(data) #['Images']['Image'] end def get(security_group_id) if security_group_id data=self.class.new(:service=>service).all() result=nil data.each do |i| if(i.id==security_group_id) result=i break end end result end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/eip_addresses.rb0000644000175200017520000000137712653673664023546 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/eip_address' module Fog module Compute class Aliyun class EipAddresses < Fog::Collection model Fog::Compute::Aliyun::EipAddress def all(filters_arg = {}) data = Fog::JSON.decode(service.list_eip_addresses(filters_arg).body)['EipAddresses']['EipAddress'] load(data) # load(data['volumeSet']) # if server # self.replace(self.select {|volume| volume.server_id == server.id}) # end # self end def get(allocation_id) if allocation_id self.class.new(:service => service).all(:allocation_id => allocation_id)[0] end end end end end endfog-aliyun-0.1.0/lib/fog/aliyun/models/compute/route_entrys.rb0000644000175200017520000000216012653673664023465 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/route_entry' module Fog module Compute class Aliyun class RouteEntrys < Fog::Collection attribute :route_table model Fog::Compute::Aliyun::RouteEntry def all(options={}) requires :route_table options[:routeTableId]=route_table.id data = Fog::JSON.decode(service.list_route_tables(route_table.v_router_id, options).body)['RouteTables']['RouteTable'][0]["RouteEntrys"]["RouteEntry"] load(data) end def get(cidr_block) requires :route_table data=self.class.new(:service=>service,:route_table=>route_table).all() result=nil data.each do |i| if i.cidr_block==cidr_block result=i break end end result end # def get(routeTableId) # requires :v_router # if routeTableId # self.class.new(:service => service,:v_router=>v_router).all(:routeTableId=>routeTableId)[0] # end # end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/security_group_rules.rb0000644000175200017520000000133212653673664025220 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/security_group_rule' module Fog module Compute class Aliyun class SecurityGroupRules < Fog::Collection model Fog::Compute::Aliyun::SecurityGroupRule attribute :security_group_id def get(security_group_id,options={}) data = Fog::JSON.decode(service.list_security_group_rules(security_group_id, options).body) self.security_group_id = data["SecurityGroupId"] permissions = data["Permissions"]["Permission"] permissions.each do |permission| permission["SecurityGroupId"] = self.security_group_id end load(permissions) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/route_table.rb0000644000175200017520000000312712653673664023234 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class RouteTable < Fog::Model # "RouteTables"=>{"RouteTable"=>[ # {"CreationTime"=>"2015-08-03T11:23:35Z", "RouteEntrys"=>{"RouteEntry"=>[ # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"172.16.0.0/24"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"172.16.1.0/24"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"172.16.2.0/24"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"100.64.0.0/10"}, # {"Status"=>"Available", "Type"=>"System", "InstanceId"=>"", "RouteTableId"=>"vtb-2504onoxh", "DestinationCidrBlock"=>"10.0.0.0/8"}]}, # "RouteTableId"=>"vtb-2504onoxh", "RouteTableType"=>"System", "VRouterId"=>"vrt-25azmd2wm"}]} identity :id, :aliases => 'RouteTableId' attribute :created_at, :aliases => 'CreationTime' attribute :type, :aliases => 'RouteTableType' attribute :v_router_id, :aliases => 'VRouterId' # collection Fog::Compute::Aliyun::RouteEntrys def route_entrys @route_entrys ||= begin Fog::Compute::Aliyun::RouteEntrys.new( :route_table => self, :service => service ) end end end end end endfog-aliyun-0.1.0/lib/fog/aliyun/models/compute/vswitch.rb0000644000175200017520000000376412653673664022425 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class Vswitch < Fog::Model identity :id, :aliases => 'VSwitchId' attribute :vpc_id, :aliases => 'VpcId' attribute :zone_id, :aliases => 'ZoneId' attribute :name, :aliases => 'VSwitchName' attribute :available_ip_count, :aliases => 'AvailableIpAddressCount' attribute :state, :aliases => 'Status' attribute :cidr_block, :aliases => 'CidrBlock' attribute :description, :aliases => 'Description' attribute :region_id, :aliases => 'RegionId' attribute :create_at, :aliases => 'CreationTime' def initialize(attributes={}) super end def ready? requires :state state == 'Available' end # Removes an existing vpc # # vpc.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :id service.delete_vswitch(id) true end # Create a vpc # # >> g = Aliyun.vpcs.new(:cidr_block => "10.1.2.0/24") # >> g.save # # == Returns: # # True or an exception depending on the result. Keep in mind that this *creates* a new vpc. # As such, it yields an InvalidGroup.Duplicate exception if you attempt to save an existing vpc. # def save(options={}) requires :vpc,:cidr_block options[:name] = name if name options[:description]=description if description data = Fog::JSON.decode(service.create_vswitch(vpc.id, cidr_block,options).body) true end def vpc $vpc end def all() data = Fog::JSON.decode(service.list_vswitchs(vpc_id).body)['VSwitches']['VSwitch'] end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/vswitches.rb0000644000175200017520000000344712653673664022753 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/vswitch' module Fog module Compute class Aliyun class Vswitches < Fog::Collection attribute :vpc model Fog::Compute::Aliyun::Vswitch # Creates a new VPC # # Aliyun.vpcs.new # # ==== Returns # # Returns the details of the new VPC # #>> Aliyun.vpcs.new # # Returns an array of all VPCs that have been created # # Aliyun.vpcs.all # # ==== Returns # # Returns an array of all VPCs # #>> Aliyun.vpcs.all # # ] # > # def all(options={}) requires :vpc data = Fog::JSON.decode(service.list_vswitchs(vpc.id, options).body)['VSwitches']['VSwitch'] load(data) end # Used to retrieve a VPC # vpc_id is required to get the associated VPC information. # # You can run the following command to get the details: # Aliyun.vpcs.get("vpc-12345678") # # ==== Returns # #>> Aliyun.vpcs.get("vpc-12345678") # # def get(vswitchId) requires :vpc if vswitchId self.class.new(:service => service,:vpc=>vpc).all(:vSwitchId=>vswitchId)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/image.rb0000644000175200017520000000460412653673664022012 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class Image < Fog::Model identity :id, :aliases => 'ImageId' attribute :description, :aliases => 'Description' attribute :product_code, :aliases => 'ProductCode' attribute :os_type, :aliases => 'OSType' attribute :architecture, :aliases => 'Architecture' attribute :os_name, :aliases => 'OSName' attribute :disk_device_mappings, :aliases => 'DiskDeviceMappings' attribute :owner_alias, :aliases => 'ImageOwnerAlias' attribute :progress, :aliases => 'Progress' attribute :usage, :aliases => 'Usage' attribute :created_at, :aliases => 'CreationTime' attribute :tags, :aliases => 'Tags' attribute :version, :aliases => 'ImageVersion' attribute :state, :aliases => 'Status' attribute :name, :aliases => 'ImageName' attribute :is_self_shared, :aliases => 'IsSelfShared' attribute :is_copied, :aliases => 'IsCopied' attribute :is_subscribed, :aliases => 'IsSubscribed' attribute :platform, :aliases => 'Platform' attribute :size, :aliases => 'Size' attribute :snapshot_id, :aliases => 'SnapshotId' def initialize(attributes) self.snapshot_id=attributes["DiskDeviceMappings"]["DiskDeviceMapping"][0]["SnapshotId"] super end def save (options={}) requires :snapshot_id options[:name] = name if name options[:description]=description if description data=Fog::JSON.decode(service.create_image(snapshot_id,options).body) merge_attributes(data) true end def destroy requires :id service.delete_image(id) true end def ready? state == 'Available' end def snapshot requires :snapshot_id Fog::Compute::Aliyun::Snapshots.new(:service=>service).all(:snapshotIds=>[snapshot_id])[0] end private def snapshot=(new_snapshot) self.snapshot_id = new_snapshot.id end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/volumes.rb0000644000175200017520000001063112653673664022417 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/volume' module Fog module Compute class Aliyun class Volumes < Fog::Collection model Fog::Compute::Aliyun::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: # Aliyun.volumes.create(:size => 10) # # ==== Returns # # # # The volume can be retrieved by running Aliyun.volumes.get("d-25ohde62o"). See get method below. # # Used to return all volumes. # Aliyun.volumes.all # # ==== Returns # #>>Aliyun.volumes.all # [{"LockReason"=>"financial"}]}, # server_id="i-25l758pg4", # device="/dev/xvdc", # delete_with_instance=false, # delete_auto_snapshot=true, # enable_auto_snapshot=true, # created_at="2015-08-03T11:35:10Z", # attached_at="2015-08-03T11:35:15Z", # detached_at="", # expired_at="2015-09-29T15:45Z", # charge_type="PostPaid", # tags={"Tag"=>[]} # > # ] # > # # The volume can be retrieved by running Aliyun.volumes.get('d-25x03nah9'). See get method below. # def all(filters_arg = {}) unless filters_arg.is_a?(Hash) Fog::Logger.deprecation("all with #{filters_arg.class} param is deprecated, use all('diskIds' => []) instead [light_black](#{caller.first})[/]") filters_arg = {'diskIds' => [*filters_arg]} end data = Fog::JSON.decode(service.list_disks(filters_arg).body)['Disks']['Disk'] load(data) # load(data['volumeSet']) # if server # self.replace(self.select {|volume| volume.server_id == server.id}) # end # self end # Used to retrieve a volume # volume_id is required to get the associated volume information. # # You can run the following command to get the details: # Aliyun.volumes.get('d-25x03nah9') # # ==== Returns # #>> Aliyun.volumes.get('d-25ohde62o') # [{"LockReason"=>"financial"}]}, # server_id="i-25l758pg4", # device="/dev/xvdc", # delete_with_instance=false, # delete_auto_snapshot=true, # enable_auto_snapshot=true, # created_at="2015-08-03T11:35:10Z", # attached_at="2015-08-03T11:35:15Z", # detached_at="", # expired_at="2015-09-29T15:45Z", # charge_type="PostPaid", # tags={"Tag"=>[]} # > # def get(volume_id) if volume_id diskIds=Array.new(1,volume_id) self.class.new(:service => service).all(:diskIds => diskIds)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/servers.rb0000644000175200017520000000301212653673664022411 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/server' module Fog module Compute class Aliyun class Servers < Fog::Collection model Fog::Compute::Aliyun::Server def all(options = {}) data = Fog::JSON.decode(service.list_servers(options).body)['Instances']['Instance'] end # Creates a new server and populates ssh keys # @return [Fog::Compute::OpenStack::Server] # @raise [Fog::Compute::OpenStack::NotFound] - HTTP 404 # @raise [Fog::Compute::OpenStack::BadRequest] - HTTP 400 # @raise [Fog::Compute::OpenStack::InternalServerError] - HTTP 500 # @raise [Fog::Compute::OpenStack::ServiceError] # @example # service.servers.bootstrap :name => 'bootstrap-server', # :flavor_ref => service.flavors.first.id, # :image_ref => service.images.find {|img| img.name =~ /Ubuntu/}.id, # :public_key_path => '~/.ssh/fog_rsa.pub', # :private_key_path => '~/.ssh/fog_rsa' # # def bootstrap(new_attributes = {}) # server = create(new_attributes) # server.wait_for { ready? } # server.setup(:password => server.password) # server # end def get(server_id) if(server_id) self.class.new(:service=>service).all(:instanceId=>server_id)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/snapshot.rb0000644000175200017520000000320212653673664022560 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class Snapshot < Fog::Model identity :id, :aliases => 'SnapshotId' attribute :name, :aliases => 'SnapshotName' attribute :description, :aliases => 'Description' attribute :progress, :aliases => 'Progress' attribute :volume_id, :aliases => 'SourceDiskId' attribute :volume_size, :aliases => 'SourceDiskSize' attribute :volume_type, :aliases => 'SourceDiskType' attribute :product_code,:aliases => 'ProductCode' attribute :created_at, :aliases => 'CreationTime' attribute :state, :aliases => 'Status' attribute :usage, :aliases => 'Usage' attribute :tags, :aliases => 'Tags' def destroy requires :id service.delete_snapshot(id) true end def ready? state == 'accomplished' end def save(options={}) # raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :volume_id options[:name] = name if name options[:description]=description if description data = Fog::JSON.decode(service.create_snapshot(volume_id, options).body) merge_attributes(data) true end def volume requires :volume_id Fog::Compute::Aliyun::Volumes.new(:service=>service).all(:diskIds=>[volume_id])[0] end private def volume=(new_volume) self.volume_id = new_volume.id end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/vrouters.rb0000644000175200017520000000315112653673664022615 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/vrouter' module Fog module Compute class Aliyun class Vrouters < Fog::Collection model Fog::Compute::Aliyun::VRouter # Returns an array of all VPCs that have been created # # Aliyun.vrouters.all # # ==== Returns # # Returns an array of all VPCs # #>> Aliyun.vrouters.all # # ] # > # def all(filters_arg = {}) unless filters_arg.is_a?(Hash) Fog::Logger.warning("all with #{filters_arg.class} param is deprecated, use all('vRouterId' => "") instead [light_black](#{caller.first})[/]") filters_arg = {'vRouterId' => filters_arg} end data = Fog::JSON.decode(service.list_vrouters(filters_arg).body)['VRouters']['VRouter'] load(data) end # Used to retrieve a VPC # vpc_id is required to get the associated VPC information. # # You can run the following command to get the details: # Aliyun.vpcs.get("vpc-12345678") # # ==== Returns # #>> Aliyun.vpcs.get("vpc-12345678") # # def get(vRouterId) if vRouterId self.class.new(:service => service).all('vRouterId' => vRouterId)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/volume.rb0000644000175200017520000000712712653673664022242 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class Volume < Fog::Model # "ImageId": "", # "InstanceId": "", # "OperationLocks": { # "OperationLock": [] # }, # "Portable": true, # "ProductCode": "", # "RegionId": "cn-qingdao", # "Size": 5, # "SourceSnapshotId": "", # "Status": "Available", # "Type": "data", identity :id, :aliases => 'DiskId' attribute :region_id, :aliases => 'RegionId' attribute :zone_id, :aliases => 'ZoneId' attribute :name, :aliases => 'DiskName' attribute :description, :aliases => 'Description' attribute :type, :aliases => 'Type' attribute :category, :aliases => 'Category' attribute :size, :aliases => 'Size' attribute :image_id, :aliases => 'ImageId' attribute :snapshot_id, :aliases => 'SourceSnapshotId' attribute :product_code, :aliases => 'ProductCode' attribute :portable, :aliases => 'Portable' attribute :state, :aliases => 'Status' attribute :operation_locks, :aliases => 'OperationLocks' attribute :server_id, :aliases => 'InstanceId' attribute :device, :aliases => 'Device' attribute :delete_with_instance, :aliases => 'DeleteWithInstance' attribute :delete_auto_snapshot, :aliases => 'DeleteAutoSnapshot' attribute :enable_auto_snapshot, :aliases => 'EnableAutoSnapshot' attribute :created_at, :aliases => 'CreationTime' attribute :attached_at, :aliases => 'AttachedTime' attribute :detached_at, :aliases => 'DetachedTime' attribute :expired_at, :aliases => 'ExpiredTime' attribute :charge_type, :aliases => 'DiskChargeType' attribute :tags, :aliases => 'Tags' def destroy requires :id service.delete_disk(id) true end def ready? requires :state state == 'Available' end def save(options={}) # raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? # requires :availability_zone requires_one :size, :snapshot_id options[:name] = name if name options[:description]=description if description if snapshot_id data=Fog::JSON.decode(service.create_disk_by_snapshot(snapshot_id,options).body) merge_attributes(data) elsif size data = Fog::JSON.decode(service.create_disk(size,options).body) merge_attributes(data) end true end def image requires :image_id Fog::Compute::Aliyun::Images.new(:service=>service).all(:imageId=>image_id)[0] end def snapshots requires :id Fog::Compute::Aliyun::Snapshots.new(:service=>service).all(:volume_id=>id) end def source requires :snapshot_id Fog::Compute::Aliyun::Snapshots.new(:service=>service).all(:snapshotIds => [snapshot_id])[0] end private def source=(new_source) self.snapshot_id=new_source.id end def image=(new_image) self.image_id = new_image.id end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/images.rb0000644000175200017520000000144312653673664022173 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/image' module Fog module Compute class Aliyun class Images < Fog::Collection model Fog::Compute::Aliyun::Image def all(filters_arg = {}) unless filters_arg.is_a?(Hash) Fog::Logger.deprecation("all with #{filters_arg.class} param is deprecated, use all('diskIds' => []) instead [light_black](#{caller.first})[/]") filters_arg = {:imageId => filters_arg} end data = Fog::JSON.decode(service.list_images(filters_arg).body)['Images']['Image'] load(data) end def get(image_id) if image_id self.class.new(:service => service).all(:imageId => image_id)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/snapshots.rb0000644000175200017520000000241512653673664022750 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/snapshot' module Fog module Compute class Aliyun class Snapshots < Fog::Collection # attribute :filters model Fog::Compute::Aliyun::Snapshot # def initialize(attributes) # self.filters ||= {} # super # end def all(filters_arg = {}) unless filters_arg.is_a?(Hash) Fog::Logger.deprecation("all with #{filters_arg.class} param is deprecated, use all('snapshotIds' => []) instead [light_black](#{caller.first})[/]") filters_arg = {'snapshotIds' => [*filters_arg]} end volume_id = filters_arg[:volume_id] volume_type = filters_arg[:volume_type] if volume_id filters_arg[:diskId]=volume_id end if volume_type filters_arg[:sourseDiskType]=volume_type end data = Fog::JSON.decode(service.list_snapshots(filters_arg).body)['Snapshots']['Snapshot'] load(data) end def get(snapshot_id) if snapshot_id snapshotIds=Array.new(1,snapshot_id) self.class.new(:service => service).all(:snapshotIds => snapshotIds)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/server.rb0000644000175200017520000001001112653673664022223 0ustar rasilrasilrequire 'fog/compute/models/server' module Fog module Compute class Aliyun class Server < Fog::Compute::Server identity :id, :aliases=>'InstanceId' attribute :image_id, :aliases => 'ImageId' attribute :inner_ip, :aliases => 'InnerIpAddress' attribute :vlan_id, :aliases => 'VlanId' attribute :eip, :aliases => 'EipAddress' attribute :max_bandwidth_in, :aliases => 'InternetMaxBandwidthIn' attribute :zone_id, :aliases => 'ZoneId' attribute :internet_charge_type, :aliases => 'InternetChargeType' attribute :serial_number, :aliases => 'SerialNumber' attribute :io_optimized, :aliases => 'IoOptimized' attribute :max_bandwidth_out, :aliases => 'InternetMaxBandwidthOut' attribute :vpc_attributes, :aliases => 'VpcAttributes' attribute :device_available, :aliases => 'DeviceAvailable' attribute :private_ip, :aliases => 'PrivateIpAddress' attribute :security_group_ids,:aliases => 'SecurityGroupIds' attribute :name, :aliases => 'InstanceName' attribute :description, :aliases => 'Description' attribute :network_type, :aliases => 'InstanceNetworkType' attribute :public_ip, :aliases => 'PublicIpAddress' attribute :host_name, :aliases => 'HostName' attribute :type, :aliases => 'InstanceType' attribute :created_at, :aliases => 'CreationTime' attribute :state, :aliases => 'Status' attribute :cluster_id, :aliases => 'ClusterId' attribute :region_id, :aliases => 'RegionId' attribute :charge_type, :aliases => 'InstanceChargeType' attribute :operation_locks, :aliases => 'OperationLocks' attribute :expired_at, :aliases => 'ExpiredTime' def image requires image_id Fog::Compute::Aliyun::Image.new(:service=>service).all(:imageId => image_id)[0] end def vpc requires :vpc_id $vpc=Fog::Compute::Aliyun::Vpcs.new(:service=>service).all('vpcId'=>vpc_id)[0] end # {"ImageId"=>"ubuntu1404_32_20G_aliaegis_20150325.vhd", "InnerIpAddress"=>{"IpAddress"=>["10.171.90.171"]}, # "VlanId"=>"", "InstanceId"=>"i-25d1ry3jz", # "EipAddress"=>{"IpAddress"=>"", "AllocationId"=>"", "InternetChargeType"=>""}, # "InternetMaxBandwidthIn"=>-1, "ZoneId"=>"cn-beijing-a", "InternetChargeType"=>"PayByTraffic", # "SerialNumber"=>"9b332890-35e8-45c9-8e52-14e1156a4f58", "IoOptimized"=>false, "InternetMaxBandwidthOut"=>1, # "VpcAttributes"=>{"NatIpAddress"=>"", "PrivateIpAddress"=>{"IpAddress"=>[]}, "VSwitchId"=>"", "VpcId"=>""}, # "DeviceAvailable"=>true, "SecurityGroupIds"=>{"SecurityGroupId"=>["sg-25rgacf5p"]}, "InstanceName"=>"iZ25d1ry3jzZ", # "Description"=>"", "InstanceNetworkType"=>"classic", "PublicIpAddress"=>{"IpAddress"=>["123.57.73.19"]}, # "HostName"=>"iZ25d1ry3jzZ", "InstanceType"=>"ecs.t1.small", "CreationTime"=>"2015-10-13T14:57Z", "Status"=>"Stopped", # "ClusterId"=>"", "RegionId"=>"cn-beijing", "InstanceChargeType"=>"PostPaid", "OperationLocks"=>{ # "LockReason"=>[{"LockReason"=>"financial"}]}, "ExpiredTime"=>"2015-10-14T20:53Z"} # @!attribute [rw] personality # @note This attribute is only used for server creation. This field will be nil on subsequent retrievals. # @return [Hash] Hash containing data to inject into the file system of the cloud server instance during server creation. # @example To inject fog.txt into file system # :personality => [{ :path => '/root/fog.txt', # :contents => Base64.encode64('Fog was here!') # }] # @see #create # @see http://docs.openstack.org/api/openstack-compute/2/content/Server_Personality-d1e2543.html end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/eip_address.rb0000644000175200017520000000353112653673664023210 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class EipAddress < Fog::Model identity :id, :aliases => 'AllocationId' attribute :allocated_at, :aliases => 'AllocationTime' attribute :bandwidth, :aliases => 'Bandwidth' attribute :server_id, :aliases => 'InstanceId' attribute :charge_type, :aliases => 'InternetChargeType' attribute :ip_address, :aliases => ['IpAddress','EipAddress'] attribute :opertion_locks,:aliases => 'OperationLocks' attribute :region_id, :aliases => 'RegionId' attribute :state, :aliases => 'Status' def destroy requires :id service.release_eip_address(id) true end def ready? requires :state state == 'Available' end def save(options={}) # raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? # requires :availability_zone options[:bandwidth] = bandwidth if bandwidth options[:internet_charge_type]=charge_type if charge_type data = Fog::JSON.decode(service.allocate_eip_address(options).body) merge_attributes(data) true end def associate(new_server,options={}) unless persisted? @server = new_server else @server = nil self.server_id = new_server.id service.associate_eip_address(server_id,id,options) end end def disassociate(new_server,options={}) @server = nil self.server_id = new_server.id if persisted? service.unassociate_eip_address(server_id,id,options) end end end end end endfog-aliyun-0.1.0/lib/fog/aliyun/models/compute/vrouter.rb0000644000175200017520000000222412653673664022432 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class VRouter < Fog::Model identity :id, :aliases => 'VRouterId' attribute :name, :aliases => 'VRouterName' attribute :route_table_ids, :aliases => 'RouteTableIds' attribute :created_at, :aliases => 'CreationTime' attribute :description, :aliases => 'Description' attribute :region_id, :aliases => 'RegionId' attribute :vpc_id, :aliases => 'VpcId' def vpc requires :vpc_id $vpc=Fog::Compute::Aliyun::Vpcs.new(:service=>service).all('vpcId'=>vpc_id)[0] end def route_tables @route_tables ||= begin Fog::Compute::Aliyun::RouteTables.new( :v_router => self, :service => service ) end end end end end end # "VRouters"=>{"VRouter"=>[{"VRouterName"=>"", "RouteTableIds"=>{"RouteTableId"=>["vtb-2504onoxh"]}, # "CreationTime"=>"2015-08-03T11:23:35Z", "Description"=>"", "RegionId"=>"cn-beijing", # "VRouterId"=>"vrt-25azmd2wm", "VpcId"=>"vpc-25mj6mguq"}]}fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/vpc.rb0000644000175200017520000000433012653673664021514 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class VPC < Fog::Model identity :id, :aliases => 'VpcId' attribute :name, :aliases => 'VpcName' attribute :state, :aliases => 'Status' attribute :cidr_block, :aliases => 'CidrBlock' attribute :v_switch_ids, :aliases => 'VSwitchIds' attribute :description, :aliases => 'Description' attribute :user_cidrs, :aliases => 'UserCidrs' attribute :region_id, :aliases => 'RegionId' attribute :v_router_id, :aliases => 'VRouterId' attribute :create_at, :aliases => 'CreationTime' def ready? requires :state state == 'Available' end # Removes an existing vpc # # vpc.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :id service.delete_vpc(id) true end def vswitches @vswitches ||= begin Fog::Compute::Aliyun::Vswitches.new( :vpc => self, :service => service ) end end def vrouter requires :v_router_id Fog::Compute::Aliyun::Vrouters.new(:service=>service).all('vRouterId'=>v_router_id)[0] end def security_groups requires :id Fog::Compute::Aliyun::SecurityGroups.new(:service=>service).all(:vpcId=>id) end # Create a vpc # # >> g = Aliyun.vpcs.new(:cidr_block => "10.1.2.0/24") # >> g.save # # == Returns: # # True or an exception depending on the result. Keep in mind that this *creates* a new vpc. # As such, it yields an InvalidGroup.Duplicate exception if you attempt to save an existing vpc. # def save(options={}) requires :cidr_block options[:name]=name if name options[:description]=description if description data = Fog::JSON.decode(service.create_vpc(cidr_block,options).body) true end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/security_group.rb0000644000175200017520000000500512653673664024007 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class SecurityGroup < Fog::Model identity :id, :aliases =>"SecurityGroupId" attribute :name, :aliases => "SecurityGroupName" attribute :description, :aliases => "Description" attribute :created_at, :aliases => "CreationTime" attribute :vpc_id, :aliases => "VpcId" def vpc requires :vpc_id service.vpcs.get(vpc_id) end def security_group_rules requires :id service.security_group_rules.get(id) end def save(options={}) options[:vpcId] = vpc_id if vpc_id options[:name] = name if name options[:description] = description if description Fog::JSON.decode(service.create_security_group(options).body) true end def destroy requires :id service.delete_security_group(id) true end def authorize_security_group_sg_rule(group_id,direction="ingress",options={}) requires :id if direction=="egress" service.create_security_group_egress_sg_rule(id,group_id,options) else service.create_security_group_sg_rule(id,group_id,options) end true end def authorize_security_group_ip_rule(cidr_ip,direction="ingress",options={}) requires :id nic_type = options.fetch(:nic_type, "internet") if direction=="egress" service.create_security_group_egress_ip_rule(id,cidr_ip,nic_type,options) else service.create_security_group_ip_rule(id,cidr_ip,nic_type,options) end true end def revoke_seurity_group_sg_rule(group_id,direction="ingress",options={}) requires :id if direction=="egress" service.delete_security_group_egress_sg_rule(id,group_id,options) else service.delete_security_group_sg_rule(id,group_id,options) end true end def revoke_security_group_ip_rule(cidr_ip,direction="ingress",options={}) requires :id nic_type = options.fetch(:nic_type, "internet") if direction=="egress" service.delete_security_group_egress_ip_rule(id,cidr_ip,nic_type,options) else service.delete_security_group_ip_rule(id,cidr_ip,nic_type,options) end true end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/route_tables.rb0000644000175200017520000000126612653673664023421 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/route_table' module Fog module Compute class Aliyun class RouteTables < Fog::Collection attribute :v_router model Fog::Compute::Aliyun::RouteTable def all(options={}) requires :v_router data = Fog::JSON.decode(service.list_route_tables(v_router.id, options).body)['RouteTables']['RouteTable'] load(data) end def get(routeTableId) requires :v_router if routeTableId self.class.new(:service => service,:v_router=>v_router).all(:routeTableId=>routeTableId)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/vpcs.rb0000644000175200017520000000364712653673664021711 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/compute/vpc' module Fog module Compute class Aliyun class Vpcs < Fog::Collection model Fog::Compute::Aliyun::VPC # Creates a new VPC # # Aliyun.vpcs.new # # ==== Returns # # Returns the details of the new VPC # #>> Aliyun.vpcs.new # # # Returns an array of all VPCs that have been created # # Aliyun.vpcs.all # # ==== Returns # # Returns an array of all VPCs # #>> Aliyun.vpcs.all # # ] # > # def all(filters_arg = {}) unless filters_arg.is_a?(Hash) Fog::Logger.warning("all with #{filters_arg.class} param is deprecated, use all('vpcId' => []) instead [light_black](#{caller.first})[/]") filters_arg = {'vpcId' => [*filters_arg]} end data = Fog::JSON.decode(service.list_vpcs(filters_arg).body)['Vpcs']['Vpc'] load(data) end # Used to retrieve a VPC # vpc_id is required to get the associated VPC information. # # You can run the following command to get the details: # Aliyun.vpcs.get("vpc-12345678") # # ==== Returns # #>> Aliyun.vpcs.get("vpc-12345678") # # def get(vpcId) if vpcId $vpc=self.class.new(:service => service).all('vpcId' => vpcId)[0] end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/compute/security_group_rule.rb0000644000175200017520000000423512653673664025042 0ustar rasilrasilrequire 'fog/core/model' module Fog module Compute class Aliyun class SecurityGroupRule < Fog::Model attribute :security_group_id, :aliases => 'SecurityGroupId' attribute :source_cidr_ip, :aliases => 'SourceCidrIp' attribute :source_owner, :aliases => 'SourceGroupOwnerAccount' attribute :source_group_id, :aliases => 'SourceGroupId' attribute :ip_protocol, :aliases => 'IpProtocol' attribute :dest_cidr_ip, :aliases => 'DestCidrIp' attribute :dest_owner, :aliases => 'DestGroupOwnerAccount' attribute :dest_group_id, :aliases => 'DestGroupId' attribute :nic_type, :aliases => 'NicType' attribute :policy, :aliases => 'Policy' attribute :port_range, :aliases => 'PortRange' attribute :direction, :aliases => 'Direction' attribute :priority, :aliases => 'Priority' def save requires :security_group_id,:ip_protocol,:port_range,:direction options={} options[:portRange] = port_range if port_range options[:policy] = policy if policy options[:priority] = priority if port_range options[:protocol] = ip_protocol if ip_protocol if direction=="egress" if dest_cidr_ip service.create_security_group_egress_ip_rule(security_group_id,dest_cidr_ip,nic_type,options) elsif dest_group_id options[:destGroupOwnerAccount] = dest_owner if dest_owner service.create_security_group_egress_sg_rule(security_group_id,dest_group_id,options) end else if source_cidr_ip service.create_security_group_ip_rule(security_group_id,source_cidr_ip,nic_type,options) elsif source_group_id options[:sourceGroupOwnerAccount] = source_owner if source_owner service.create_security_group_sg_rule(security_group_id,source_group_id,options) end end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/storage/0000755000175200017520000000000012653673664020367 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/aliyun/models/storage/directory.rb0000644000175200017520000000200612653673664022716 0ustar rasilrasilrequire 'fog/core/model' require 'fog/aliyun/models/storage/files' module Fog module Storage class Aliyun class Directory < Fog::Model identity :key def destroy requires :key prefix = key+'/' ret = service.list_objects(:prefix=>prefix)["Contents"] if ret.nil? puts " Not found: Direction not exist!" false elsif ret.size == 1 service.delete_container(key) true else raise Fog::Storage::Aliyun::Error, " Forbidden: Direction not empty!" false end end def files @files ||= begin Fog::Storage::Aliyun::Files.new( :directory => self, :service => service ) end end def public_url nil end def save requires :key service.put_container(key) true end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/storage/files.rb0000644000175200017520000001441712653673664022025 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/storage/file' module Fog module Storage class Aliyun class Files < Fog::Collection attribute :directory attribute :limit attribute :marker attribute :path attribute :prefix model Fog::Storage::Aliyun::File def all(options = {}) requires :directory if directory.key != "" && directory.key != "." && directory.key != nil prefix = directory.key+"/" end files = service.list_objects({:prefix => prefix})["Contents"] if nil == files return end data = Array.new i = 0 files.each do |file| if file["Key"][0][-1] != "/" content_length = file["Size"][0].to_i key = file["Key"][0] lastModified = file["LastModified"][0] if lastModified != nil && lastModified != "" last_modified = (Time.parse(lastModified)).localtime else last_modified = nil end type = file["Type"][0] data[i] = {:content_length => content_length, :key => key, :last_modified => last_modified, :etag => file["ETag"][0], :object_type => type} i = i + 1 end end load(data) end alias_method :each_file_this_page, :each def each if !block_given? self else subset = dup.all subset.each_file_this_page {|f| yield f} while subset.length == (subset.limit || 10000) subset = subset.all(:marker => subset.last.key) subset.each_file_this_page {|f| yield f} end self end end def get(key, &block) requires :directory if directory.key == "" object = key else object = directory.key+"/"+key end if block_given? pagesNum = (contentLen + Excon::CHUNK_SIZE - 1)/Excon::CHUNK_SIZE for i in 1..pagesNum _start = (i-1)*(Excon::CHUNK_SIZE) _end = i*(Excon::CHUNK_SIZE) - 1 range = "#{_start}-#{_end}" data = service.get_object(object, range) chunk = data[:body] yield(chunk) body = nil end else data = service.get_object(object) body = data[:body] end contentLen = data[:headers]["Content-Length"].to_i if data[:status] != 200 return nil end lastModified = data[:headers]["Last-Modified"] if lastModified != nil && lastModified != "" last_modified = (Time.parse(lastModified)).localtime else last_modified = nil end date = data[:headers]["Date"] if date != nil && date != "" date = (Time.parse(date)).localtime else date = nil end file_data = { :body => body, :content_length => contentLen, :key => key, :last_modified => last_modified, :content_type => data[:headers]["Content-Type"], :etag => data[:headers]["ETag"], :date => date, :connection => data[:headers]["Connection"], :accept_ranges => data[:headers]["Accept-Ranges"], :server => data[:headers]["Server"], :object_type => data[:headers]["x-oss-object-type"], :content_disposition => data[:headers]["Content-Disposition"] } new(file_data) end def get_url(key) requires :directory if directory.key == "" object = key else object = directory.key+"/"+key end service.get_object_http_url_public(object, 3600) end def get_http_url(key, expires, options = {}) requires :directory if directory.key == "" object = key else object = directory.key+"/"+key end service.get_object_http_url_public(object, expires, options) end def get_https_url(key, expires, options = {}) requires :directory if directory.key == "" object = key else object = directory.key+"/"+key end service.get_object_https_url_public(object, expires, options) end def head(key, options = {}) requires :directory if directory.key == "" object = key else object = directory.key+"/"+key end data = service.head_object(object).data lastModified = data[:headers]["Last-Modified"] if lastModified != nil && lastModified != "" last_modified = (Time.parse(lastModified)).localtime else last_modified = nil end date = data[:headers]["Date"] if date != nil && date != "" date = (Time.parse(date)).localtime else date = nil end file_data = { :content_length => data[:headers]["Content-Length"].to_i, :key => key, :last_modified => last_modified, :content_type => data[:headers]["Content-Type"], :etag => data[:headers]["ETag"], :date => date, :connection => data[:headers]["Connection"], :accept_ranges => data[:headers]["Accept-Ranges"], :server => data[:headers]["Server"], :object_type => data[:headers]["x-oss-object-type"] } new(file_data) rescue Fog::Storage::Aliyun::NotFound nil end def new(attributes = {}) requires :directory super({ :directory => directory }.merge!(attributes)) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/storage/directories.rb0000644000175200017520000000201112653673664023222 0ustar rasilrasilrequire 'fog/core/collection' require 'fog/aliyun/models/storage/directory' module Fog module Storage class Aliyun class Directories < Fog::Collection model Fog::Storage::Aliyun::Directory def all containers = service.get_containers() if nil == containers return nil end data = Array.new i = 0 containers.each do |entry| key = entry["Prefix"][0] key[-1] = '' data[i] = {:key=>key} i = i + 1 end load(data) end def get(key, options = {}) if key != nil && key != "" && key != '.' dir = key+'/' ret = service.head_object(dir, options) if ret.data[:status] == 200 new(:key => key) else nil end else new(:key => "") end rescue Fog::Storage::Aliyun::NotFound nil end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/models/storage/file.rb0000644000175200017520000001361512653673664021641 0ustar rasilrasilrequire 'fog/core/model' module Fog module Storage class Aliyun class File < Fog::Model identity :key, :aliases => 'name' attribute :date, :aliases => 'Date' attribute :content_length, :aliases => 'Content-Length', :type => :integer attribute :content_type, :aliases => 'Content-Type' attribute :connection, :aliases => 'Connection' attribute :content_disposition, :aliases => 'Content-Disposition' attribute :etag, :aliases => 'Etag' attribute :last_modified, :aliases => 'Last-Modified', :type => :time attribute :accept_ranges, :aliases => 'Accept-Ranges' attribute :server, :aliases => 'Server' attribute :object_type, :aliases => 'x-oss-object-type' def body attributes[:body] ||= if last_modified collection.get(identity).body else '' end end def body=(new_body) attributes[:body] = new_body end def directory @directory end def copy(target_directory_key, target_file_key, options={}) requires :directory, :key if directory.key == "" source_object = key else source_object = directory.key+"/"+key end if target_directory_key == "" target_object = target_file_key else target_object = target_directory_key+"/"+target_file_key end service.copy_object(nil, source_object, nil, target_object, options) target_directory = service.directories.new(:key => target_directory_key) target_directory.files.get(target_file_key) end def destroy requires :directory, :key if directory.key == "" object = key else object = directory.key+"/"+key end service.delete_object(object) true end def metadata attributes[:metadata] ||= headers_to_metadata end def owner=(new_owner) if new_owner attributes[:owner] = { :display_name => new_owner['DisplayName'], :id => new_owner['ID'] } end end def public=(new_public) new_public end # Get a url for file. # # required attributes: directory, key # # @param expires [String] number of seconds (since 1970-01-01 00:00) before url expires # @param options [Hash] # @return [String] url # def url(expires, options = {}) requires :directory, :key if directory.key == "" object = key else object = directory.key+"/"+key end self.service.get_object_http_url_public(object, expires, options) end def public_url requires :key self.collection.get_url(self.key) end def save(options = {}) requires :body, :directory, :key options['Content-Type'] = content_type if content_type options['Content-Disposition'] = content_disposition if content_disposition options['Access-Control-Allow-Origin'] = access_control_allow_origin if access_control_allow_origin options['Origin'] = origin if origin options.merge!(metadata_to_headers) if directory.key == "" object = key else object = directory.key+"/"+key end if body.is_a?(::File) data = service.put_object(object, body, options).data elsif body.is_a?(String) data = service.put_object_with_body(object, body, options).data else raise Fog::Storage::Aliyun::Error, " Forbidden: Invalid body type: #{body.class}!" end update_attributes_from(data) refresh_metadata self.content_length = Fog::Storage.get_body_size(body) self.content_type ||= Fog::Storage.get_content_type(body) true end private def directory=(new_directory) @directory = new_directory end def refresh_metadata metadata.reject! {|k, v| v.nil? } end def headers_to_metadata key_map = key_mapping Hash[metadata_attributes.map {|k, v| [key_map[k], v] }] end def key_mapping key_map = metadata_attributes key_map.each_pair {|k, v| key_map[k] = header_to_key(k)} end def header_to_key(opt) opt.gsub(metadata_prefix, '').split('-').map {|k| k[0, 1].downcase + k[1..-1]}.join('_').to_sym end def metadata_to_headers header_map = header_mapping Hash[metadata.map {|k, v| [header_map[k], v] }] end def header_mapping header_map = metadata.dup header_map.each_pair {|k, v| header_map[k] = key_to_header(k)} end def key_to_header(key) metadata_prefix + key.to_s.split(/[-_]/).map(&:capitalize).join('-') end def metadata_attributes if last_modified if directory.key == "" object = key else object = directory.key+"/"+key end headers = service.head_object(object).data[:headers] headers.reject! {|k, v| !metadata_attribute?(k)} else {} end end def metadata_attribute?(key) key.to_s =~ /^#{metadata_prefix}/ end def metadata_prefix "X-Object-Meta-" end def update_attributes_from(data) merge_attributes(data[:headers].reject {|key, value| ['Content-Length', 'Content-Type'].include?(key)}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/0000755000175200017520000000000012653673664017313 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/0000755000175200017520000000000012653673664020767 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/start_server.rb0000644000175200017520000000236612653673664024046 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Start the server. # # === Parameters # * server_id <~String> - The ID of the server to be started. # === Returns # * success <~Boolean> # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&staetinstance] def start_server(server_id) _action = 'StartInstance' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId']=server_id _pathURL += '&InstanceId='+server_id _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end # def start_server end # class Real class Mock def start_server(server_id) true end # def start_server end # class Mock end # class aliyun end # module Compute end # module Fogfog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_disk.rb0000644000175200017520000000436112653673664023574 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Delete a disk By the given id. # # ==== Parameters # * diskId<~String> - the disk_id # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/disk&deletedisk] def delete_disk(diskId) action = 'DeleteDisk' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["DiskId"] = diskId pathUrl += '&DiskId=' pathUrl += diskId signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group(name, description) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::V2::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i + 1 self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/modify_vswitch.rb0000644000175200017520000000457412653673664024364 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&modifyvswitchattribute] def modify_vpc(vSwitchId,options={}) action = 'ModifyVSwitchAttribute' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["VSwitchId"] = vSwitchId pathUrl += '&VSwitchId=' pathUrl += URI.encode(vpcId,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') name = options[:name] desc = options[:description] if name parameters["VSwitchName"] = name pathUrl += '&VSwitchName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def modify_vpc(vpcId, options={}) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::V2::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i + 1 self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/associate_eip_address.rb0000644000175200017520000000433712653673664025640 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Associate an avalable eip IP address to the given instance. # # ==== Parameters # * server_id<~String> - id of the instance # * allocationId<~String> - id of the EIP # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/network&associateeipaddresss] def associate_eip_address(server_id, allocationId,options={}) _action = 'AssociateEipAddress' _sigNonce = randonStr() _time = Time.new.utc type=options['instance_type'] _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId'] = server_id _pathURL += '&InstanceId='+server_id _parameters['AllocationId'] = allocationId _pathURL += '&AllocationId='+allocationId if type _parameters['InstanceType'] = type _pathURL += 'InstanceType='+type end _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def allocate_address(pool = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool"=>"nova" } } response end end # mock end # aliyun end #compute end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_disk.rb0000644000175200017520000001371012653673664023573 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Create a disk with assigned size. # # ==== Parameters # * size<~String> - the size of the disk (GB).--cloud:5~2000GB,cloud_efficiency: 20~2048GB,cloud_ssd:20~1024GB # * options<~hash> # * :name - The name of the disk,default nil. If not nil, it must start with english or chinise character. # The length should be within [2,128]. It can contain digits,'.','_' or '-'.It shouldn't start with 'http://' or 'https://' # * :description - The name of the disk,default nil. If not nil, the length should be within [2,255].It shouldn't start with 'http://' or 'https://' # * :category - Default 'cloud'. can be set to 'cloud','cloud_efficiency' or 'cloud_ssd' # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # * 'DiskId'<~String> - Id of the created disk # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/disk&createdisk] def create_disk(size, options={}) action = 'CreateDisk' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["ZoneId"] = @aliyun_zone_id pathUrl += '&ZoneId=' pathUrl += @aliyun_zone_id parameters["Size"] = size pathUrl += '&Size=' pathUrl += size name = options[:name] desc = options[:description] category = options[:category] if name parameters["DiskName"] = name pathUrl += '&DiskName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end if category parameters["DiskCategory"] = category pathUrl += 'DiskCategory' pathUrl += category end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ).merge(options) end # Create a disk By the snapshot with given snapshot_id. # # ==== Parameters # * snapshotId<~String> - the snapshot_id # * options<~hash> # * :name - The name of the disk,default nil. If not nil, it must start with english or chinise character. # The length should be within [2,128]. It can contain digits,'.','_' or '-'.It shouldn't start with 'http://' or 'https://' # * :description - The name of the disk,default nil. If not nil, the length should be within [2,255].It shouldn't start with 'http://' or 'https://' # * :category - Default 'cloud'. can be set to 'cloud','cloud_efficiency' or 'cloud_ssd' # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # * 'DiskId'<~String> - Id of the created disk # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/disk&createdisk] def create_disk_by_snapshot(snapshotId, options={}) action = 'CreateDisk' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["ZoneId"] = @aliyun_zone_id pathUrl += '&ZoneId=' pathUrl += @aliyun_zone_id parameters["SnapshotId"] = snapshotId pathUrl += '&SnapshotId=' pathUrl += snapshotId name = options[:name] desc = options[:description] category = options[:category] if name parameters["DiskName"] = name pathUrl += '&DiskName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end if category parameters["DiskCategory"] = category pathUrl += 'DiskCategory' pathUrl += category end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group(name, description) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::V2::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i + 1 self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/reboot_server.rb0000644000175200017520000000236712653673664024204 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&rebootinstance] def reboot_server(server_id, options = {}) _action = 'RebootInstance' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId']=server_id _pathURL += '&InstanceId='+server_id _ForceStop = options[:aliyun_ForceStop] if _ForceStop _parameters['ForceStop']=_ForceStop _pathURL += '&ForceStop='+_ForceStop end _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def reboot_server(server_id, type = 'SOFT') response = Excon::Response.new response.status = 202 response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_disks.rb0000644000175200017520000001315512653673664023471 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Describe disks. # # ==== Parameters # * options<~hash> # * :diskIds - arry of diskId, the length of arry should less than or equal to 100. # * :instanceId - id of the instance # * :diskType - Default 'all'.Can be set to all | system | data # * :category - Default 'all'. Can be set to all | cloud | cloud_efficiency | cloud_ssd | ephemeral | ephemeral_ssd # * :state - status of the disk. Default 'All'. Can be set to In_use | Available | Attaching | Detaching | Creating | ReIniting | All # * :snapshotId - id of snapshot which used to create disk. # * :name - name of disk # * :portable - If ture, can exist dependently,which means it can be mount or umont in available zones. # Else, it must be created or destroyed with a instance. # The value for ocal disks and system disks on the cloud and cloud disks paid by month must be false. # * :delWithIns - If ture, the disk will be released when the instance is released. # * :delAutoSna - If ture, the auto created snapshot will be destroyed when the disk is destroyed # * :enAutoSna - Whether the disk apply the auto snapshot strategy. # * :diskChargeType - Prepaid | Postpaid # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # * 'Disks'<~Hash> - list of Disk,and the parameter of disk refer to the Volume model # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/disk&describedisks] def list_disks(options={}) action = 'DescribeDisks' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) pageNumber = options[:pageNumber] pageSize = options[:pageSize] instanceId = options[:instanceId] diskIds = options[:diskIds] diskType = options[:diskType] category = options[:category] state = options[:state] snapshotId = options[:snapshotId] name = options[:name] portable = options[:portable] delWithIns = options[:deleteWithInstance] delAutoSna = options[:deleteAutoSnapshot] enAutoSna = options[:enableAutoSnapshot] diskChargeType = options[:diskChargeType] if diskChargeType parameters["DiskChargeType"] = diskChargeType pathUrl += '&DiskChargeType=' pathUrl += diskChargeType end if enAutoSna parameters["EnableAutoSnapshot"] = enAutoSna pathUrl += '&EnableAutoSnapshot=' pathUrl += enAutoSna end if delAutoSna parameters["DeleteAutoSnapshot"] = delAutoSna pathUrl += '&DeleteAutoSnapshot=' pathUrl += delAutoSna end if delWithIns parameters["DeleteWithInstance"] = delWithIns pathUrl += '&DeleteWithInstance=' pathUrl += delWithIns end if portable parameters["Portable"] = portable pathUrl += '&Portable=' pathUrl += portable end if name parameters["DiskName"] = name pathUrl += '&DiskName=' pathUrl += name end if snapshotId parameters["SnapshotId"] = snapshotId pathUrl += '&SnapshotId=' pathUrl += snapshotId end if state parameters["Status"] = state pathUrl += '&Status=' pathUrl += state end if category parameters["DiskType"] = diskType pathUrl += '&DiskType=' pathUrl += diskType end if category parameters["Category"] = category pathUrl += '&Category=' pathUrl += category end if instanceId parameters["InstanceId"] = instanceId pathUrl += '&InstanceId=' pathUrl += instanceId end if diskIds parameters["DiskIds"] = Fog::JSON.encode(diskIds) pathUrl += '&DiskIds=' pathUrl += Fog::JSON.encode(diskIds) end if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end pageSize = options[:pageSize] unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_zones(*args) Excon::Response.new( :body => { "availabilityZoneInfo" => [ { "zoneState" => { "available" => true }, "hosts" => nil, "zoneName" => "nova" } ] }, :status => 200 ) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/detach_disk.rb0000644000175200017520000000321412653673664023556 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/disk&detachdisk] def detach_disk(instanceId, diskId,options={}) action = 'DetachDisk' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["InstanceId"] = instanceId pathUrl += '&InstanceId=' pathUrl += instanceId parameters["DiskId"] = diskId pathUrl += '&DiskId=' pathUrl += diskId if device parameters["Device"] = device pathUrl += '&Device=' pathUrl += URI.encode(device,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def attach_volume(volume_id, server_id, device) response = Excon::Response.new response.status = 200 data = { 'id' => volume_id, 'volumeId' => volume_id, 'serverId' => server_id, 'device' => device } self.data[:volumes][volume_id]['attachments'] << data response.body = { 'volumeAttachment' => data } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_eip_addresses.rb0000644000175200017520000000463512653673664025171 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/network&describeeipaddress] def list_eip_addresses(options={}) _action = 'DescribeEipAddresses' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _Status = options[:state] if _Status _parameters['Status']=_Status _pathURL += '&Status='+_Status end _EipAddress = options[:ip_address] if _EipAddress _parameters['EipAddress']=_EipAddress _pathURL += '&EipAddress='+_EipAddress end _AllocationId = options[:allocation_id] if _AllocationId _parameters['AllocationId']=_AllocationId _pathURL += '&AllocationId='+_AllocationId end _PageNumber = options[:page_number] if _PageNumber _parameters['PageNumber']=_PageNumber _pathURL += '&PageNumber='+_PageNumber end _PageSize = options[:page_size] unless _PageSize _PageSize = '50' end _parameters['PageSize']=_PageSize _pathURL += '&PageSize='+_PageSize _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def allocate_address(pool = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool"=>"nova" } } response end end # mock end # aliyun end #compute end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_security_groups.rb0000644000175200017520000000456012653673664025622 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&describesecuritygroup] def list_security_groups(options={}) action = 'DescribeSecurityGroups' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) pageNumber = options[:pageNumber] pageSize = options[:pageSize] vpcId = options[:vpcId] if vpcId parameters["VpcId"] = vpcId pathUrl += '&VpcId=' pathUrl += vpcId end if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end pageSize = options[:pageSize] unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200], :method => 'GET', :path => pathUrl ) end end class Mock def list_security_groups(server_id = nil) security_groups = self.data[:security_groups].values groups = if server_id then server_group_names = Array(self.data[:server_security_group_map][server_id]) server_group_names.map do |name| security_groups.find do |sg| sg['name'] == name end end.compact else security_groups end Excon::Response.new( :body => { 'security_groups' => groups }, :headers => { "X-Compute-Request-Id" => "req-#{Fog::Mock.random_base64(36)}", "Content-Type" => "application/json", "Date" => Date.new }, :status => 200 ) end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_security_group_ip_rule.rb0000644000175200017520000000647512653673664027454 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def delete_security_group_ip_rule(securitygroup_id,sourceCidrIp, nicType, option={}) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&revokesecuritygroup] action = 'RevokeSecurityGroup' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["SourceCidrIp"] = sourceCidrIp pathUrl += '&SourceCidrIp=' pathUrl += URI.encode(sourceCidrIp,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') unless nicType nicType='intranet' end parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_vswitch.rb0000644000175200017520000000513612653673664024333 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def create_vswitch(vpcId, cidrBlock, options={}) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&createvswitch] action = 'CreateVSwitch' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["VpcId"] = vpcId pathUrl += '&VpcId=' pathUrl += vpcId parameters["CidrBlock"] = cidrBlock pathUrl += '&CidrBlock=' pathUrl += URI.encode(cidrBlock,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') parameters["ZoneId"] = @aliyun_zone_id pathUrl += '&ZoneId=' pathUrl += @aliyun_zone_id name = options[:name] desc = options[:description] if name parameters["VSwitchName"] = name pathUrl += '&VSwitchName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group(name, description) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::V2::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i + 1 self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_security_group_egress_sg_rule.rb0000644000175200017520000000674612653673664031026 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&authorizesecuritygroup] def delete_security_group_egress_sg_rule(securitygroup_id, dest_group_id, option={}) action = 'RevokeSecurityGroupEgress' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["DestGroupId"] = dest_group_id pathUrl += '&DestGroupId=' pathUrl += dest_group_id nicType = 'intranet' parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol destGOAccount = option[:destGroupOwnerAccount] if sourceGOAccount parameters["DestGroupOwnerAccount"]=destGOAccount pathUrl += '&DestGroupOwnerAccount=' pathUrl += destGOAccount end policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_security_group_sg_rule.rb0000644000175200017520000000700612653673664027444 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def delete_security_group_sg_rule(securitygroup_id, source_securitygroup_id, option={}) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&revokesecuritygroup] action = 'RevokeSecurityGroup' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["SourceGroupId"] = source_securitygroup_id pathUrl += '&SourceGroupId=' pathUrl += source_securitygroup_id nicType = 'intranet' parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol sourceGOAccount = option[:sourceGroupOwnerAccount] if sourceGOAccount parameters["SourceGroupOwnerAccount"]=sourceGOAccount pathUrl += '&SourceGroupOwnerAccount=' pathUrl += sourceGOAccount end policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_security_group_rules.rb0000644000175200017520000000454212653673664026651 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&describesecuritygroupattribute] def list_security_group_rules(securityGroupId, options = {}) action = 'DescribeSecurityGroupAttribute' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securityGroupId pathUrl += '&SecurityGroupId=' pathUrl += securityGroupId nicType = options[:nicType] if nicType parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType end pageNumber = options[:pageNumber] pageSize = options[:pageSize] if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end if pageSize parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def get_security_group(security_group_id) security_group = self.data[:security_groups][security_group_id.to_s] response = Excon::Response.new if security_group response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-63a90344-7c4d-42e2-936c-fd748bced1b3", "Content-Type" => "application/json", "Content-Length" => "167", "Date" => Date.new } response.body = { "security_group" => security_group } else raise Fog::Compute::OpenStack::NotFound, "Security group #{security_group_id} does not exist" end response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_security_group_ip_rule.rb0000644000175200017520000000650212653673664027444 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&authorizesecuritygroup] def create_security_group_ip_rule(securitygroup_id,sourceCidrIp, nicType, option={}) action = 'AuthorizeSecurityGroup' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["SourceCidrIp"] = sourceCidrIp pathUrl += '&SourceCidrIp=' pathUrl += URI.encode(sourceCidrIp,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') unless nicType nicType='intranet' end parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/allocate_eip_address.rb0000644000175200017520000000522612653673664025447 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Allocate an eip IP address. # # ==== Notes # The new eip Ip address would be avalable # The allocated eip Ip address can only associate to the instance of the vpc in the same region # Now the eip can support ICMP,TCP,UDP # ==== Parameters # * server_id<~String> - id of the instance # * allocationId<~String> - id of the EIP # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'EipAddress'<~String> - the allocated eip address # * 'AllocationId'<~String> - the instance id on the public ip # * 'RequestId'<~String> - Id of the request # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/network&allocateeipaddress] def allocate_eip_address(options={}) _action = 'AllocateEipAddress' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) #optional parameters _Bandwidth = options[:bandwidth] if _Bandwidth _parameters['Bandwidth']=_Bandwidth _pathURL += '&Bandwidth='+_Bandwidth end _InternetChargeType = options[:internet_charge_type] unless _InternetChargeType _InternetChargeType = 'PayByTraffic' end _parameters['InternetChargeType']=_InternetChargeType _pathURL += '&InternetChargeType='+_InternetChargeType _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def allocate_address(pool = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool"=>"nova" } } response end end # mock end # aliyun end #compute end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_snapshot.rb0000644000175200017520000000245112653673664024477 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def delete_snapshot(snapshotId) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/snapshot&deletesnapshot] action = 'DeleteSnapshot' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SnapshotId"] = snapshotId pathUrl += '&SnapshotId=' pathUrl += snapshotId signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_images response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_vpc.rb0000644000175200017520000000455012653673664023433 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def create_vpc(cidrBlock, options={}) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vpc&createvpc] action = 'CreateVpc' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["CidrBlock"] = cidrBlock pathUrl += '&CidrBlock=' pathUrl += URI.encode(cidrBlock,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') name = options[:name] desc = options[:description] if name parameters["VpcName"] = name pathUrl += '&VpcName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group(name, description) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::V2::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i + 1 self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_images.rb0000644000175200017520000000464212653673664023622 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/image&describeimages] def list_images(options={}) action = 'DescribeImages' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) pageNumber = options[:pageNumber] if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end pageSize = options[:pageSize] unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize imageId = options[:imageId] if imageId parameters["ImageId"] = imageId pathUrl += '&ImageId=' pathUrl += imageId end imageName = options[:imageName] if imageName parameters["ImageName"] = imageName pathUrl += '&ImageName=' pathUrl += imageName end snapshotId = options[:snapshotId] if snapshotId parameters["SnapshotId"] = snapshotId pathUrl += '&SnapshotId=' pathUrl += snapshotId end ownerAlias = options[:ownerAlias] if ownerAlias parameters["ImageOwnerAlias"] = ownerAlias pathUrl += '&ImageOwnerAlias=' pathUrl += ownerAlias end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_images response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_vswitch.rb0000644000175200017520000000272612653673664024334 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def delete_vswitch(vswitch_id) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&deletevswitch] action = 'DeleteVSwitch' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) if vswitch_id parameters["VSwitchId"] = vswitch_id pathUrl += '&VSwitchId=' pathUrl += vswitch_id else raise ArgumentError, "Missing required vswitch_id" end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def delete_security_group(security_group_id) self.data[:security_groups].delete security_group_id.to_s response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response.body = {} response end end # mock end # aliyun end # compute end #fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/stop_server.rb0000644000175200017520000000234412653673664023672 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Stop the server. # # === Parameters # * server_id <~String> - The ID of the server to be stopped. # === Returns # * success <~Boolean> # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&stopinstance] def stop_server(server_id) _action = 'StopInstance' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId']=server_id _pathURL += '&InstanceId='+server_id _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end # def stop_server end # class Real class Mock def stop_server(server_id) true end # def stop_server end # class Mock end # class aliyun end # module Compute end # module Fogfog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/join_security_group.rb0000644000175200017520000000225412653673664025421 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&joinsecuritygroup] def join_security_group(server_id, group_id) _action = 'JoinSecurityGroup' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId']=server_id _pathURL += '&InstanceId='+server_id _parameters['SecurityGroupId']=group_id _pathURL += '&SecurityGroupId='+group_id _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def join_security_group(server_id, group_id) response = Excon::Response.new response.status = 200 response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_security_group.rb0000644000175200017520000000466112653673664025731 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/securitygroup&createsecuritygroup] def create_security_group(options={}) action = 'CreateSecurityGroup' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) name = options[:name] desc = options[:description] vpcid = options[:vpcId] if name parameters["SecurityGroupName"] = name pathUrl += '&SecurityGroupName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end if vpcid parameters["VpcId"] = vpcid pathUrl += '&VpcId=' pathUrl += vpcid end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group(name, description) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::V2::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i + 1 self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_security_group_egress_ip_rule.rb0000644000175200017520000000650512653673664031017 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&authorizesecuritygroup] def create_security_group_egress_ip_rule(securitygroup_id,destCidrIp, nicType, option={}) action = 'AuthorizeSecurityGroupEgress' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["DestCidrIp"] = destCidrIp pathUrl += '&DestCidrIp=' pathUrl += URI.encode(destCidrIp,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') unless nicType nicType='intranet' end parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_server.rb0000644000175200017520000000277712653673664024161 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def delete_server(server_id) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&deleteinstance] _action = 'DeleteInstance' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId']=server_id _pathURL += '&InstanceId='+server_id _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def delete_server(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'] == server_id} if server['status'] == 'BUILD' response.status = 409 raise(Excon::Errors.status_error({:expects => 204}, response)) else self.data[:last_modified][:servers].delete(server_id) self.data[:servers].delete(server_id) response.status = 204 end response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_vpcs.rb0000644000175200017520000000341012653673664023320 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vpc&describevpcs] def list_vpcs(options={}) action = 'DescribeVpcs' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) _VpcId = options[:vpcId] if _VpcId parameters["VpcId"] = _VpcId pathUrl += '&VpcId=' pathUrl += _VpcId end pageNumber = options[:pageNumber] pageSize = options[:pageSize] if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_images response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_security_group_egress_sg_rule.rb0000644000175200017520000000675112653673664031023 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&authorizesecuritygroup] def create_security_group_egress_sg_rule(securitygroup_id, dest_group_id, option={}) action = 'AuthorizeSecurityGroupEgress' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["DestGroupId"] = dest_group_id pathUrl += '&DestGroupId=' pathUrl += dest_group_id nicType = 'intranet' parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol destGOAccount = option[:destGroupOwnerAccount] if sourceGOAccount parameters["DestGroupOwnerAccount"]=destGOAccount pathUrl += '&DestGroupOwnerAccount=' pathUrl += destGOAccount end policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_snapshot.rb0000644000175200017520000000325112653673664024477 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def create_snapshot(diskId, options={}) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/snapshot&createsnapshot] action = 'CreateSnapshot' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["DiskId"] = diskId pathUrl += '&DiskId=' pathUrl += diskId name = options[:name] desc = options[:description] if name parameters["SnapshotName"] = name pathUrl += '&SnapshotName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_images response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/unassociate_eip_address.rb0000644000175200017520000000435012653673664026176 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Disassociate an avalable eip IP address to the given instance. # # ==== Parameters # * server_id<~String> - id of the instance # * allocationId<~String> - id of the EIP # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/network&associateeipaddresss] def unassociate_eip_address(server_id, allocationId, options={}) _action = 'UnassociateEipAddress' _sigNonce = randonStr() _time = Time.new.utc type=options['instance_type'] _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId'] = server_id _pathURL += '&InstanceId='+server_id _parameters['AllocationId'] = allocationId _pathURL += '&AllocationId='+allocationId if type _parameters['InstanceType'] = type _pathURL += 'InstanceType='+type end _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def allocate_address(pool = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool"=>"nova" } } response end end # mock end # aliyun end #compute end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_security_group_sg_rule.rb0000644000175200017520000000701212653673664027442 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&authorizesecuritygroup] def create_security_group_sg_rule(securitygroup_id, source_securitygroup_id, option={}) action = 'AuthorizeSecurityGroup' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["SourceGroupId"] = source_securitygroup_id pathUrl += '&SourceGroupId=' pathUrl += source_securitygroup_id nicType = 'intranet' parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol sourceGOAccount = option[:sourceGroupOwnerAccount] if sourceGOAccount parameters["SourceGroupOwnerAccount"]=sourceGOAccount pathUrl += '&SourceGroupOwnerAccount=' pathUrl += sourceGOAccount end policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_zones.rb0000644000175200017520000000224512653673664023510 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/region&describezones] def list_zones() action = 'DescribeZones' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_zones(*args) Excon::Response.new( :body => { "availabilityZoneInfo" => [ { "zoneState" => { "available" => true }, "hosts" => nil, "zoneName" => "nova" } ] }, :status => 200 ) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/modify_vpc.rb0000644000175200017520000000453012653673664023455 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vpc&modifyvpcattribute] def modify_vpc(vpcId,options={}) action = 'ModifyVpcAttribute' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["VpcId"] = vpcId pathUrl += '&VpcId=' pathUrl += URI.encode(vpcId,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') name = options[:name] desc = options[:description] if name parameters["VpcName"] = name pathUrl += '&VpcName=' pathUrl += name end if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def modify_vpc(vpcId, options={}) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::V2::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i + 1 self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_snapshots.rb0000644000175200017520000000624512653673664024400 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/snapshot&describesnapshots] def list_snapshots(options={}) action = 'DescribeSnapshots' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) pageNumber = options[:pageNumber] pageSize = options[:pageSize] instanceId = options[:instanceId] diskId = options[:diskId] snapshotId = options[:snapshotIds] sourceDiskType = options[:sourceDiskType] name = options[:snapshotName] state = options[:state] type = options[:snapshotType] usage = options[:usage] if usage parameters["Usage"] = usage pathUrl += '&Usage=' pathUrl += usage end if type parameters["SnapshotType"] = type pathUrl += '&SnapshotType=' pathUrl += type end if state parameters["Status"] = state pathUrl += '&Status=' pathUrl += state end if name parameters["SnapshotName"] = name pathUrl += '&SnapshotName=' pathUrl += name end if instanceId parameters["InstanceId"] = instanceId pathUrl += '&InstanceId=' pathUrl += instanceId end if diskId parameters["DiskId"] = diskId pathUrl += '&DiskId=' pathUrl += diskId end if snapshotId parameters["SnapshotIds"] = Fog::JSON.encode(snapshotId) pathUrl += '&SnapshotIds=' pathUrl += Fog::JSON.encode(snapshotId) end if sourceDiskType parameters["SourceDiskType"] = sourceDiskType pathUrl += '&SourceDiskType=' pathUrl += sourceDiskType end if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_images response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/leave_security_group.rb0000644000175200017520000000226012653673664025553 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&leavesecuritygroup] def leave_security_group(server_id, group_id) _action = 'LeaveSecurityGroup' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId']=server_id _pathURL += '&InstanceId='+server_id _parameters['SecurityGroupId']=group_id _pathURL += '&SecurityGroupId='+group_id _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def add_security_group(server_id, group_name) response = Excon::Response.new response.status = 200 response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_security_group_egress_ip_rule.rb0000644000175200017520000000650212653673664031013 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&authorizesecuritygroup] def delete_security_group_egress_ip_rule(securitygroup_id,destCidrIp, nicType, option={}) action = 'RevokeSecurityGroupEgress' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SecurityGroupId"] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters["DestCidrIp"] = destCidrIp pathUrl += '&DestCidrIp=' pathUrl += URI.encode(destCidrIp,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') unless nicType nicType='intranet' end parameters["NicType"] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] unless portRange portRange = '-1/-1' end parameters["PortRange"] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] unless protocol protocol = 'all' end parameters["IpProtocol"] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] unless policy policy = 'accept' end parameters["Policy"] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] unless priority priority = '1' end parameters["Priority"] = priority pathUrl += '&Priority=' pathUrl += priority signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # aliyun end # compute end # fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_image.rb0000644000175200017520000000474112653673664023727 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/image&createimage] def create_image(snapshotId, options={}) action = 'CreateImage' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["SnapshotId"] = snapshotId pathUrl += '&SnapshotId=' pathUrl += snapshotId name = options[:name] if name parameters["ImageName"] = name pathUrl += '&ImageName=' pathUrl += name end desc = options[:description] if desc parameters["Description"] = desc pathUrl += '&Description=' pathUrl += desc end version = options[:version] if version parameters["ImageVersion"] = version pathUrl += '&ImageVersion=' pathUrl += version end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_image(server_id, name, metadata={}) response = Excon::Response.new response.status = 202 img_id=Fog::Mock.random_numbers(6).to_s data = { 'id' => img_id, 'server' => {"id"=>"3", "links"=>[{"href"=>"http://nova1:8774/admin/servers/#{server_id}", "rel"=>"bookmark"}]}, 'links' => [{"href"=>"http://nova1:8774/v1.1/admin/images/#{img_id}", "rel"=>"self"}, {"href"=>"http://nova1:8774/admin/images/#{img_id}", "rel"=>"bookmark"}], 'metadata' => metadata || {}, 'name' => name || "server_#{rand(999)}", 'progress' => 0, 'status' => 'SAVING', 'minDisk' => 0, 'minRam' => 0, 'updated' => "", 'created' => "" } self.data[:last_modified][:images][data['id']] = Time.now self.data[:images][data['id']] = data response.body = { 'image' => data } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_server_types.rb0000644000175200017520000000537312653673664025111 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/other&describeinstancetypes] def list_server_types _action = 'DescribeInstanceTypes' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature response = request( :expects => [200, 203], :method => 'GET', :path => _pathURL ) #_InstanceType = Hash.new #_InstanceTypeList = Fog::JSON.decode(response.body)["InstanceTypes"]["InstanceType"] #_InstanceTypeList.each do |instanceType| # _InstanceType[[instanceType["CpuCoreCount"], instanceType["MemorySize"]]] = instanceType["InstanceTypeId"] #end #_InstanceType end #end list_server_types def get_instance_type(cpuCount, memorySize) _action = 'DescribeInstanceTypes' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature response = request( :expects => [200, 203], :method => 'GET', :path => _pathURL ) _InstanceTypeId = nil _InstanceTypeList = Fog::JSON.decode(response.body)["InstanceTypes"]["InstanceType"] _InstanceTypeList.each do |instanceType| if ((instanceType["CpuCoreCount"] == cpuCount) && (instanceType["MemorySize"] == memorySize)) _InstanceTypeId = instanceType["InstanceTypeId"] puts "_instanceTypeId: "+_InstanceTypeId break end #end if end #end each _InstanceTypeId end #end get_instance_type end #end class Real # class Mock # def list_servers(options = {}) # response = Excon::Response.new # data = list_servers_detail.body['servers'] # servers = [] # for server in data # servers << server.reject { |key, value| !['id', 'name', 'links'].include?(key) } # end # response.status = [200, 203][rand(1)] # response.body = { 'servers' => servers } # response # end # end end #end class Aliyun end #end module Compute #end module Fog endfog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_image.rb0000644000175200017520000000360112653673664023720 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/image&deleteimage] def delete_image(imageId) action = 'DeleteImage' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["ImageId"] = imageId pathUrl += '&ImageId=' pathUrl += imageId signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def create_image(server_id, name, metadata={}) response = Excon::Response.new response.status = 202 img_id=Fog::Mock.random_numbers(6).to_s data = { 'id' => img_id, 'server' => {"id"=>"3", "links"=>[{"href"=>"http://nova1:8774/admin/servers/#{server_id}", "rel"=>"bookmark"}]}, 'links' => [{"href"=>"http://nova1:8774/v1.1/admin/images/#{img_id}", "rel"=>"self"}, {"href"=>"http://nova1:8774/admin/images/#{img_id}", "rel"=>"bookmark"}], 'metadata' => metadata || {}, 'name' => name || "server_#{rand(999)}", 'progress' => 0, 'status' => 'SAVING', 'minDisk' => 0, 'minRam' => 0, 'updated' => "", 'created' => "" } self.data[:last_modified][:images][data['id']] = Time.now self.data[:images][data['id']] = data response.body = { 'image' => data } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_security_group.rb0000644000175200017520000000303112653673664025716 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real def delete_security_group(security_group_id) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/securitygroup&deletesecuritygroup] action = 'DeleteSecurityGroup' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) if security_group_id parameters["SecurityGroupId"] = security_group_id pathUrl += '&SecurityGroupId=' pathUrl += security_group_id else raise ArgumentError, "Missing required securyti id " end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def delete_security_group(security_group_id) self.data[:security_groups].delete security_group_id.to_s response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response.body = {} response end end # mock end # aliyun end # compute end #fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/create_server.rb0000644000175200017520000001601212653673664024145 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&createinstance] def create_server(imageId, securityGroupId, instanceType, options = {}) _action = 'CreateInstance' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['ImageId'] = imageId _pathURL += '&ImageId='+imageId _parameters['InstanceType'] = instanceType _pathURL += '&InstanceType='+instanceType _parameters['SecurityGroupId'] = securityGroupId _pathURL += '&SecurityGroupId='+securityGroupId _ZoneId = options[:ZoneId] if _ZoneId _parameters['ZoneId']=_ZoneId _pathURL += '&ZoneId='+_ZoneId end _InstanceName = options[:InstanceName] if _InstanceName _parameters['InstanceName']=_InstanceName _pathURL += '&InstanceName='+_InstanceName end _Description = options[:Description] if _Description _parameters['Description']=_Description _pathURL += '&Description='+_Description end _InternetChargeType = options[:InternetChargeType] if _InternetChargeType _parameters['InternetChargeType']=_InternetChargeType _pathURL += '&InternetChargeType='+_InternetChargeType end _HostName = options[:HostName] if _HostName _parameters['HostName']=_HostName _pathURL += '&HostName='+_HostName end _Password = options[:Password] if _Password _parameters['Password']=_Password _pathURL += '&Password='+_Password end _VSwitchId = options[:VSwitchId] _PrivateIpAddress= options[:PrivateIpAddress] if _VSwitchId _parameters['VSwitchId']=_VSwitchId _pathURL += '&VSwitchId='+_VSwitchId if _PrivateIpAddress _parameters['PrivateIpAddress']=_PrivateIpAddress _pathURL += '&PrivateIpAddress='+_PrivateIpAddress end else _InternetMaxBandwidthIn = options[:InternetMaxBandwidthIn] if _InternetMaxBandwidthIn _parameters['InternetMaxBandwidthIn']=_InternetMaxBandwidthIn _pathURL += '&InternetMaxBandwidthIn='+_InternetMaxBandwidthIn end _InternetMaxBandwidthOut = options[:InternetMaxBandwidthOut] if _InternetMaxBandwidthOut _parameters['InternetMaxBandwidthOut']=_InternetMaxBandwidthOut _pathURL += '&InternetMaxBandwidthOut='+_InternetMaxBandwidthOut end end _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 203], :method => 'GET', :path => _pathURL ) end end class Mock def create_server(name, image_ref, flavor_ref, options = {}) response = Excon::Response.new response.status = 202 server_id = Fog::Mock.random_numbers(6).to_s identity = Fog::Identity::OpenStack.new :openstack_auth_url => credentials[:openstack_auth_url] user = identity.users.find { |u| u.name == @openstack_username } user_id = if user then user.id else response = identity.create_user(@openstack_username, 'password', "#{@openstack_username}@example.com") response.body["user"]["id"] end mock_data = { 'addresses' => {"Private" => [{"addr" => Fog::Mock.random_ip }]}, 'flavor' => {"id" => flavor_ref, "links"=>[{"href"=>"http://nova1:8774/admin/flavors/1", "rel"=>"bookmark"}]}, 'id' => server_id, 'image' => {"id" => image_ref, "links"=>[{"href"=>"http://nova1:8774/admin/images/#{image_ref}", "rel"=>"bookmark"}]}, 'links' => [{"href"=>"http://nova1:8774/v1.1/admin/servers/5", "rel"=>"self"}, {"href"=>"http://nova1:8774/admin/servers/5", "rel"=>"bookmark"}], 'hostId' => "123456789ABCDEF01234567890ABCDEF", 'metadata' => options['metadata'] || {}, 'name' => name || "server_#{rand(999)}", 'accessIPv4' => options['accessIPv4'] || "", 'accessIPv6' => options['accessIPv6'] || "", 'progress' => 0, 'status' => 'BUILD', 'created' => '2012-09-27T00:04:18Z', 'updated' => '2012-09-27T00:04:27Z', 'user_id' => @openstack_username, 'config_drive' => options['config_drive'] || '', } if nics = options['nics'] nics.each do |nic| mock_data["addresses"].merge!( "Public" => [{ 'addr' => Fog::Mock.random_ip }] ) end end response_data = {} if options['return_reservation_id'] == 'True' then response_data = { 'reservation_id' => "r-#{Fog::Mock.random_numbers(6).to_s}" } else response_data = { 'adminPass' => 'password', 'id' => server_id, 'links' => mock_data['links'], } end if block_devices = options["block_device_mapping_v2"] block_devices.each { |bd| compute.volumes.get(bd[:uuid]).attach(server_id, bd[:device_name]) } elsif block_device = options["block_device_mapping"] compute.volumes.get(block_device[:volume_id]).attach(server_id, block_device[:device_name]) end self.data[:last_modified][:servers][server_id] = Time.now self.data[:servers][server_id] = mock_data if security_groups = options['security_groups'] then groups = Array(options['security_groups']).map do |sg| if sg.is_a?(Fog::Compute::OpenStack::SecurityGroup) then sg.name else sg end end self.data[:server_security_group_map][server_id] = groups response_data['security_groups'] = groups end self.data[:last_modified][:servers][server_id] = Time.now self.data[:servers][server_id] = mock_data if options['return_reservation_id'] == 'True' then response.body = response_data else response.body = { 'server' => response_data } end response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/release_eip_address.rb0000644000175200017520000000310212653673664025272 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/network&releaseeipaddress] def release_eip_address(allocationId) _action = 'ReleaseEipAddress' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['AllocationId'] = allocationId _pathURL += '&AllocationId='+allocationId _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def allocate_address(pool = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool"=>"nova" } } response end end # mock end # aliyun end #compute end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/delete_vpc.rb0000644000175200017520000000266312653673664023435 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vpc&deletevpc] def delete_vpc(vpc_id) action = 'DeleteVpc' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) if vpc_id parameters["VpcId"] = vpc_id pathUrl += '&VpcId=' pathUrl += vpc_id else raise ArgumentError, "Missing required vpc_id" end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def delete_security_group(security_group_id) self.data[:security_groups].delete security_group_id.to_s response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response.body = {} response end end # mock end # aliyun end # compute end #fog fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_vswitchs.rb0000644000175200017520000000362012653673664024222 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&describevswitches] def list_vswitchs(vpcid, options={}) action = 'DescribeVSwitches' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["VpcId"] = vpcid pathUrl += '&VpcId=' pathUrl += vpcid pageNumber = options[:pageNumber] pageSize = options[:pageSize] vswitchId = options[:vSwitchId] if vswitchId parameters["VSwitchId"] = vswitchId pathUrl +='&VSwitchId=' pathUrl += vswitchId end if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_images response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/attach_disk.rb0000644000175200017520000000505512653673664023577 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Mount a disk. # # ==== Parameters # * instanceId<~String> - id of the instance # * diskId<~String> - id of the disk # * options<~hash> # * :deleteWithInstance - if 'true',the disk will be relese with the instance.else, won't # * :device - if nil, the system will default allocate from /dev/xvdb to /dev/xvdz. default nil # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/disk&attachdisk] def attach_disk(instanceId, diskId, options={}) action = 'AttachDisk' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["InstanceId"] = instanceId pathUrl += '&InstanceId=' pathUrl += instanceId parameters["DiskId"] = diskId pathUrl += '&DiskId=' pathUrl += diskId deleteWithInstance = options[:deleteWithInstance] device = options[:device] unless deleteWithInstance deleteWithInstance = 'true' end parameters["DeleteWithInstance"] = deleteWithInstance pathUrl += '&DeleteWithInstance=' pathUrl += deleteWithInstance if device parameters["Device"] = device pathUrl += '&Device=' pathUrl += URI.encode(device,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def attach_volume(volume_id, server_id, device) response = Excon::Response.new response.status = 200 data = { 'id' => volume_id, 'volumeId' => volume_id, 'serverId' => server_id, 'device' => device } self.data[:volumes][volume_id]['attachments'] << data response.body = { 'volumeAttachment' => data } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_vrouters.rb0000644000175200017520000000346112653673664024244 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vpc&describevpcs] def list_vrouters(options={}) action = 'DescribeVrouters' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) _VRouterId = options[:vRouterId] if _VRouterId parameters["VRouterId"] = _VRouterId pathUrl += '&VRouterId=' pathUrl += _VRouterId end pageNumber = options[:pageNumber] pageSize = options[:pageSize] if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_vrouters response = Excon::Response.new data = list_images_detail.body['VRouters'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'VRouter' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_route_tables.rb0000644000175200017520000000373412653673664025046 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&describevswitches] def list_route_tables(vrouterid, options={}) action = 'DescribeRouteTables' sigNonce = randonStr() time = Time.new.utc parameters = defalutParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters["VRouterId"] = vrouterid pathUrl += '&VRouterId=' pathUrl += vrouterid pageNumber = options[:pageNumber] pageSize = options[:pageSize] routeTableId = options[:routeTableId] if routeTableId parameters["RouteTableId"] = routeTableId pathUrl +='&RouteTableId=' pathUrl += routeTableId end if pageNumber parameters["PageNumber"] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end unless pageSize pageSize = '50' end parameters["PageSize"] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature request( :expects => [200, 203], :method => 'GET', :path => pathUrl ) end end class Mock def list_route_tables(vrouterid, options={}) response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/list_servers.rb0000644000175200017520000000434112653673664024042 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/instance&describeinstances] def list_servers(options={}) _action = 'DescribeInstances' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _InstanceId = options[:instanceId] _VpcId = options[:vpcId] _SecurityGroupId = options[:securityGroupId] _PageNumber = options[:pageNumber] _PageSize = options[:pageSize] if _InstanceId != nil _InstanceStr = "[\"#{_InstanceId}\"]" _parameters['InstanceIds'] = _InstanceStr _pathURL += '&InstanceIds='+_InstanceStr end if _VpcId != nil _parameters['VpcId'] = _VpcId _pathURL += '&VpcId='+_VpcId end if _SecurityGroupId != nil _parameters['SecurityGroupId']=_SecurityGroupId _pathURL += '&SecurityGroupId='+_SecurityGroupId end if _PageNumber != nil _parameters['PageNumber']=_PageNumber _pathURL += '&PageNumber='+_PageNumber end unless _PageSize _PageSize = '50' end _parameters['PageSize']=_PageSize _pathURL += '&PageSize='+_PageSize _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 203], :method => 'GET', :path => _pathURL ) end end class Mock def list_servers(options = {}) response = Excon::Response.new data = list_servers_detail.body['servers'] servers = [] for server in data servers << server.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'servers' => servers } response end end end end endfog-aliyun-0.1.0/lib/fog/aliyun/requests/compute/allocate_public_ip_address.rb0000644000175200017520000000371212653673664026636 0ustar rasilrasilmodule Fog module Compute class Aliyun class Real # Allocate an avalable public IP address to the given instance. # # ==== Parameters # * server_id<~String> - id of the instance # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'IpAddress'<~String> - The allocated ip address # * 'RequestId'<~String> - Id of the request # # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.201.106.DGkmH7#/pub/ecs/open-api/network&allocatepublicipaddress] def allocate_public_ip_address(server_id) _action = 'AllocatePublicIpAddress' _sigNonce = randonStr() _time = Time.new.utc _parameters = defalutParameters(_action, _sigNonce, _time) _pathURL = defaultAliyunUri(_action, _sigNonce, _time) _parameters['InstanceId']=server_id _pathURL += '&InstanceId='+server_id _signature = sign(@aliyun_accesskey_secret, _parameters) _pathURL += '&Signature='+_signature request( :expects => [200, 204], :method => 'GET', :path => _pathURL ) end end class Mock def allocate_address(pool = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool"=>"nova" } } response end end # mock end # aliyun end #compute end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/0000755000175200017520000000000012653673664020757 5ustar rasilrasilfog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/delete_container.rb0000644000175200017520000000162712653673664024616 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Delete an existing container # # ==== Parameters # * container<~String> - Name of container to delete # * options # def delete_container(container, options={}) bucket = options[:bucket] bucket ||= @aliyun_oss_bucket location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" object = container+'/' resource = bucket+'/'+object request( :expects => 204, :method => 'DELETE', :path => object, :bucket => bucket, :resource => resource, :endpoint => endpoint ) end end class Mock def delete_container(container, options={}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/put_bucket.rb0000644000175200017520000000073512653673664023456 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real def put_bucket(bucketName) resource = bucketName+'/' ret = request( :expects => [200, 203], :method => 'PUT', :resource => resource, :bucket => bucketName ) end end class Mock def put_bucket(bucketName) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/head_object.rb0000644000175200017520000000152112653673664023532 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Get headers for object # # ==== Parameters # * object<~String> - Name of object to look for # def head_object(object, options={}) bucket = options[:bucket] bucket ||= @aliyun_oss_bucket location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/'+object ret = request( :expects => [200, 404], :method => 'HEAD', :path => object, :bucket => bucket, :resource => resource, :endpoint => endpoint ) return ret end end class Mock def head_object(object, options={}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/delete_object.rb0000644000175200017520000000262112653673664024075 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Delete an existing object # # ==== Parameters # * object<~String> - Name of object to delete # def delete_object(object, options={}) bucket = options[:bucket] bucket ||= @aliyun_oss_bucket location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/'+object request( :expects => 204, :method => 'DELETE', :path => object, :bucket => bucket, :resource => resource, :endpoint => endpoint ) end def abort_multipart_upload(bucket, object, endpoint, uploadid) if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end path = object+"?uploadId="+uploadid resource = bucket+'/'+path ret = request( :expects => 204, :method => 'DELETE', :path => path, :bucket => bucket, :resource => resource, :endpoint => endpoint ) end end class Mock def delete_object(object, options={}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/list_buckets.rb0000644000175200017520000000213712653673664024002 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real def list_buckets(options={}) prefix = options[:prefix] marker = options[:marker] maxKeys = options[:maxKeys] path = "" if prefix path+="?prefix="+prefix if marker path+="&marker="+marker end if maxKeys path+="&max-keys="+maxKeys end elsif marker path+="?marker="+marker if maxKeys path+="&max-keys="+maxKeys end elsif maxKeys path+="?max-keys="+maxKeys end ret = request( :expects => [200, 203], :method => 'GET', :path => path ) xml = ret.data[:body] result = XmlSimple.xml_in(xml)["Buckets"][0] end end class Mock def list_buckets(options={}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/get_object_http_url.rb0000644000175200017520000000304212653673664025331 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Get an expiring object http url # # ==== Parameters # * container<~String> - Name of container containing object # * object<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object def get_object_http_url_public(object, expires, options = {}) options = options.reject {|key, value| value.nil?} bucket = options[:bucket] bucket ||= @aliyun_oss_bucket acl = get_bucket_acl(bucket) location = get_bucket_location(bucket) if "private" == acl expires_time = (Time.now.to_i + expires).to_s resource = bucket+'/'+object signature = sign("GET", expires_time, nil, resource) url = "http://"+bucket+"."+location+".aliyuncs.com/"+object+ "?OSSAccessKeyId="+@aliyun_accesskey_id+"&Expires="+expires_time+ "&Signature="+URI.encode(signature,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') elsif "public-read" == acl or "public-read-write" == acl url = "http://"+bucket+"."+location+".aliyuncs.com/"+object else url = "acl is wrong with value:"+acl end end end class Mock def get_object_http_url_public(object, expires, options = {}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/copy_object.rb0000644000175200017520000000265412653673664023613 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Copy object # # ==== Parameters # * source_bucket<~String> - Name of source bucket # * source_object<~String> - Name of source object # * target_bucket<~String> - Name of bucket to create copy in # * target_object<~String> - Name for new copy of object # * options<~Hash> - Additional headers options={} def copy_object(source_bucket, source_object, target_bucket, target_object, options = {}) options = options.reject {|key, value| value.nil?} bucket = options[:bucket] bucket ||= @aliyun_oss_bucket source_bucket ||= bucket target_bucket ||= bucket headers = { 'x-oss-copy-source' => "/#{source_bucket}/#{source_object}" } location = get_bucket_location(target_bucket) endpoint = "http://"+location+".aliyuncs.com" resource = target_bucket+'/'+target_object request({ :expects => [200, 203], :headers => headers, :method => 'PUT', :path => target_object, :bucket => target_bucket, :resource => resource, :endpoint => endpoint }) end end class Mock def copy_object(source_bucket, source_object, target_bucket, target_object) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/list_objects.rb0000644000175200017520000000605412653673664023775 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real def list_objects(options={}) bucket = options[:bucket] bucket ||= @aliyun_oss_bucket prefix = options[:prefix] marker = options[:marker] maxKeys = options[:maxKeys] delimiter = options[:delimiter] path = "" if prefix path+="?prefix="+prefix if marker path+="&marker="+marker end if maxKeys path+="&max-keys="+maxKeys end if delimiter path+="&delimiter="+delimiter end elsif marker path+="?marker="+marker if maxKeys path+="&max-keys="+maxKeys end if delimiter path+="&delimiter="+delimiter end elsif maxKeys path+="?max-keys="+maxKeys if delimiter path+="&delimiter="+delimiter end elsif delimiter path+="?delimiter="+delimiter end location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/' ret = request( :expects => [200, 203, 400], :method => 'GET', :path => path, :resource => resource, :bucket => bucket ) xml = ret.data[:body] result = XmlSimple.xml_in(xml) end def list_multipart_uploads(bucket, endpoint, options = {}) if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end path = "?uploads" resource = bucket+'/'+path ret = request( :expects => 200, :method => 'GET', :path => path, :bucket => bucket, :resource => resource, :endpoint => endpoint ) uploadid = XmlSimple.xml_in(ret.data[:body])["Upload"] end def list_parts(bucket, object, endpoint, uploadid, options = {}) if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end path = object+"?uploadId="+uploadid resource = bucket+'/'+path ret = request( :expects => 200, :method => 'GET', :path => path, :bucket => bucket, :resource => resource, :endpoint => endpoint ) parts = XmlSimple.xml_in(ret.data[:body])["Part"] end end class Mock def list_objects(options={}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/get_bucket.rb0000644000175200017520000001163312653673664023424 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real def get_bucket(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/' ret = request( :expects => [200, 203], :method => 'GET', :bucket => bucket, :resource => resource, :endpoint => endpoint ) xml = ret.data[:body] result = XmlSimple.xml_in(xml) end def get_bucket_location(bucket) attribute = '?location' resource = bucket+'/'+attribute ret = request( :expects => [200, 203], :method => 'GET', :path => attribute, :bucket => bucket, :resource => resource ) location = XmlSimple.xml_in(ret.data[:body]) end def get_bucket_acl(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" attribute = '?acl' resource = bucket+'/'+attribute ret = request( :expects => [200, 203], :method => 'GET', :path => attribute, :bucket => bucket, :resource => resource, :endpoint => endpoint ) acl = XmlSimple.xml_in(ret.data[:body])["AccessControlList"][0]["Grant"][0] end def get_bucket_CORSRules(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" attribute = '?cors' resource = bucket+'/'+attribute ret = request( :expects => [200, 203, 404], :method => 'GET', :path => attribute, :bucket => bucket, :resource => resource, :endpoint => endpoint ) if 404 != ret.data[:status] cors = XmlSimple.xml_in(ret.data[:body])["CORSRule"][0] else nil end end def get_bucket_lifecycle(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" attribute = '?lifecycle' resource = bucket+'/'+attribute ret = request( :expects => [200, 203, 404], :method => 'GET', :path => attribute, :bucket => bucket, :resource => resource, :endpoint => endpoint ) if 404 != ret.data[:status] lifecycle = XmlSimple.xml_in(ret.data[:body])["Rule"][0] else nil end end def get_bucket_logging(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" attribute = '?logging' resource = bucket+'/'+attribute ret = request( :expects => [200, 203], :method => 'GET', :path => attribute, :bucket => bucket, :resource => resource, :endpoint => endpoint ) logging = XmlSimple.xml_in(ret.data[:body])["LoggingEnabled"][0]["TargetPrefix"] end def get_bucket_referer(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" attribute = '?referer' resource = bucket+'/'+attribute ret = request( :expects => [200, 203], :method => 'GET', :path => attribute, :bucket => bucket, :resource => resource, :endpoint => endpoint ) referer = XmlSimple.xml_in(ret.data[:body]) end def get_bucket_website(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" attribute = '?website' resource = bucket+'/'+attribute ret = request( :expects => [200, 203, 404], :method => 'GET', :path => attribute, :bucket => bucket, :resource => resource, :endpoint => endpoint ) if 404 != ret.data[:status] website = XmlSimple.xml_in(ret.data[:body]) else nil end end end class Mock def get_bucket(bucket) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/get_container.rb0000644000175200017520000000351312653673664024127 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real def get_container(container, options = {}) options = options.reject {|key, value| value.nil?} bucket = options[:bucket] bucket ||= @aliyun_oss_bucket marker = options[:marker] maxKeys = options[:maxKeys] delimiter = '/' path = "" if container == "" || container == "." || container == nil prefix = nil else prefix = container+'/' end if prefix path+="?prefix="+prefix if marker path+="&marker="+marker end if maxKeys path+="&max-keys="+maxKeys end if delimiter path+="&delimiter="+delimiter end elsif marker path+="?marker="+marker if maxKeys path+="&max-keys="+maxKeys end if delimiter path+="&delimiter="+delimiter end elsif maxKeys path+="?max-keys="+maxKeys if delimiter path+="&delimiter="+delimiter end elsif delimiter path+="?delimiter="+delimiter end location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/' ret = request( :expects => [200, 203, 400], :method => 'GET', :path => path, :resource => resource, :bucket => bucket ) xml = ret.data[:body] result = XmlSimple.xml_in(xml)["CommonPrefixes"] end end class Mock def get_container(container, options = {}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/get_containers.rb0000644000175200017520000000376212653673664024320 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # List existing storage containers # # ==== Parameters # * options<~Hash>: # * 'maxKeys'<~Integer> - Upper limit to number of results returned # * 'marker'<~String> - Only return objects with name greater than this value # # ==== Returns # def get_containers(options = {}) options = options.reject {|key, value| value.nil?} bucket = options[:bucket] bucket ||= @aliyun_oss_bucket prefix = options[:prefix] marker = options[:marker] maxKeys = options[:maxKeys] delimiter = '/' path = "" if prefix path+="?prefix="+prefix if marker path+="&marker="+marker end if maxKeys path+="&max-keys="+maxKeys end if delimiter path+="&delimiter="+delimiter end elsif marker path+="?marker="+marker if maxKeys path+="&max-keys="+maxKeys end if delimiter path+="&delimiter="+delimiter end elsif maxKeys path+="?max-keys="+maxKeys if delimiter path+="&delimiter="+delimiter end elsif delimiter path+="?delimiter="+delimiter end location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/' ret = request( :expects => [200, 203, 400], :method => 'GET', :path => path, :resource => resource, :bucket => bucket ) xml = ret.data[:body] result = XmlSimple.xml_in(xml)["CommonPrefixes"] end end class Mock def get_containers(options = {}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/put_object.rb0000644000175200017520000001506212653673664023446 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Put details for object # # ==== Parameters # * object<~String> - Name of object to look for # def put_object(object, file=nil, options={}) bucket = options[:bucket] bucket ||= @aliyun_oss_bucket location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" if (nil == file) return put_folder(bucket, object, endpoint) end #put multiparts if object's size is over 100m if file.size >104857600 return put_multipart_object(bucket, object, file) end body = file.read resource = bucket+'/'+object ret = request( :expects => [200, 203], :method => 'PUT', :path => object, :bucket => bucket, :resource => resource, :body => body, :endpoint => endpoint ) end def put_object_with_body(object, body, options={}) bucket = options[:bucket] bucket ||= @aliyun_oss_bucket location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/'+object ret = request( :expects => [200, 203], :method => 'PUT', :path => object, :bucket => bucket, :resource => resource, :body => body, :endpoint => endpoint ) end def put_folder(bucket, folder, endpoint) if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end path = folder+'/' resource = bucket+'/'+folder+'/' ret = request( :expects => [200, 203], :method => 'PUT', :path => path, :bucket => bucket, :resource => resource, :endpoint => endpoint ) end def put_multipart_object(bucket, object, file) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" # find the right uploadid uploads = list_multipart_uploads(bucket, endpoint) if nil != uploads upload = uploads.find do |tmpupload| tmpupload["Key"][0] == object end else upload = nil end parts = nil uploadedSize = 0 start_partNumber = 1 if ( nil != upload ) uploadId = upload["UploadId"][0] parts = list_parts(bucket, object, endpoint, uploadId) if ((nil != parts) &&(0 != parts.size)) if (parts[-1]["Size"][0].to_i != 5242880) # the part is the last one, if its size is over 5m, then finish this upload complete_multipart_upload(bucket, object, endpoint, uploadId) return end uploadedSize = (parts[0]["Size"][0].to_i * (parts.size - 1)) + parts[-1]["Size"][0].to_i start_partNumber = parts[-1]["PartNumber"][0].to_i + 1 end else #create upload ID uploadId = initiate_multipart_upload(bucket, object, endpoint) end if (file.size <= uploadedSize) complete_multipart_upload(bucket, object, endpoint, uploadId) return end end_partNumber = (file.size + 5242880 -1) / 5242880 file.seek(uploadedSize) for i in start_partNumber..end_partNumber body = file.read(5242880) upload_part(bucket, object, endpoint, i.to_s, uploadId, body) end complete_multipart_upload(bucket, object, endpoint, uploadId) end def initiate_multipart_upload(bucket, object, endpoint) if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end path = object+"?uploads" resource = bucket+'/'+path ret = request( :expects => 200, :method => 'POST', :path => path, :bucket => bucket, :resource => resource, :endpoint => endpoint ) uploadid = XmlSimple.xml_in(ret.data[:body])["UploadId"][0] end def upload_part(bucket, object, endpoint, partNumber, uploadId, body) if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end path = object+"?partNumber="+partNumber+"&uploadId="+uploadId resource = bucket+'/'+path ret = request( :expects => [200, 203], :method => 'PUT', :path => path, :bucket => bucket, :resource => resource, :body => body, :endpoint => endpoint ) end def complete_multipart_upload(bucket, object, endpoint, uploadId) if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end parts = list_parts(bucket, object, endpoint, uploadId, options = {}) request_part = Array.new if parts.size == 0 return end for i in 0..(parts.size-1) part = parts[i] request_part[i] = {"PartNumber"=>part["PartNumber"], "ETag"=>part["ETag"]} end body = XmlSimple.xml_out({"Part"=>request_part},'RootName'=>'CompleteMultipartUpload') path = object+"?uploadId="+uploadId resource = bucket+'/'+path ret = request( :expects => 200, :method => 'POST', :path => path, :bucket => bucket, :resource => resource, :endpoint => endpoint, :body => body ) end end class Mock def put_object(object, file=nil, options={}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/delete_bucket.rb0000644000175200017520000000131612653673664024104 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Delete an existing bucket # # ==== Parameters # * bucket<~String> - Name of bucket to delete # def delete_bucket(bucket) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" resource = bucket+'/' request( :expects => 204, :method => 'DELETE', :bucket => bucket, :resource => resource, :endpoint => endpoint ) end end class Mock def delete_bucket(bucket) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/get_object.rb0000644000175200017520000000224312653673664023412 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Get details for object # # ==== Parameters # * object<~String> - Name of object to look for # def get_object(object, range = nil, options = {}) options = options.reject {|key, value| value.nil?} bucket = options[:bucket] bucket ||= @aliyun_oss_bucket endpoint = options[:endpoint] if (nil == endpoint) location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" end resource = bucket+'/'+object para = { :expects => [200, 206, 404], :method => 'GET', :path => object, :bucket => bucket, :resource => resource, :endpoint => endpoint } if range rangeStr = "bytes="+range para[:headers] = {'Range' => rangeStr} end response = request(para) response.data end end class Mock def get_object(object, range = nil, options = {}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/put_container.rb0000644000175200017520000000153012653673664024155 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Create a new container # # ==== Parameters # * name<~String> - Name for container # def put_container(name, options={}) bucket = options[:bucket] bucket ||= @aliyun_oss_bucket location = get_bucket_location(bucket) endpoint = "http://"+location+".aliyuncs.com" path = name+'/' resource = bucket+'/'+name+'/' request( :expects => [200, 203], :method => 'PUT', :path => path, :bucket => bucket, :resource => resource, :endpoint => endpoint ) end end class Mock def put_container(name, options={}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/requests/storage/get_object_https_url.rb0000644000175200017520000000307012653673664025515 0ustar rasilrasilmodule Fog module Storage class Aliyun class Real # Get an expiring object https url from Cloud Files # # ==== Parameters # * container<~String> - Name of container containing object # * object<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object def get_object_https_url_public(object, expires, options = {}) options = options.reject {|key, value| value.nil?} bucket = options[:bucket] bucket ||= @aliyun_oss_bucket acl = get_bucket_acl(bucket) location = get_bucket_location(bucket) if "private" == acl expires_time = (Time.now.to_i + expires).to_s resource = bucket+'/'+object signature = sign("GET", expires_time, nil, resource) url = "https://"+bucket+"."+location+".aliyuncs.com/"+object+ "?OSSAccessKeyId="+@aliyun_accesskey_id+"&Expires="+expires_time+ "&Signature="+URI.encode(signature,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') elsif "public-read" == acl or "public-read-write" == acl url = "https://"+bucket+"."+location+".aliyuncs.com/"+object else url = "acl is wrong with value:"+acl end end end class Mock def get_object_https_url_public(object, expires, options = {}) end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/compute.rb0000644000175200017520000003074012653673664017445 0ustar rasilrasilmodule Fog module Compute class Aliyun < Fog::Service recognizes :aliyun_url, :aliyun_accesskey_id, :aliyun_accesskey_secret, :aliyun_region_id, :aliyun_zone_id ## MODELS # model_path 'fog/aliyun/models/compute' model :server collection :servers model :image collection :images model :eip_address collection :eip_addresses model :security_group collection :security_groups model :security_group_rule collection :security_group_rules model :volume collection :volumes model :snapshot collection :snapshots model :vpc collection :vpcs model :vswitch collection :vswitches model :vrouter collection :vrouters model :route_table collection :route_tables model :route_entry collection :route_entrys ## REQUESTS # request_path 'fog/aliyun/requests/compute' # Server CRUD request :list_servers request :list_server_types request :create_server request :delete_server # Server Actions request :reboot_server request :start_server request :stop_server #SnapShoot CRUD request :list_snapshots request :create_snapshot request :delete_snapshot # Image CRUD request :list_images request :create_image request :delete_image # Eip request :list_eip_addresses request :allocate_eip_address request :release_eip_address request :associate_eip_address request :unassociate_eip_address # Security Group request :list_security_groups request :list_security_group_rules request :create_security_group request :create_security_group_ip_rule request :create_security_group_sg_rule request :create_security_group_egress_ip_rule request :create_security_group_egress_sg_rule request :delete_security_group request :delete_security_group_ip_rule request :delete_security_group_sg_rule request :delete_security_group_egress_ip_rule request :delete_security_group_egress_sg_rule request :join_security_group request :leave_security_group # Zones request :list_zones # VPC request :create_vpc request :delete_vpc request :list_vpcs request :create_vswitch request :delete_vswitch request :list_vswitchs request :modify_vpc request :modify_vswitch #VRouter request :list_vrouters #RouteTable request :list_route_tables #clouddisk request :list_disks request :create_disk request :delete_disk request :attach_disk request :detach_disk class Mock attr_reader :auth_token attr_reader :auth_token_expiration attr_reader :current_user attr_reader :current_tenant def self.data @data ||= Hash.new do |hash, key| hash[key] = { :last_modified => { :images => {}, :servers => {}, :key_pairs => {}, :security_groups => {}, :addresses => {} }, :images => { "0e09fbd6-43c5-448a-83e9-0d3d05f9747e" => { "id"=>"0e09fbd6-43c5-448a-83e9-0d3d05f9747e", "name"=>"cirros-0.3.0-x86_64-blank", 'progress' => 100, 'status' => "ACTIVE", 'updated' => "", 'minRam' => 0, 'minDisk' => 0, 'metadata' => {}, 'links' => [{"href"=>"http://nova1:8774/v1.1/admin/images/1", "rel"=>"self"}, {"href"=>"http://nova1:8774/admin/images/2", "rel"=>"bookmark"}] } }, :servers => {}, :key_pairs => {}, :security_groups => { '0' => { "id" => 0, "tenant_id" => Fog::Mock.random_hex(8), "name" => "default", "description" => "default", "rules" => [ { "id" => 0, "parent_group_id" => 0, "from_port" => 68, "to_port" => 68, "ip_protocol" => "udp", "ip_range" => { "cidr" => "0.0.0.0/0" }, "group" => {}, }, ], }, }, :server_security_group_map => {}, :addresses => {}, :quota => { 'security_group_rules' => 20, 'security_groups' => 10, 'injected_file_content_bytes' => 10240, 'injected_file_path_bytes' => 256, 'injected_files' => 5, 'metadata_items' => 128, 'floating_ips' => 10, 'instances' => 10, 'key_pairs' => 10, 'gigabytes' => 5000, 'volumes' => 10, 'cores' => 20, 'ram' => 51200 }, :volumes => {} } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_user_domain = options[:openstack_user_domain] || options[:openstack_domain] @openstack_project_domain = options[:openstack_project_domain] || options[:openstack_domain] || 'Default' @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @current_tenant = options[:openstack_tenant] @current_tenant_id = options[:openstack_tenant_id] @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 management_url = URI.parse(options[:openstack_auth_url]) management_url.port = 8774 management_url.path = '/v1.1/1' @openstack_management_url = management_url.to_s identity_public_endpoint = URI.parse(options[:openstack_auth_url]) identity_public_endpoint.port = 5000 @openstack_identity_public_endpoint = identity_public_endpoint.to_s end def data self.class.data["#{@openstack_username}-#{@current_tenant}"] end def reset_data self.class.data.delete("#{@openstack_username}-#{@current_tenant}") end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :openstack_identity_endpoint => @openstack_identity_public_endpoint } end end class Real # Initialize connection to ECS # # ==== Notes # options parameter must include values for :aliyun_url, :aliyun_accesskey_id, # :aliyun_secret_access_key, :aliyun_region_id and :aliyun_zone_id in order to create a connection. # if you haven't set these values in the configuration file. # # ==== Examples # sdb = Fog::Compute.new(:provider=>'aliyun', # :aliyun_accesskey_id => your_:aliyun_accesskey_id, # :aliyun_secret_access_key => your_aliyun_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * ECS object with connection to aliyun. attr_reader :aliyun_accesskey_id attr_reader :aliyun_accesskey_secret attr_reader :aliyun_region_id attr_reader :aliyun_url attr_reader :aliyun_zone_id def initialize(options={}) #initialize the parameters @aliyun_url = options[:aliyun_url] @aliyun_accesskey_id = options[:aliyun_accesskey_id] @aliyun_accesskey_secret = options[:aliyun_accesskey_secret] @aliyun_region_id = options[:aliyun_region_id] @aliyun_zone_id = options[:aliyun_zone_id] #check for the parameters missing_credentials = Array.new missing_credentials << :aliyun_accesskey_id unless @aliyun_accesskey_id missing_credentials << :aliyun_accesskey_secret unless @aliyun_accesskey_secret missing_credentials << :aliyun_region_id unless @aliyun_region_id missing_credentials << :aliyun_url unless @aliyun_url missing_credentials << :aliyun_zone_id unless @aliyun_zone_id raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? @connection_options = options[:connection_options] || {} uri = URI.parse(@aliyun_url) @host = uri.host @path = uri.path @port = uri.port @scheme = uri.scheme @persistent = options[:persistent] || false @connection = Fog::Core::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{params[:path]}", :query => params[:query] })) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::Aliyun::NotFound.slurp(error) else error end end if !response.body.empty? and response.get_header('Content-Type') == 'application/json' response.body = Fog::JSON.decode(response.body) end response end #operation compute-- default URL def defaultAliyunUri(action, sigNonce, time) parTimeFormat = time.strftime("%Y-%m-%dT%H:%M:%SZ") urlTimeFormat = URI.encode(parTimeFormat,':') return '?Format=JSON&AccessKeyId='+@aliyun_accesskey_id+'&Action='+action+'&SignatureMethod=HMAC-SHA1&RegionId='+@aliyun_region_id+'&SignatureNonce='+sigNonce+'&SignatureVersion=1.0&Version=2014-05-26&Timestamp='+urlTimeFormat end #generate random num def randonStr () numStr = rand(100000).to_s timeStr = Time.now.to_f.to_s ranStr = timeStr+"-"+numStr return ranStr end #operation compute--collection of default parameters def defalutParameters(action, sigNonce, time) parTimeFormat = time.strftime("%Y-%m-%dT%H:%M:%SZ") para = { 'Format'=>'JSON', 'Version'=>'2014-05-26', 'Action'=>action, 'AccessKeyId'=>@aliyun_accesskey_id, 'SignatureVersion'=>'1.0', 'SignatureMethod'=>'HMAC-SHA1', 'SignatureNonce'=>sigNonce, 'RegionId'=>@aliyun_region_id, 'Timestamp'=>parTimeFormat}; return para end #compute signature def sign (accessKeySecret,parameters) sortedParameters = parameters.sort canonicalizedQueryString = '' sortedParameters.each do | k, v | canonicalizedQueryString += '&' + URI.encode(k,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') + '=' + URI.encode(v,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') end canonicalizedQueryString[0] = '' stringToSign = 'GET&%2F&' + URI.encode(canonicalizedQueryString,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') key = accessKeySecret + '&' digVer = OpenSSL::Digest.new("sha1") digest = OpenSSL::HMAC.digest(digVer, key, stringToSign) signature = Base64.encode64(digest) signature[-1] = '' encodedSig = URI.encode(signature,'/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') return encodedSig end end end end end fog-aliyun-0.1.0/lib/fog/aliyun/version.rb0000644000175200017520000000007312653673664017452 0ustar rasilrasilmodule Fog module Aliyun VERSION = "0.1.0" end end fog-aliyun-0.1.0/lib/fog/aliyun/storage.rb0000644000175200017520000001657112653673664017443 0ustar rasilrasilrequire 'xmlsimple' module Fog module Storage class Aliyun < Fog::Service recognizes :aliyun_oss_endpoint, :aliyun_oss_location, :aliyun_oss_bucket, :aliyun_accesskey_id, :aliyun_accesskey_secret model_path 'fog/aliyun/models/storage' model :directory collection :directories model :file collection :files request_path 'fog/aliyun/requests/storage' request :copy_object request :delete_bucket request :delete_object request :get_bucket request :get_object request :get_object_http_url request :get_object_https_url request :head_object request :put_bucket request :put_object request :list_buckets request :list_objects request :get_containers request :get_container request :delete_container request :put_container class Real # Initialize connection to OSS # # ==== Notes # options parameter must include values for :aliyun_oss_endpoint, :aliyun_accesskey_id, # :aliyun_secret_access_key, :aliyun_oss_location and :aliyun_oss_bucket in order to create a connection. # if you haven't set these values in the configuration file. # # ==== Examples # sdb = Fog::Storage.new(:provider=>'aliyun', # :aliyun_accesskey_id => your_:aliyun_accesskey_id, # :aliyun_secret_access_key => your_aliyun_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * OSS object with connection to aliyun. attr_reader :aliyun_accesskey_id attr_reader :aliyun_accesskey_secret attr_reader :aliyun_oss_endpoint attr_reader :aliyun_oss_location attr_reader :aliyun_oss_bucket def initialize(options={}) #initialize the parameters @aliyun_oss_endpoint = options[:aliyun_oss_endpoint] @aliyun_oss_location = options[:aliyun_oss_location] @aliyun_accesskey_id = options[:aliyun_accesskey_id] @aliyun_accesskey_secret = options[:aliyun_accesskey_secret] @aliyun_oss_bucket = options[:aliyun_oss_bucket] #check for the parameters missing_credentials = Array.new missing_credentials << :aliyun_oss_endpoint unless @aliyun_oss_endpoint missing_credentials << :aliyun_oss_location unless @aliyun_oss_location missing_credentials << :aliyun_accesskey_id unless @aliyun_accesskey_id missing_credentials << :aliyun_accesskey_secret unless @aliyun_accesskey_secret raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? @connection_options = options[:connection_options] || {} uri = URI.parse(@aliyun_oss_endpoint) @host = uri.host @path = uri.path @port = uri.port @scheme = uri.scheme @persistent = options[:persistent] || false end def reload @connection.reset end def request(params) method = params[:method] time = Time.new.utc date = time.strftime("%a, %d %b %Y %H:%M:%S GMT") endpoint = params[:endpoint] if endpoint uri = URI.parse(endpoint) host = uri.host path = uri.path port = uri.port scheme = uri.scheme else host = @host path = @path port = @port scheme = @scheme end bucket = params[:bucket] if bucket tmpHost = bucket + '.' + host else tmpHost = host end @connection = Fog::Core::Connection.new("#{scheme}://#{tmpHost}", @persistent, @connection_options) contentType = params[:contentType] begin headers = "" if params[:headers] params[:headers].each do |k,v| if k != "Range" headers += "#{k}:#{v}\n" end end end signature = sign(method, date, contentType, params[:resource], headers) response = @connection.request(params.merge({ :headers => { 'Content-Type' => contentType, 'Authorization' =>'OSS '+@aliyun_accesskey_id+':'+signature, 'Date' => date }.merge!(params[:headers] || {}), :path => "#{path}/#{params[:path]}", :query => params[:query] })) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Storage::Aliyun::NotFound.slurp(error) else error end end response end #copmute signature def sign (method, date, contentType, resource=nil, headers = nil) contentmd5 = "" if resource canonicalizedResource = "/"+resource else canonicalizedResource = "/" end if headers canonicalizedOSSHeaders = headers else canonicalizedOSSHeaders = "" end if contentType contentTypeStr = contentType else contentTypeStr = "" end stringToSign = method+"\n"+contentmd5+"\n"+contentTypeStr+"\n"+date+"\n"+canonicalizedOSSHeaders+canonicalizedResource digVer = OpenSSL::Digest.new("sha1") digest = OpenSSL::HMAC.digest(digVer, @aliyun_accesskey_secret, stringToSign) signature = Base64.encode64(digest) signature[-1] = "" return signature end end class Mock def initialize(options={}) @aliyun_oss_endpoint = options[:aliyun_oss_endpoint] @aliyun_oss_location = options[:aliyun_oss_location] @aliyun_accesskey_id = options[:aliyun_accesskey_id] @aliyun_accesskey_secret = options[:aliyun_accesskey_secret] @aliyun_oss_bucket = options[:aliyun_oss_bucket] #missing_credentials = Array.new #missing_credentials << :aliyun_oss_endpoint unless @aliyun_oss_endpoint #missing_credentials << :aliyun_oss_location unless @aliyun_oss_location #missing_credentials << :aliyun_accesskey_id unless @aliyun_accesskey_id #missing_credentials << :aliyun_accesskey_secret unless @aliyun_accesskey_secret #raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? @connection_options = options[:connection_options] || {} #uri = URI.parse(@aliyun_oss_endpoint) #@host = uri.host #@path = uri.path #@port = uri.port #@scheme = uri.scheme #@persistent = options[:persistent] || false end end end end end fog-aliyun-0.1.0/Gemfile0000644000175200017520000000013712653673664014112 0ustar rasilrasilsource 'https://rubygems.org' # Specify your gem's dependencies in fog-aliyun.gemspec gemspec fog-aliyun-0.1.0/.rspec0000644000175200017520000000003712653673664013733 0ustar rasilrasil--format documentation --color fog-aliyun-0.1.0/.gitignore0000644000175200017520000000013212653673664014602 0ustar rasilrasil/.bundle/ /.yardoc /Gemfile.lock /_yardoc/ /coverage/ /doc/ /pkg/ /spec/reports/ /tmp/ *~ fog-aliyun-0.1.0/metadata.yml0000644000175200017520000002072712653673664015131 0ustar rasilrasil--- !ruby/object:Gem::Specification name: fog-aliyun version: !ruby/object:Gem::Version version: 0.1.0 platform: ruby authors: - Qinsi Deng, Jianxun Li, Jane Han autorequire: bindir: exe cert_chain: [] date: 2015-11-07 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: bundler requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.10' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.10' - !ruby/object:Gem::Dependency name: rake requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '10.0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '10.0' - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '3.3' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '3.3' - !ruby/object:Gem::Dependency name: fog-core requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.27' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.27' - !ruby/object:Gem::Dependency name: fog-json requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.0' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.0' - !ruby/object:Gem::Dependency name: ipaddress requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '0.8' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '0.8' - !ruby/object:Gem::Dependency name: xml-simple requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.1' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.1' description: As a FOG provider, fog-aliyun support aliyun OSS/ECS. It will support more aliyun services later. email: - dengqs@dtdream.com executables: [] extensions: [] extra_rdoc_files: [] files: - ".gitignore" - ".rspec" - ".travis.yml" - CODE_OF_CONDUCT.md - Gemfile - LICENSE.txt - README.md - Rakefile - bin/console - bin/setup - fog-aliyun.gemspec - lib/fog/aliyun.rb - lib/fog/aliyun/compute.rb - lib/fog/aliyun/models/compute/eip_address.rb - lib/fog/aliyun/models/compute/eip_addresses.rb - lib/fog/aliyun/models/compute/image.rb - lib/fog/aliyun/models/compute/images.rb - lib/fog/aliyun/models/compute/route_entry.rb - lib/fog/aliyun/models/compute/route_entrys.rb - lib/fog/aliyun/models/compute/route_table.rb - lib/fog/aliyun/models/compute/route_tables.rb - lib/fog/aliyun/models/compute/security_group.rb - lib/fog/aliyun/models/compute/security_group_rule.rb - lib/fog/aliyun/models/compute/security_group_rules.rb - lib/fog/aliyun/models/compute/security_groups.rb - lib/fog/aliyun/models/compute/server.rb - lib/fog/aliyun/models/compute/servers.rb - lib/fog/aliyun/models/compute/snapshot.rb - lib/fog/aliyun/models/compute/snapshots.rb - lib/fog/aliyun/models/compute/volume.rb - lib/fog/aliyun/models/compute/volumes.rb - lib/fog/aliyun/models/compute/vpc.rb - lib/fog/aliyun/models/compute/vpcs.rb - lib/fog/aliyun/models/compute/vrouter.rb - lib/fog/aliyun/models/compute/vrouters.rb - lib/fog/aliyun/models/compute/vswitch.rb - lib/fog/aliyun/models/compute/vswitches.rb - lib/fog/aliyun/models/storage/directories.rb - lib/fog/aliyun/models/storage/directory.rb - lib/fog/aliyun/models/storage/file.rb - lib/fog/aliyun/models/storage/files.rb - lib/fog/aliyun/requests/compute/allocate_eip_address.rb - lib/fog/aliyun/requests/compute/allocate_public_ip_address.rb - lib/fog/aliyun/requests/compute/associate_eip_address.rb - lib/fog/aliyun/requests/compute/attach_disk.rb - lib/fog/aliyun/requests/compute/create_disk.rb - lib/fog/aliyun/requests/compute/create_image.rb - lib/fog/aliyun/requests/compute/create_security_group.rb - lib/fog/aliyun/requests/compute/create_security_group_egress_ip_rule.rb - lib/fog/aliyun/requests/compute/create_security_group_egress_sg_rule.rb - lib/fog/aliyun/requests/compute/create_security_group_ip_rule.rb - lib/fog/aliyun/requests/compute/create_security_group_sg_rule.rb - lib/fog/aliyun/requests/compute/create_server.rb - lib/fog/aliyun/requests/compute/create_snapshot.rb - lib/fog/aliyun/requests/compute/create_vpc.rb - lib/fog/aliyun/requests/compute/create_vswitch.rb - lib/fog/aliyun/requests/compute/delete_disk.rb - lib/fog/aliyun/requests/compute/delete_image.rb - lib/fog/aliyun/requests/compute/delete_security_group.rb - lib/fog/aliyun/requests/compute/delete_security_group_egress_ip_rule.rb - lib/fog/aliyun/requests/compute/delete_security_group_egress_sg_rule.rb - lib/fog/aliyun/requests/compute/delete_security_group_ip_rule.rb - lib/fog/aliyun/requests/compute/delete_security_group_sg_rule.rb - lib/fog/aliyun/requests/compute/delete_server.rb - lib/fog/aliyun/requests/compute/delete_snapshot.rb - lib/fog/aliyun/requests/compute/delete_vpc.rb - lib/fog/aliyun/requests/compute/delete_vswitch.rb - lib/fog/aliyun/requests/compute/detach_disk.rb - lib/fog/aliyun/requests/compute/join_security_group.rb - lib/fog/aliyun/requests/compute/leave_security_group.rb - lib/fog/aliyun/requests/compute/list_disks.rb - lib/fog/aliyun/requests/compute/list_eip_addresses.rb - lib/fog/aliyun/requests/compute/list_images.rb - lib/fog/aliyun/requests/compute/list_route_tables.rb - lib/fog/aliyun/requests/compute/list_security_group_rules.rb - lib/fog/aliyun/requests/compute/list_security_groups.rb - lib/fog/aliyun/requests/compute/list_server_types.rb - lib/fog/aliyun/requests/compute/list_servers.rb - lib/fog/aliyun/requests/compute/list_snapshots.rb - lib/fog/aliyun/requests/compute/list_vpcs.rb - lib/fog/aliyun/requests/compute/list_vrouters.rb - lib/fog/aliyun/requests/compute/list_vswitchs.rb - lib/fog/aliyun/requests/compute/list_zones.rb - lib/fog/aliyun/requests/compute/modify_vpc.rb - lib/fog/aliyun/requests/compute/modify_vswitch.rb - lib/fog/aliyun/requests/compute/reboot_server.rb - lib/fog/aliyun/requests/compute/release_eip_address.rb - lib/fog/aliyun/requests/compute/start_server.rb - lib/fog/aliyun/requests/compute/stop_server.rb - lib/fog/aliyun/requests/compute/unassociate_eip_address.rb - lib/fog/aliyun/requests/storage/copy_object.rb - lib/fog/aliyun/requests/storage/delete_bucket.rb - lib/fog/aliyun/requests/storage/delete_container.rb - lib/fog/aliyun/requests/storage/delete_object.rb - lib/fog/aliyun/requests/storage/get_bucket.rb - lib/fog/aliyun/requests/storage/get_container.rb - lib/fog/aliyun/requests/storage/get_containers.rb - lib/fog/aliyun/requests/storage/get_object.rb - lib/fog/aliyun/requests/storage/get_object_http_url.rb - lib/fog/aliyun/requests/storage/get_object_https_url.rb - lib/fog/aliyun/requests/storage/head_object.rb - lib/fog/aliyun/requests/storage/list_buckets.rb - lib/fog/aliyun/requests/storage/list_objects.rb - lib/fog/aliyun/requests/storage/put_bucket.rb - lib/fog/aliyun/requests/storage/put_container.rb - lib/fog/aliyun/requests/storage/put_object.rb - lib/fog/aliyun/storage.rb - lib/fog/aliyun/version.rb - lib/fog/bin/aliyun.rb homepage: https://github.com/fog/fog-aliyun licenses: - MIT metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.4.8 signing_key: specification_version: 4 summary: Fog provider for Aliyun Web Services. test_files: [] has_rdoc: fog-aliyun-0.1.0/.travis.yml0000644000175200017520000000011412653673664014723 0ustar rasilrasillanguage: ruby rvm: - 2.1.6 before_install: gem install bundler -v 1.10.6 fog-aliyun-0.1.0/CODE_OF_CONDUCT.md0000644000175200017520000000263212653673664015420 0ustar rasilrasil# Contributor Code of Conduct As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) fog-aliyun-0.1.0/fog-aliyun.gemspec0000644000175200017520000000231512653673664016236 0ustar rasilrasil# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'fog/aliyun/version' Gem::Specification.new do |spec| spec.name = "fog-aliyun" spec.version = Fog::Aliyun::VERSION spec.authors = ["Qinsi Deng, Jianxun Li, Jane Han"] spec.email = ["dengqs@dtdream.com"] spec.summary = %q{Fog provider for Aliyun Web Services.} spec.description = %q{As a FOG provider, fog-aliyun support aliyun OSS/ECS. It will support more aliyun services later.} spec.homepage = "https://github.com/fog/fog-aliyun" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.10" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.3" spec.add_dependency 'fog-core', '~> 1.27' spec.add_dependency 'fog-json', '~> 1.0' spec.add_dependency 'ipaddress', '~> 0.8' spec.add_dependency 'xml-simple', '~> 1.1' end