pax_global_header00006660000000000000000000000064133132776510014522gustar00rootroot0000000000000052 comment=f8f53e4b00fbad4f3eeb9c81f327c82b962fd273 fog-aliyun-0.3.2/000077500000000000000000000000001331327765100135765ustar00rootroot00000000000000fog-aliyun-0.3.2/.gitignore000066400000000000000000000003111331327765100155610ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp *.bundle *.so *.o *.a mkmf.log gemfiles/*.lock fog-aliyun-0.3.2/.rspec000066400000000000000000000000371331327765100147130ustar00rootroot00000000000000--format documentation --color fog-aliyun-0.3.2/.rubocop.yml000066400000000000000000000010131331327765100160430ustar00rootroot00000000000000inherit_from: .rubocop_todo.yml Style/Documentation: Enabled: false Metrics/MethodLength: Enabled: false Metrics/AbcSize: Enabled: false Metrics/LineLength: Max: 120 Metrics/BlockLength: Enabled: false Layout/ExtraSpacing: AllowForAlignment: false ForceEqualSignAlignment: false Style/ExpandPathArguments: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Naming/VariableName: Enabled: false Lint/UnderscorePrefixedVariableName: Enabled: false Metrics/LineLength: Enabled: falsefog-aliyun-0.3.2/.rubocop_todo.yml000066400000000000000000000116271331327765100171040ustar00rootroot00000000000000# This configuration was generated by # `rubocop --auto-gen-config` # on 2018-06-22 19:29:12 -0300 using RuboCop version 0.57.2. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. # Offense count: 4 # Configuration parameters: AllowSafeAssignment. Lint/AssignmentInCondition: Exclude: - 'lib/fog/aliyun/requests/compute/create_server.rb' - 'lib/fog/aliyun/requests/compute/delete_server.rb' # Offense count: 4 Lint/RandOne: Exclude: - 'lib/fog/aliyun/requests/compute/list_images.rb' - 'lib/fog/aliyun/requests/compute/list_route_tables.rb' - 'lib/fog/aliyun/requests/compute/list_servers.rb' - 'lib/fog/aliyun/requests/compute/list_vrouters.rb' # Offense count: 1 Lint/UnreachableCode: Exclude: - 'lib/fog/aliyun/models/storage/directory.rb' # Offense count: 26 Lint/UriEscapeUnescape: Enabled: false # Offense count: 37 Lint/UselessAssignment: Exclude: - 'lib/fog/aliyun/requests/compute/create_server.rb' - 'lib/fog/aliyun/requests/compute/list_disks.rb' - 'lib/fog/aliyun/requests/compute/list_security_groups.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_http_url.rb' - 'lib/fog/aliyun/requests/storage/get_object_https_url.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_object.rb' - 'lib/fog/aliyun/storage.rb' # Offense count: 7 # Configuration parameters: CountComments. Metrics/ClassLength: Max: 154 # Offense count: 87 # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https Metrics/LineLength: Max: 247 # Offense count: 1 # Configuration parameters: CountKeywordArgs. Metrics/ParameterLists: Max: 6 # Offense count: 17 Metrics/PerceivedComplexity: Max: 19 # Offense count: 7 # Configuration parameters: EnforcedStyle. # SupportedStyles: snake_case, camelCase Naming/MethodName: Exclude: - 'lib/fog/aliyun/compute.rb' - 'lib/fog/aliyun/requests/storage/get_bucket.rb' # Offense count: 48 # Configuration parameters: MinNameLength, AllowNamesEndingInNumbers, AllowedNames, ForbiddenNames. # AllowedNames: io, id, to, by, on, in, at Naming/UncommunicativeMethodParamName: Enabled: false # Offense count: 5 Performance/Caller: Exclude: - 'lib/fog/aliyun/models/compute/images.rb' - 'lib/fog/aliyun/models/compute/snapshots.rb' - 'lib/fog/aliyun/models/compute/volumes.rb' - 'lib/fog/aliyun/models/compute/vpcs.rb' - 'lib/fog/aliyun/models/compute/vrouters.rb' # Offense count: 1 Style/ClassVars: Exclude: - 'lib/fog/bin/aliyun.rb' # Offense count: 7 # Configuration parameters: EnforcedStyle. # SupportedStyles: each, for Style/For: Exclude: - 'lib/fog/aliyun/models/storage/files.rb' - 'lib/fog/aliyun/requests/compute/list_images.rb' - 'lib/fog/aliyun/requests/compute/list_route_tables.rb' - 'lib/fog/aliyun/requests/compute/list_servers.rb' - 'lib/fog/aliyun/requests/compute/list_vrouters.rb' - 'lib/fog/aliyun/requests/storage/put_object.rb' # Offense count: 4 # Configuration parameters: AllowedVariables. Style/GlobalVars: Exclude: - 'lib/fog/aliyun/models/compute/server.rb' - 'lib/fog/aliyun/models/compute/vpcs.rb' - 'lib/fog/aliyun/models/compute/vrouter.rb' - 'lib/fog/aliyun/models/compute/vswitch.rb' # Offense count: 11 # Configuration parameters: MinBodyLength. Style/GuardClause: Exclude: - 'lib/fog/aliyun/models/compute/security_groups.rb' - 'lib/fog/aliyun/models/compute/snapshots.rb' - 'lib/fog/aliyun/models/compute/volumes.rb' - 'lib/fog/aliyun/models/storage/file.rb' - 'lib/fog/aliyun/requests/compute/delete_security_group.rb' - 'lib/fog/aliyun/requests/compute/delete_server.rb' - 'lib/fog/aliyun/requests/compute/delete_vpc.rb' - 'lib/fog/aliyun/requests/compute/delete_vpn_connection.rb' - 'lib/fog/aliyun/requests/compute/delete_vpn_customergateway.rb' - 'lib/fog/aliyun/requests/compute/delete_vswitch.rb' - 'lib/fog/aliyun/requests/compute/list_security_group_rules.rb' # Offense count: 2 Style/IdenticalConditionalBranches: Exclude: - 'lib/fog/aliyun/models/storage/files.rb' # Offense count: 1 Style/IfInsideElse: Exclude: - 'lib/fog/aliyun/models/compute/security_group_rule.rb' # Offense count: 2 Style/MultipleComparison: Exclude: - 'lib/fog/aliyun/requests/storage/get_object_http_url.rb' - 'lib/fog/aliyun/requests/storage/get_object_https_url.rb' fog-aliyun-0.3.2/.ruby-gemset000066400000000000000000000000131331327765100160340ustar00rootroot00000000000000fog-aliyun fog-aliyun-0.3.2/.ruby-version000066400000000000000000000000061331327765100162370ustar00rootroot000000000000002.5.1 fog-aliyun-0.3.2/.travis.yml000066400000000000000000000001141331327765100157030ustar00rootroot00000000000000language: ruby rvm: - 2.1.6 before_install: gem install bundler -v 1.10.6 fog-aliyun-0.3.2/CODE_OF_CONDUCT.md000066400000000000000000000026321331327765100164000ustar00rootroot00000000000000# 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.3.2/Gemfile000066400000000000000000000001761331327765100150750ustar00rootroot00000000000000# frozen_string_literal: true source 'https://rubygems.org' # Specify your gem's dependencies in fog-aliyun.gemspec gemspec fog-aliyun-0.3.2/LICENSE.txt000066400000000000000000000020641331327765100154230ustar00rootroot00000000000000The 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.3.2/README.md000066400000000000000000000202071331327765100150560ustar00rootroot00000000000000# 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_region_id: ``` ### 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_bucket => , :aliyun_region_id => , :aliyun_oss_endpoint => , } conn = Fog::Storage.new(opt) ``` **-> Note:** `:aliyun_region_id` is optional and default to "cn-hangzhou". **-> Note:** `:aliyun_oss_endpoint` is optional. If it is not specified, it will be generated automatically by `:aliyun_region_id`. Its basic format is "oss-.aliyuncs.com" and with default schema "http" and default port "80". If you want to use https or 443 port, you can use a format "://oss-.aliyuncs.com:". ## 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.3.2/Rakefile000066400000000000000000000002211331327765100152360ustar00rootroot00000000000000# frozen_string_literal: true require 'bundler/gem_tasks' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) task default: :spec fog-aliyun-0.3.2/bin/000077500000000000000000000000001331327765100143465ustar00rootroot00000000000000fog-aliyun-0.3.2/bin/console000077500000000000000000000005551331327765100157430ustar00rootroot00000000000000#!/usr/bin/env ruby # frozen_string_literal: true 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.3.2/bin/setup000066400000000000000000000001631331327765100154310ustar00rootroot00000000000000#!/bin/bash set -euo pipefail IFS=$'\n\t' bundle install # Do any other automated setup that you need to do here fog-aliyun-0.3.2/fog-aliyun.gemspec000066400000000000000000000023731331327765100172220ustar00rootroot00000000000000# frozen_string_literal: true 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 = ['dengqinsi@sina.com'] spec.summary = 'Fog provider for Aliyun Web Services.' spec.description = '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' spec.add_development_dependency 'mime-types', '~> 2.6', '>= 2.6.2' spec.add_development_dependency 'pry-nav' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec' spec.add_development_dependency 'rubocop' spec.add_dependency 'fog-core' spec.add_dependency 'fog-json' spec.add_dependency 'ipaddress', '~> 0.8' spec.add_dependency 'xml-simple', '~> 1.1' end fog-aliyun-0.3.2/lib/000077500000000000000000000000001331327765100143445ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/000077500000000000000000000000001331327765100151175ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun.rb000066400000000000000000000005511331327765100167460ustar00rootroot00000000000000# frozen_string_literal: true require 'fog/core' require 'fog/json' require 'fog/aliyun/version' module Fog module Compute autoload :Aliyun, 'fog/aliyun/compute' end module Storage autoload :Aliyun, 'fog/aliyun/storage' end module Aliyun extend Fog::Provider service(:compute, 'Compute') service(:storage, 'Storage') end end fog-aliyun-0.3.2/lib/fog/aliyun/000077500000000000000000000000001331327765100164205ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun/compute.rb000066400000000000000000000355051331327765100204310ustar00rootroot00000000000000# frozen_string_literal: true module 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 request :list_vpn_gateways request :list_vpn_customergateways request :list_vpn_connections request :create_vpn_customergateway request :create_vpn_connection request :delete_vpn_customergateway request :delete_vpn_connection # 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' => 10_240, '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' => 51_200 }, volumes: {} } end end def self.reset @data = nil end def initialize(options = {}) @aliyun_username = options[:aliyun_username] @aliyun_user_domain = options[:aliyun_user_domain] || options[:aliyun_domain] @aliyun_project_domain = options[:aliyun_project_domain] || options[:aliyun_domain] || 'Default' raise ArgumentError, 'Missing required arguments: :aliyun_auth_url' unless options.key?[:aliyun_auth_url] @aliyun_auth_uri = URI.parse(options[:aliyun_auth_url]) @current_tenant = options[:aliyun_tenant] @current_tenant_id = options[:aliyun_tenant_id] @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86_400).iso8601 management_url = URI.parse(@aliyun_auth_url) management_url.port = 8774 management_url.path = '/v1.1/1' @aliyun_management_url = management_url.to_s identity_public_endpoint = URI.parse(@aliyun_auth_url) identity_public_endpoint.port = 5000 @aliyun_identity_public_endpoint = identity_public_endpoint.to_s end def data self.class.data["#{@aliyun_username}-#{@current_tenant}"] end def reset_data self.class.data.delete("#{@aliyun_username}-#{@current_tenant}") end def credentials { provider: 'aliyun', aliyun_auth_url: @aliyun_auth_uri.to_s, aliyun_auth_token: @auth_token, aliyun_management_url: @aliyun_management_url, aliyun_identity_endpoint: @aliyun_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 = [] 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 vpcuri = URI.parse('https://vpc.aliyuncs.com') @vpchost = vpcuri.host @vpcpath = vpcuri.path @vpcport = vpcuri.port @vpcscheme = vpcuri.scheme @persistent = options[:persistent] || false @connection = Fog::Core::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) @VPCconnection = Fog::Core::Connection.new("#{@vpcscheme}://#{@vpchost}:#{@vpcport}", @persistent, @connection_options) end def reload @connection.reset @VPCconnection.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 response.body = Fog::JSON.decode(response.body) if !response.body.empty? && response.get_header('Content-Type') == 'application/json' response end def VPCrequest(params) begin response = @VPCconnection.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 response.body = Fog::JSON.decode(response.body) if !response.body.empty? && response.get_header('Content-Type') == 'application/json' response end # operation compute-- default URL def defaultAliyunUri(action, sigNonce, time) parTimeFormat = time.strftime('%Y-%m-%dT%H:%M:%SZ') urlTimeFormat = URI.encode(parTimeFormat, ':') '?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 def defaultAliyunVPCUri(action, sigNonce, time) parTimeFormat = time.strftime('%Y-%m-%dT%H:%M:%SZ') urlTimeFormat = URI.encode(parTimeFormat, ':') '?Format=JSON&AccessKeyId=' + @aliyun_accesskey_id + '&Action=' + action + '&SignatureMethod=HMAC-SHA1&RegionId=' + @aliyun_region_id + '&SignatureNonce=' + sigNonce + '&SignatureVersion=1.0&Version=2016-04-28&Timestamp=' + urlTimeFormat end # generate random num def randonStr numStr = rand(100_000).to_s timeStr = Time.now.to_f.to_s ranStr = timeStr + '-' + numStr 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 } para end def defalutVPCParameters(action, sigNonce, time) parTimeFormat = time.strftime('%Y-%m-%dT%H:%M:%SZ') para = { 'Format' => 'JSON', 'Version' => '2016-04-28', 'Action' => action, 'AccessKeyId' => @aliyun_accesskey_id, 'SignatureVersion' => '1.0', 'SignatureMethod' => 'HMAC-SHA1', 'SignatureNonce' => sigNonce, 'RegionId' => @aliyun_region_id, 'Timestamp' => parTimeFormat } 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, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') encodedSig end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/000077500000000000000000000000001331327765100177035ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/000077500000000000000000000000001331327765100213575ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/eip_address.rb000066400000000000000000000034021331327765100241650ustar00rootroot00000000000000# frozen_string_literal: true require '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: %w[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 = {}) if persisted? @server = nil self.server_id = new_server.id service.associate_eip_address(server_id, id, options) else @server = new_server end end def disassociate(new_server, options = {}) @server = nil self.server_id = new_server.id service.unassociate_eip_address(server_id, id, options) if persisted? end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/eip_addresses.rb000066400000000000000000000013741331327765100245230ustar00rootroot00000000000000# frozen_string_literal: true require '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) self.class.new(service: service).all(allocation_id: allocation_id)[0] if allocation_id end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/image.rb000066400000000000000000000041461331327765100227730ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/images.rb000066400000000000000000000014371331327765100231560ustar00rootroot00000000000000# frozen_string_literal: true require '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) self.class.new(service: service).all(imageId: image_id)[0] if image_id end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/route_entry.rb000066400000000000000000000027201331327765100242640ustar00rootroot00000000000000# frozen_string_literal: true require '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 end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/route_entrys.rb000066400000000000000000000022301331327765100244430ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/route_table.rb000066400000000000000000000031021331327765100242050ustar00rootroot00000000000000# frozen_string_literal: true require '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 end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/route_tables.rb000066400000000000000000000012711331327765100243750ustar00rootroot00000000000000# frozen_string_literal: true require '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 self.class.new(service: service, v_router: v_router).all(routeTableId: routeTableId)[0] if routeTableId end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/security_group.rb000066400000000000000000000050601331327765100247700ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/security_group_rule.rb000066400000000000000000000037621331327765100260260ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/security_group_rules.rb000066400000000000000000000013741331327765100262060ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/security_groups.rb000066400000000000000000000015061331327765100251540ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/server.rb000066400000000000000000000074051331327765100232200ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/servers.rb000066400000000000000000000030531331327765100233760ustar00rootroot00000000000000# frozen_string_literal: true require '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 = {}) 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) self.class.new(service: service).all(instanceId: server_id)[0] if server_id end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/snapshot.rb000066400000000000000000000031201331327765100235370ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/snapshots.rb000066400000000000000000000023721331327765100237320ustar00rootroot00000000000000# frozen_string_literal: true require '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] filters_arg[:diskId] = volume_id if volume_id filters_arg[:sourseDiskType] = volume_type if volume_type 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.3.2/lib/fog/aliyun/models/compute/volume.rb000066400000000000000000000063501331327765100232170ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/volumes.rb000066400000000000000000000106671331327765100234100ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/vpc.rb000066400000000000000000000041651331327765100225020ustar00rootroot00000000000000# frozen_string_literal: true require '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 Fog::JSON.decode(service.create_vpc(cidr_block, options).body) true end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/vpcs.rb000066400000000000000000000036571331327765100226720ustar00rootroot00000000000000# frozen_string_literal: true require '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) $vpc = self.class.new(service: service).all('vpcId' => vpcId)[0] if vpcId end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/vrouter.rb000066400000000000000000000021501331327765100234100ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/compute/vrouters.rb000066400000000000000000000031561331327765100236020ustar00rootroot00000000000000# frozen_string_literal: true require '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) self.class.new(service: service).all('vRouterId' => vRouterId)[0] if vRouterId end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/vswitch.rb000066400000000000000000000036021331327765100233740ustar00rootroot00000000000000# frozen_string_literal: true require '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 Fog::JSON.decode(service.create_vswitch(vpc.id, cidr_block, options).body) true end def vpc $vpc end def all Fog::JSON.decode(service.list_vswitchs(vpc_id).body)['VSwitches']['VSwitch'] end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/compute/vswitches.rb000066400000000000000000000034451331327765100237310ustar00rootroot00000000000000# frozen_string_literal: true require '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 self.class.new(service: service, vpc: vpc).all(vSwitchId: vswitchId)[0] if vswitchId end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/storage/000077500000000000000000000000001331327765100213475ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun/models/storage/directories.rb000066400000000000000000000016731331327765100242170ustar00rootroot00000000000000# frozen_string_literal: true require '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 return nil if containers.nil? data = [] i = 0 containers.each do |entry| key = entry['Prefix'][0] key[-1] = '' data[i] = { key: key } i += 1 end load(data) end def get(key, options = {}) if !key.nil? && key != '' && key != '.' dir = key + '/' ret = service.head_object(dir, options) new(key: key) if ret.data[:status] == 200 else new(key: '') end rescue Fog::Storage::Aliyun::NotFound nil end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/models/storage/directory.rb000066400000000000000000000020201331327765100236720ustar00rootroot00000000000000# frozen_string_literal: true require '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.3.2/lib/fog/aliyun/models/storage/file.rb000066400000000000000000000134341331327765100226200ustar00rootroot00000000000000# frozen_string_literal: true require '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 attr_reader :directory def copy(target_directory_key, target_file_key, options = {}) requires :directory, :key source_object = if directory.key == '' key else directory.key + '/' + key end target_object = if target_directory_key == '' target_file_key else 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 object = if directory.key == '' key else 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 object = if directory.key == '' key else directory.key + '/' + key end service.get_object_http_url_public(object, expires, options) end def public_url requires :key collection.get_url(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.merge!(metadata_to_headers) object = if directory.key == '' key else 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 attr_writer :directory 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 object = if directory.key == '' key else directory.key + '/' + key end headers = service.head_object(object).data[:headers] headers.select! { |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.3.2/lib/fog/aliyun/models/storage/files.rb000066400000000000000000000135411331327765100230020ustar00rootroot00000000000000# frozen_string_literal: true require '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 prefix = directory.key + '/' if directory.key != '' && directory.key != '.' && !directory.key.nil? files = service.list_objects(prefix: prefix)['Contents'] return if files.nil? data = [] i = 0 files.each do |file| next unless file['Key'][0][-1] != '/' content_length = file['Size'][0].to_i key = file['Key'][0] lastModified = file['LastModified'][0] last_modified = (Time.parse(lastModified).localtime if !lastModified.nil? && lastModified != '') type = file['Type'][0] data[i] = { content_length: content_length, key: key, last_modified: last_modified, etag: file['ETag'][0], object_type: type } i += 1 end load(data) end alias 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 || 10_000) subset = subset.all(marker: subset.last.key) subset.each_file_this_page { |f| yield f } end self end end def get(key) requires :directory object = if directory.key == '' key else directory.key + '/' + key end begin data = service.get_object(object) rescue StandardError => error case error.response.body when %r{NoSuchKey} nil else raise(error) end end contentLen = data[:headers]['Content-Length'].to_i 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 body = data[:body] end lastModified = data[:headers]['Last-Modified'] last_modified = (Time.parse(lastModified).localtime if !lastModified.nil? && lastModified != '') date = data[:headers]['Date'] date = (Time.parse(date).localtime if !date.nil? && date != '') 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 object = if directory.key == '' key else directory.key + '/' + key end service.get_object_http_url_public(object, 3600) end def get_http_url(key, expires, options = {}) requires :directory object = if directory.key == '' key else directory.key + '/' + key end service.get_object_http_url_public(object, expires, options) end def get_https_url(key, expires, options = {}) requires :directory object = if directory.key == '' key else directory.key + '/' + key end service.get_object_https_url_public(object, expires, options) end def head(key, _options = {}) requires :directory object = if directory.key == '' key else directory.key + '/' + key end data = service.head_object(object).data lastModified = data[:headers]['Last-Modified'] last_modified = (Time.parse(lastModified).localtime if !lastModified.nil? && lastModified != '') date = data[:headers]['Date'] date = (Time.parse(date).localtime if !date.nil? && date != '') 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.3.2/lib/fog/aliyun/requests/000077500000000000000000000000001331327765100202735ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/000077500000000000000000000000001331327765100217475ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/allocate_eip_address.rb000066400000000000000000000036341331327765100264300ustar00rootroot00000000000000# frozen_string_literal: true module 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] _InternetChargeType ||= 'PayByTraffic' _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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/allocate_public_ip_address.rb000066400000000000000000000024021331327765100276110ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/associate_eip_address.rb000066400000000000000000000030301331327765100266050ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/attach_disk.rb000066400000000000000000000047131331327765100245570ustar00rootroot00000000000000# frozen_string_literal: true module 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] deleteWithInstance ||= 'true' 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.3.2/lib/fog/aliyun/requests/compute/create_disk.rb000066400000000000000000000114301331327765100245500ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_image.rb000066400000000000000000000047371331327765100247140ustar00rootroot00000000000000# frozen_string_literal: true module 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.3.2/lib/fog/aliyun/requests/compute/create_security_group.rb000066400000000000000000000046171331327765100267120ustar00rootroot00000000000000# frozen_string_literal: true module 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 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' => data[:security_groups][security_group_id.to_s] } response end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_security_group_egress_ip_rule.rb000066400000000000000000000040101331327765100317640ustar00rootroot00000000000000# frozen_string_literal: true module 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, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_security_group_egress_sg_rule.rb000066400000000000000000000043261331327765100317770ustar00rootroot00000000000000# frozen_string_literal: true module 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] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol destGOAccount = option[:destGroupOwnerAccount] if sourceGOAccount parameters['DestGroupOwnerAccount'] = destGOAccount pathUrl += '&DestGroupOwnerAccount=' pathUrl += destGOAccount end policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_security_group_ip_rule.rb000066400000000000000000000040051331327765100304200ustar00rootroot00000000000000# frozen_string_literal: true module 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, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_security_group_sg_rule.rb000066400000000000000000000043671331327765100304340ustar00rootroot00000000000000# frozen_string_literal: true module 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] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol sourceGOAccount = option[:sourceGroupOwnerAccount] if sourceGOAccount parameters['SourceGroupOwnerAccount'] = sourceGOAccount pathUrl += '&SourceGroupOwnerAccount=' pathUrl += sourceGOAccount end policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_server.rb000066400000000000000000000161261331327765100251330ustar00rootroot00000000000000# frozen_string_literal: true module 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 do |u| u.name == @openstack_username end user_id = if user 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' => user_id, '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 = {} response_data = if options['return_reservation_id'] == 'True' { 'reservation_id' => "r-#{Fog::Mock.random_numbers(6)}" } else { '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 data[:last_modified][:servers][server_id] = Time.now data[:servers][server_id] = mock_data if options['security_groups'] groups = Array(options['security_groups']).map do |sg| if sg.is_a?(Fog::Compute::OpenStack::SecurityGroup) sg.name else sg end end data[:server_security_group_map][server_id] = groups response_data['security_groups'] = groups end data[:last_modified][:servers][server_id] = Time.now data[:servers][server_id] = mock_data response.body = if options['return_reservation_id'] == 'True' response_data else { 'server' => response_data } end response end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_snapshot.rb000066400000000000000000000023441331327765100254610ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_vpc.rb000066400000000000000000000024031331327765100244060ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_vpn_connection.rb000066400000000000000000000033251331327765100266440ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Compute class Aliyun class Real def create_vpn_connection(customergatewayId, vpngatewayId, localsubnet, remotesubnet, options = {}) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&createvswitch] action = 'CreateVpnConnection' sigNonce = randonStr time = Time.new.utc parameters = defalutVPCParameters(action, sigNonce, time) pathUrl = defaultAliyunVPCUri(action, sigNonce, time) parameters['CustomerGatewayId'] = customergatewayId pathUrl += '&CustomerGatewayId=' pathUrl += customergatewayId parameters['VpnGatewayId'] = vpngatewayId pathUrl += '&VpnGatewayId=' pathUrl += vpngatewayId parameters['LocalSubnet'] = localsubnet pathUrl += '&LocalSubnet=' pathUrl += localsubnet parameters['RemoteSubnet'] = remotesubnet pathUrl += '&RemoteSubnet=' pathUrl += remotesubnet name = options[:name] ipsecconfig = options[:ipsecconfig] if name parameters['Name'] = name pathUrl += '&Name=' pathUrl += name end if ipsecconfig parameters['IpsecConfig'] = ipsecconfig pathUrl += '&IpsecConfig=' pathUrl += ipsecconfig end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature VPCrequest( expects: [200, 203], method: 'GET', path: pathUrl ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_vpn_customergateway.rb000066400000000000000000000023741331327765100277330ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Compute class Aliyun class Real def create_vpn_customergateway(ipaddress, options = {}) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&createvswitch] action = 'CreateCustomerGateway' sigNonce = randonStr time = Time.new.utc parameters = defalutVPCParameters(action, sigNonce, time) pathUrl = defaultAliyunVPCUri(action, sigNonce, time) parameters['IpAddress'] = ipaddress pathUrl += '&IpAddress=' pathUrl += ipaddress name = options[:name] desc = options[:description] if name parameters['Name'] = name pathUrl += '&Name=' pathUrl += name end if desc parameters['Description'] = desc pathUrl += '&Description=' pathUrl += desc end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature VPCrequest( expects: [200, 203], method: 'GET', path: pathUrl ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/create_vswitch.rb000066400000000000000000000027721331327765100253160ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_disk.rb000066400000000000000000000021721331327765100245520ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_image.rb000066400000000000000000000015451331327765100247050ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_security_group.rb000066400000000000000000000027641331327765100267120ustar00rootroot00000000000000# frozen_string_literal: true module 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) 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_security_group_egress_ip_rule.rb000066400000000000000000000040051331327765100317670ustar00rootroot00000000000000# frozen_string_literal: true module 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, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_security_group_egress_sg_rule.rb000066400000000000000000000043231331327765100317730ustar00rootroot00000000000000# frozen_string_literal: true module 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] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol destGOAccount = option[:destGroupOwnerAccount] if sourceGOAccount parameters['DestGroupOwnerAccount'] = destGOAccount pathUrl += '&DestGroupOwnerAccount=' pathUrl += destGOAccount end policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_security_group_ip_rule.rb000066400000000000000000000040011331327765100304130ustar00rootroot00000000000000# frozen_string_literal: true module 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, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_security_group_sg_rule.rb000066400000000000000000000043631331327765100304270ustar00rootroot00000000000000# frozen_string_literal: true module 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] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += URI.encode(portRange, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') protocol = option[:protocol] protocol ||= 'all' parameters['IpProtocol'] = protocol pathUrl += '&IpProtocol=' pathUrl += protocol sourceGOAccount = option[:sourceGroupOwnerAccount] if sourceGOAccount parameters['SourceGroupOwnerAccount'] = sourceGOAccount pathUrl += '&SourceGroupOwnerAccount=' pathUrl += sourceGOAccount end policy = option[:policy] policy ||= 'accept' parameters['Policy'] = policy pathUrl += '&Policy=' pathUrl += policy priority = option[:priority] priority ||= '1' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_server.rb000066400000000000000000000027531331327765100251330ustar00rootroot00000000000000# frozen_string_literal: true module 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 data[:last_modified][:servers].delete(server_id) 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.3.2/lib/fog/aliyun/requests/compute/delete_snapshot.rb000066400000000000000000000015761331327765100254660ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_vpc.rb000066400000000000000000000017041331327765100244100ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_vpn_connection.rb000066400000000000000000000020621331327765100266400ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Compute class Aliyun class Real def delete_vpn_connection(vpn_connectionid) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&deletevswitch] action = 'DeleteVpnConnection' sigNonce = randonStr time = Time.new.utc parameters = defalutVPCParameters(action, sigNonce, time) pathUrl = defaultAliyunVPCUri(action, sigNonce, time) if vpn_connectionid parameters['VpnConnectionId'] = vpn_connectionid pathUrl += '&VpnConnectionId=' pathUrl += vpn_connectionid else raise ArgumentError, 'Missing required vpn_connectionid' end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature VPCrequest( expects: [200, 203], method: 'GET', path: pathUrl ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_vpn_customergateway.rb000066400000000000000000000021261331327765100277250ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Compute class Aliyun class Real def delete_vpn_customergateway(vpn_customergatewayid) # {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/vswitch&deletevswitch] action = 'DeleteCustomerGateway' sigNonce = randonStr time = Time.new.utc parameters = defalutVPCParameters(action, sigNonce, time) pathUrl = defaultAliyunVPCUri(action, sigNonce, time) if vpn_customergatewayid parameters['CustomerGatewayId'] = vpn_customergatewayid pathUrl += '&CustomerGatewayId=' pathUrl += vpn_customergatewayid else raise ArgumentError, 'Missing required vpn_customergatewayid' end signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature VPCrequest( expects: [200, 203], method: 'GET', path: pathUrl ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/delete_vswitch.rb000066400000000000000000000017621331327765100253130ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/detach_disk.rb000066400000000000000000000023071331327765100245400ustar00rootroot00000000000000# frozen_string_literal: true module 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 device = _options[:device] 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/join_security_group.rb000066400000000000000000000017431331327765100264030ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/leave_security_group.rb000066400000000000000000000017461331327765100265430ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_disks.rb000066400000000000000000000122011331327765100244400ustar00rootroot00000000000000# frozen_string_literal: true module 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] pageSize ||= '50' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_eip_addresses.rb000066400000000000000000000032421331327765100261420ustar00rootroot00000000000000# frozen_string_literal: true module 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] _PageSize ||= '50' _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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_images.rb000066400000000000000000000045261331327765100246030ustar00rootroot00000000000000# frozen_string_literal: true module 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] pageSize ||= '50' 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(_options = {}) response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.select { |key, _value| %w[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.3.2/lib/fog/aliyun/requests/compute/list_route_tables.rb000066400000000000000000000036541331327765100260270ustar00rootroot00000000000000# frozen_string_literal: true module 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 pageSize ||= '50' 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.select { |key, _value| %w[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.3.2/lib/fog/aliyun/requests/compute/list_security_group_rules.rb000066400000000000000000000044301331327765100276250ustar00rootroot00000000000000# frozen_string_literal: true module 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 = 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_security_groups.rb000066400000000000000000000043761331327765100266070ustar00rootroot00000000000000# frozen_string_literal: true module 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] pageSize ||= '50' 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 = data[:security_groups].values groups = if server_id server_group_names = Array(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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_server_types.rb000066400000000000000000000034051331327765100260630ustar00rootroot00000000000000# frozen_string_literal: true module 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 request( expects: [200, 203], method: 'GET', path: _pathURL ) end 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 |instance_type| next unless (instance_type['CpuCoreCount'] == cpuCount) && (instance_type['MemorySize'] == memorySize) _InstanceTypeId = instance_type['InstanceTypeId'] puts '_instanceTypeId: ' + _InstanceTypeId break end _InstanceTypeId end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_servers.rb000066400000000000000000000042751331327765100250300ustar00rootroot00000000000000# frozen_string_literal: true module 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] unless _InstanceId.nil? _InstanceStr = "[\"#{_InstanceId}\"]" _parameters['InstanceIds'] = _InstanceStr _pathURL += '&InstanceIds=' + _InstanceStr end unless _VpcId.nil? _parameters['VpcId'] = _VpcId _pathURL += '&VpcId=' + _VpcId end unless _SecurityGroupId.nil? _parameters['SecurityGroupId'] = _SecurityGroupId _pathURL += '&SecurityGroupId=' + _SecurityGroupId end unless _PageNumber.nil? _parameters['PageNumber'] = _PageNumber _pathURL += '&PageNumber=' + _PageNumber end _PageSize ||= '50' _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.select { |key, _value| %w[id name links].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'servers' => servers } response end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_snapshots.rb000066400000000000000000000052641331327765100253600ustar00rootroot00000000000000# frozen_string_literal: true module 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 pageSize ||= '50' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_vpcs.rb000066400000000000000000000024461331327765100243100ustar00rootroot00000000000000# frozen_string_literal: true module 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 pageSize ||= '50' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_vpn_connections.rb000066400000000000000000000025651331327765100265440ustar00rootroot00000000000000# frozen_string_literal: true module 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_vpn_connections(options = {}) action = 'DescribeVpnConnections' sigNonce = randonStr time = Time.new.utc parameters = defalutVPCParameters(action, sigNonce, time) pathUrl = defaultAliyunVPCUri(action, sigNonce, time) _VpnGatewayId = options[:vpngatewayId] if _VpnGatewayId parameters['VpnGatewayId'] = _VpnGatewayId pathUrl += '&VpnGatewayId=' pathUrl += _VpnGatewayId end pageNumber = options[:pageNumber] pageSize = options[:pageSize] if pageNumber parameters['PageNumber'] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end pageSize ||= '50' parameters['PageSize'] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature VPCrequest( expects: [200, 203], method: 'GET', path: pathUrl ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_vpn_customergateways.rb000066400000000000000000000022351331327765100276220ustar00rootroot00000000000000# frozen_string_literal: true module 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_vpn_customergateways(options = {}) action = 'DescribeCustomerGateways' sigNonce = randonStr time = Time.new.utc parameters = defalutVPCParameters(action, sigNonce, time) pathUrl = defaultAliyunVPCUri(action, sigNonce, time) pageNumber = options[:pageNumber] pageSize = options[:pageSize] if pageNumber parameters['PageNumber'] = pageNumber pathUrl += '&PageNumber=' pathUrl += pageNumber end pageSize ||= '50' parameters['PageSize'] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature VPCrequest( expects: [200, 203], method: 'GET', path: pathUrl ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_vpn_gateways.rb000066400000000000000000000024761331327765100260470ustar00rootroot00000000000000# frozen_string_literal: true module 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_vpn_gateways(options = {}) action = 'DescribeVpnGateways' sigNonce = randonStr time = Time.new.utc parameters = defalutVPCParameters(action, sigNonce, time) pathUrl = defaultAliyunVPCUri(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 pageSize ||= '50' parameters['PageSize'] = pageSize pathUrl += '&PageSize=' pathUrl += pageSize signature = sign(@aliyun_accesskey_secret, parameters) pathUrl += '&Signature=' pathUrl += signature VPCrequest( expects: [200, 203], method: 'GET', path: pathUrl ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_vrouters.rb000066400000000000000000000033641331327765100252260ustar00rootroot00000000000000# frozen_string_literal: true module 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 pageSize ||= '50' 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.select { |key, _value| %w[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.3.2/lib/fog/aliyun/requests/compute/list_vswitchs.rb000066400000000000000000000026671331327765100252140ustar00rootroot00000000000000# frozen_string_literal: true module 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 pageSize ||= '50' 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/list_zones.rb000066400000000000000000000021741331327765100244710ustar00rootroot00000000000000# frozen_string_literal: true module 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.3.2/lib/fog/aliyun/requests/compute/modify_vpc.rb000066400000000000000000000045041331327765100244360ustar00rootroot00000000000000# frozen_string_literal: true module 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 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' => data[:security_groups][security_group_id.to_s] } response end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/modify_vswitch.rb000066400000000000000000000024451331327765100253370ustar00rootroot00000000000000# frozen_string_literal: true module 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_switch(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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/reboot_server.rb000066400000000000000000000020571331327765100251600ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/release_eip_address.rb000066400000000000000000000015731331327765100262640ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/start_server.rb000066400000000000000000000020321331327765100250140ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/stop_server.rb000066400000000000000000000020261331327765100246470ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/compute/unassociate_eip_address.rb000066400000000000000000000030371331327765100271570ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/000077500000000000000000000000001331327765100217375ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/copy_object.rb000066400000000000000000000024641331327765100245720ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/delete_bucket.rb000066400000000000000000000011611331327765100250620ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/delete_container.rb000066400000000000000000000014651331327765100255760ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/delete_object.rb000066400000000000000000000024101331327765100250510ustar00rootroot00000000000000# frozen_string_literal: true module 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 endpoint.nil? 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/get_bucket.rb000066400000000000000000000100301331327765100243720ustar00rootroot00000000000000# frozen_string_literal: true module 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] 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 ) 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 ) 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 ) XmlSimple.xml_in(ret.data[:body])['CORSRule'][0] if ret.data[:status] != 404 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 ) XmlSimple.xml_in(ret.data[:body])['Rule'][0] if ret.data[:status] != 404 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 ) 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 ) 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 ) XmlSimple.xml_in(ret.data[:body]) if ret.data[:status] != 404 end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/get_container.rb000066400000000000000000000030741331327765100251110ustar00rootroot00000000000000# frozen_string_literal: true module 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 = '' prefix = if container == '' || container == '.' || container.nil? nil else container + '/' end if prefix path += '?prefix=' + prefix path += '&marker=' + marker if marker path += '&max-keys=' + maxKeys if maxKeys path += '&delimiter=' + delimiter if delimiter elsif marker path += '?marker=' + marker path += '&max-keys=' + maxKeys if maxKeys path += '&delimiter=' + delimiter if delimiter elsif maxKeys path += '?max-keys=' + maxKeys path += '&delimiter=' + delimiter if delimiter elsif delimiter path += '?delimiter=' + delimiter end location = get_bucket_location(bucket) resource = bucket + '/' ret = request( expects: [200, 203, 400], method: 'GET', path: path, resource: resource, bucket: bucket ) xml = ret.data[:body] XmlSimple.xml_in(xml)['CommonPrefixes'] end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/get_containers.rb000066400000000000000000000033301331327765100252670ustar00rootroot00000000000000# frozen_string_literal: true module 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 path += '&marker=' + marker if marker path += '&max-keys=' + maxKeys if maxKeys path += '&delimiter=' + delimiter if delimiter elsif marker path += '?marker=' + marker path += '&max-keys=' + maxKeys if maxKeys path += '&delimiter=' + delimiter if delimiter elsif maxKeys path += '?max-keys=' + maxKeys path += '&delimiter=' + delimiter if delimiter elsif delimiter path += '?delimiter=' + delimiter end location = get_bucket_location(bucket) resource = bucket + '/' ret = request( expects: [200, 203, 400], method: 'GET', path: path, resource: resource, bucket: bucket ) xml = ret.data[:body] XmlSimple.xml_in(xml)['CommonPrefixes'] end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/get_object.rb000066400000000000000000000021201331327765100243640ustar00rootroot00000000000000# frozen_string_literal: true module 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 endpoint.nil? 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/get_object_http_url.rb000066400000000000000000000027211331327765100263140ustar00rootroot00000000000000# frozen_string_literal: true module 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 acl == 'private' expires_time = (Time.now.to_i + expires).to_s resource = bucket + '/' + object signature = sign('GET', expires_time, nil, resource) 'http://' + bucket + '.' + location + '.aliyuncs.com/' + object + '?OSSAccessKeyId=' + @aliyun_accesskey_id + '&Expires=' + expires_time + '&Signature=' + URI.encode(signature, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') elsif acl == 'public-read' || acl == 'public-read-write' 'http://' + bucket + '.' + location + '.aliyuncs.com/' + object else 'acl is wrong with value:' + acl end end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/get_object_https_url.rb000066400000000000000000000027461331327765100265060ustar00rootroot00000000000000# frozen_string_literal: true module 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 acl == 'private' expires_time = (Time.now.to_i + expires).to_s resource = bucket + '/' + object signature = sign('GET', expires_time, nil, resource) 'https://' + bucket + '.' + location + '.aliyuncs.com/' + object + '?OSSAccessKeyId=' + @aliyun_accesskey_id + '&Expires=' + expires_time + '&Signature=' + URI.encode(signature, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" ') elsif acl == 'public-read' || acl == 'public-read-write' 'https://' + bucket + '.' + location + '.aliyuncs.com/' + object else 'acl is wrong with value:' + acl end end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/head_object.rb000066400000000000000000000014041331327765100245120ustar00rootroot00000000000000# frozen_string_literal: true module 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 ) ret end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/list_buckets.rb000066400000000000000000000015421331327765100247610ustar00rootroot00000000000000# frozen_string_literal: true module 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 path += '&marker=' + marker if marker path += '&max-keys=' + maxKeys if maxKeys elsif marker path += '?marker=' + marker path += '&max-keys=' + maxKeys if maxKeys elsif maxKeys path += '?max-keys=' + maxKeys end ret = request( expects: [200, 203], method: 'GET', path: path ) xml = ret.data[:body] XmlSimple.xml_in(xml)['Buckets'][0] end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/list_objects.rb000066400000000000000000000046501331327765100247550ustar00rootroot00000000000000# frozen_string_literal: true module 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 path += '&marker=' + marker if marker path += '&max-keys=' + maxKeys if maxKeys path += '&delimiter=' + delimiter if delimiter elsif marker path += '?marker=' + marker path += '&max-keys=' + maxKeys if maxKeys path += '&delimiter=' + delimiter if delimiter elsif maxKeys path += '?max-keys=' + maxKeys path += '&delimiter=' + delimiter if delimiter elsif delimiter path += '?delimiter=' + delimiter end resource = bucket + '/' ret = request( expects: [200, 203, 400], method: 'GET', path: path, resource: resource, bucket: bucket ) xml = ret.data[:body] XmlSimple.xml_in(xml) end def list_multipart_uploads(bucket, endpoint, _options = {}) if endpoint.nil? 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 ) XmlSimple.xml_in(ret.data[:body])['Upload'] end def list_parts(bucket, object, endpoint, uploadid, _options = {}) if endpoint.nil? 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 ) XmlSimple.xml_in(ret.data[:body])['Part'] end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/put_bucket.rb000066400000000000000000000005501331327765100244310ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Storage class Aliyun class Real def put_bucket(bucketName) resource = bucketName + '/' request( expects: [200, 203], method: 'PUT', resource: resource, bucket: bucketName ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/put_container.rb000066400000000000000000000014041331327765100251350ustar00rootroot00000000000000# frozen_string_literal: true module 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 end end end fog-aliyun-0.3.2/lib/fog/aliyun/requests/storage/put_object.rb000066400000000000000000000134121331327765100244230ustar00rootroot00000000000000# frozen_string_literal: true module 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' return put_folder(bucket, object, endpoint) if file.nil? # put multiparts if object's size is over 100m return put_multipart_object(bucket, object, file) if file.size > 104_857_600 body = file.read resource = bucket + '/' + object 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 request( expects: [200, 203], method: 'PUT', path: object, bucket: bucket, resource: resource, body: body, endpoint: endpoint ) end def put_folder(bucket, folder, endpoint) if endpoint.nil? location = get_bucket_location(bucket) endpoint = 'http://' + location + '.aliyuncs.com' end path = folder + '/' resource = bucket + '/' + folder + '/' 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) upload = (uploads&.find { |tmpupload| tmpupload['Key'][0] == object }) uploadedSize = 0 start_partNumber = 1 if !upload.nil? uploadId = upload['UploadId'][0] parts = list_parts(bucket, object, endpoint, uploadId) if !parts.nil? && !parts.empty? if parts[-1]['Size'][0].to_i != 5_242_880 # 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 + 5_242_880 - 1) / 5_242_880 file.seek(uploadedSize) for i in start_partNumber..end_partNumber body = file.read(5_242_880) 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 endpoint.nil? 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 ) XmlSimple.xml_in(ret.data[:body])['UploadId'][0] end def upload_part(bucket, object, endpoint, partNumber, uploadId, body) if endpoint.nil? location = get_bucket_location(bucket) endpoint = 'http://' + location + '.aliyuncs.com' end path = object + '?partNumber=' + partNumber + '&uploadId=' + uploadId resource = bucket + '/' + path 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 endpoint.nil? location = get_bucket_location(bucket) endpoint = 'http://' + location + '.aliyuncs.com' end parts = list_parts(bucket, object, endpoint, uploadId, options = {}) request_part = [] return if parts.empty? 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 request( expects: 200, method: 'POST', path: path, bucket: bucket, resource: resource, endpoint: endpoint, body: body ) end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/storage.rb000066400000000000000000000157211331327765100204170ustar00rootroot00000000000000# frozen_string_literal: true require 'xmlsimple' module Fog module Storage class Aliyun < Fog::Service DEFAULT_REGION = 'cn-hangzhou' DEFAULT_SCHEME = 'http' DEFAULT_SCHEME_PORT = { 'http' => 80, 'https' => 443 }.freeze recognizes :aliyun_oss_endpoint, :aliyun_oss_location, :aliyun_region_id requires :aliyun_accesskey_id, :aliyun_accesskey_secret, :aliyun_oss_bucket 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_accesskey_id, :aliyun_secret_access_key and :aliyun_oss_bucket in order to create a connection. # :aliyun_oss_location will be replaced by :aliyun_region_id, and it has a default value cn-hangzhou # if :aliyun_oss_endpoint is not specified, it will be generated by method region_to_endpoint # # ==== 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_region_id attr_reader :aliyun_oss_bucket def initialize(options = {}) # initialize the parameters @aliyun_region_id = options[:aliyun_region_id] || options[:aliyun_oss_location] || DEFAULT_REGION @aliyun_oss_endpoint = options[:aliyun_oss_endpoint] || region_to_endpoint(@aliyun_region_id) @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 = [] missing_credentials << :aliyun_oss_bucket unless @aliyun_oss_bucket 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] || {} endpoint = @aliyun_oss_endpoint @aliyun_oss_endpoint = "#{DEFAULT_SCHEME}://#{endpoint}" unless endpoint.start_with?(DEFAULT_SCHEME) uri = URI.parse(@aliyun_oss_endpoint) @host = uri.host @path = uri.path @scheme = uri.scheme || DEFAULT_SCHEME @port = uri.port || DEFAULT_SCHEME_PORT[@scheme] @persistent = options[:persistent] || false end def reload @connection.reset end def region_to_endpoint(region = nil) case region.to_s when '' "oss-#{DEFAULT_REGION}.aliyuncs.com" else "oss-#{region}.aliyuncs.com" end 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] tmpHost = if bucket bucket + '.' + host else host end @connection = Fog::Core::Connection.new("#{scheme}://#{tmpHost}", @persistent, @connection_options) contentType = params[:contentType] begin headers = '' params[:headers]&.each do |k, v| headers += "#{k}:#{v}\n" if k != 'Range' 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 = '' canonicalizedResource = if resource '/' + resource else '/' end canonicalizedOSSHeaders = headers || '' contentTypeStr = contentType || '' 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] = '' signature end end class Mock def initialize(options = {}) @aliyun_oss_endpoint = options[:aliyun_oss_endpoint] @aliyun_region_id = options[:aliyun_region_id] @aliyun_accesskey_id = options[:aliyun_accesskey_id] @aliyun_accesskey_secret = options[:aliyun_accesskey_secret] @aliyun_oss_bucket = options[:aliyun_oss_bucket] @connection_options = options[:connection_options] || {} end end end end end fog-aliyun-0.3.2/lib/fog/aliyun/version.rb000066400000000000000000000001321331327765100204260ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun VERSION = '0.3.2' end end fog-aliyun-0.3.2/lib/fog/bin/000077500000000000000000000000001331327765100156675ustar00rootroot00000000000000fog-aliyun-0.3.2/lib/fog/bin/aliyun.rb000066400000000000000000000014401331327765100175140ustar00rootroot00000000000000# frozen_string_literal: true class 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.3.2/spec/000077500000000000000000000000001331327765100145305ustar00rootroot00000000000000fog-aliyun-0.3.2/spec/fog/000077500000000000000000000000001331327765100153035ustar00rootroot00000000000000fog-aliyun-0.3.2/spec/fog/aliyun_spec.rb000066400000000000000000000003521331327765100201430ustar00rootroot00000000000000# frozen_string_literal: true require 'spec_helper' describe Fog::Aliyun do it 'has a version number' do expect(Fog::Aliyun::VERSION).not_to be nil end it 'does something useful' do expect(true).to eq(true) end end fog-aliyun-0.3.2/spec/spec_helper.rb000066400000000000000000000001571331327765100173510ustar00rootroot00000000000000# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'fog/aliyun'