pax_global_header00006660000000000000000000000064142771076020014520gustar00rootroot0000000000000052 comment=e3d22408a0b3a6b404a4a9f6746f933fdf088f73 fog-aliyun-0.4.0/000077500000000000000000000000001427710760200135735ustar00rootroot00000000000000fog-aliyun-0.4.0/.gitignore000066400000000000000000000003521427710760200155630ustar00rootroot00000000000000.idea .idea/* *.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 morethan100m *.log fog-aliyun-0.4.0/.rspec000066400000000000000000000000371427710760200147100ustar00rootroot00000000000000--format documentation --color fog-aliyun-0.4.0/.rubocop.yml000066400000000000000000000010131427710760200160400ustar00rootroot00000000000000inherit_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.4.0/.rubocop_todo.yml000066400000000000000000000116271427710760200171010ustar00rootroot00000000000000# 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.4.0/.ruby-gemset000066400000000000000000000000131427710760200160310ustar00rootroot00000000000000fog-aliyun fog-aliyun-0.4.0/.ruby-version000066400000000000000000000000061427710760200162340ustar00rootroot000000000000003.0.4 fog-aliyun-0.4.0/.travis.yml000066400000000000000000000001141427710760200157000ustar00rootroot00000000000000language: ruby rvm: - 2.1.6 before_install: gem install bundler -v 1.10.6 fog-aliyun-0.4.0/CHANGELOG.md000066400000000000000000000156141427710760200154130ustar00rootroot00000000000000## 0.4.1 (Unreleased) ## 0.4.0 (August 17, 2022) IMPROVEMENTS: - Ruby 3 [GH-158](https://github.com/fog/fog-aliyun/pull/158) ## 0.3.19 (August 17, 2020) IMPROVEMENTS: - Upgrade oss ruby sdk to support setting log level [GH-152](https://github.com/fog/fog-aliyun/pull/152) ## 0.3.18 (August 03, 2020) IMPROVEMENTS: - reconstruct perform test [GH-148](https://github.com/fog/fog-aliyun/pull/148) - Reconstruct fog-aliyun by using oss [GH-147](https://github.com/fog/fog-aliyun/pull/147) - reconstruct cover case test [GH-146](https://github.com/fog/fog-aliyun/pull/146) - reconstruct case test [GH-144](https://github.com/fog/fog-aliyun/pull/144) - reconstruct parts two of file [GH-143](https://github.com/fog/fog-aliyun/pull/143) - implement blobstore for cloud_controller_ng [GH-142](https://github.com/fog/fog-aliyun/pull/142) - reconstruct parts of file [GH-141](https://github.com/fog/fog-aliyun/pull/141) - reconstruct the files [GH-140](https://github.com/fog/fog-aliyun/pull/140) - reconstruct the directory [GH-139](https://github.com/fog/fog-aliyun/pull/139) - reconstruct the directories [GH-138](https://github.com/fog/fog-aliyun/pull/138) - improve files.get code [GH-137](https://github.com/fog/fog-aliyun/pull/137) - add testcase for testing head notexistfile [GH-136](https://github.com/fog/fog-aliyun/pull/136) - improve head_object using oss sdk [GH-135](https://github.com/fog/fog-aliyun/pull/135) BUG FIXES: - fix files all options problem [GH-149](https://github.com/fog/fog-aliyun/pull/149) ## 0.3.17 (July 06, 2020) IMPROVEMENTS: - adater oss_sdk_log_path [GH-125](https://github.com/fog/fog-aliyun/pull/125) - update ruby sdk to 0.7.3 [GH-124](https://github.com/fog/fog-aliyun/pull/124) - adapter maxkeys conversion problem [GH-123](https://github.com/fog/fog-aliyun/pull/123) - [Enhance tests][Auth & Connectivity scenarios] Test that API cannot be accessed using incorrect credentials [GH-117](https://github.com/fog/fog-aliyun/pull/117) - [Enhance tests][Auth & Connectivity scenarios] Test that API can be accessed using valid credentials [GH-116](https://github.com/fog/fog-aliyun/pull/116) - adapter custom log environment variable [GH-114](https://github.com/fog/fog-aliyun/pull/114) - [Enhance tests][Buckets scenarios] (NEGATIVE TEST) Test that error is thrown when trying to access non-existing bucket [GH-110](https://github.com/fog/fog-aliyun/pull/110) - [Enhance tests][Buckets scenarios] (NEGATIVE TEST) Test that error is thrown when trying to create already existing bucket [GH-109](https://github.com/fog/fog-aliyun/pull/109) - [Enhance tests][Buckets scenarios] Test that it is possible to destroy a bucket [GH-108](https://github.com/fog/fog-aliyun/pull/108) - [Enhance tests][Buckets scenarios] Test that it is possible to create a new bucket [GH-107](https://github.com/fog/fog-aliyun/pull/107) - [Enhance tests][Buckets scenarios] Test that it is possible to list all buckets [GH-105](https://github.com/fog/fog-aliyun/pull/105) - [Enhance tests][Files & Directory scenarios] Test getting bucket when directory exists named with the same name as a bucket [GH-101](https://github.com/fog/fog-aliyun/pull/101) - [Enhance tests][Files & Directory scenarios] Test file copy operations [GH-100](https://github.com/fog/fog-aliyun/pull/100) - reset the last PR [GH-133](https://github.com/fog/fog-aliyun/pull/133) - improve put_object_with_body and head_object using sdk do_request [GH-131](https://github.com/fog/fog-aliyun/pull/131) BUG FIXES: - fix max key again [GH-128](https://github.com/fog/fog-aliyun/pull/128) - fix downloading object when pushing app twice [GH-127](https://github.com/fog/fog-aliyun/pull/127) - fix max key [GH-126](https://github.com/fog/fog-aliyun/pull/126) - fix max-keys conversion problem [GH-121](https://github.com/fog/fog-aliyun/pull/121) - fix @aliyun_oss_sdk_log_path is nil [GH-132](https://github.com/fog/fog-aliyun/pull/132) ## 0.3.16 (June 18, 2020) IMPROVEMENTS: - [Enhance tests][Files & Directory scenarios] Test get nested directories and files in nested directory [GH-98](https://github.com/fog/fog-aliyun/pull/98) - remove get_bucket_location and use ruby sdk to improve performance when uploading object [GH-97](https://github.com/fog/fog-aliyun/pull/97) - using bucket_exist to checking bucket [GH-95](https://github.com/fog/fog-aliyun/pull/95) - add change log [GH-94](https://github.com/fog/fog-aliyun/pull/94) BUG FIXES: - fix delete all of files bug when specifying a prefix [GH-102](https://github.com/fog/fog-aliyun/pull/102) ## 0.3.15 (June 05, 2020) BUG FIXES: - change dependence ruby sdk to gems [GH-92](https://github.com/fog/fog-aliyun/pull/92) ## 0.3.13 (June 02, 2020) IMPROVEMENTS: - using ruby sdk to delete object [GH-90](https://github.com/fog/fog-aliyun/pull/90) ## 0.3.12 (May 28, 2020 ) BUG FIXES: - add missing dependence [GH-88](https://github.com/fog/fog-aliyun/pull/88) ## 0.3.11 (May 25, 2020) IMPROVEMENTS: - using oss ruby sdk to improve downloading object performance [GH-86](https://github.com/fog/fog-aliyun/pull/86) - Add performance tests [GH-85](https://github.com/fog/fog-aliyun/pull/85) - [Enhance tests][Entity operations]Add tests for each type of entity that validates the CURD operations [GH-84](https://github.com/fog/fog-aliyun/pull/84) - [Enhance tests][Auth & Connectivity scenarios] Test region is selected according to provider configuration [GH-83](https://github.com/fog/fog-aliyun/pull/83) - [Enhance tests][Files & Directory scenarios] test file listing using parameters such as prefix, marker, delimeter and maxKeys [GH-82](https://github.com/fog/fog-aliyun/pull/82) - [Enhance tests][Files & Directory scenarios]test directory listing using parameters such as prefix, marker, delimeter and maxKeys [GH-81](https://github.com/fog/fog-aliyun/pull/81) - [Enhance tests][Files & Directory scenarios]Test that it is possible to upload (write) large file (multi part upload) [GH-79](https://github.com/fog/fog-aliyun/pull/79) - upgrade deprecated code [GH-78](https://github.com/fog/fog-aliyun/pull/78) - improve fog/integration_spec [GH-77](https://github.com/fog/fog-aliyun/pull/77) - [Enhance tests][Files & Directory scenarios]Test that it is possible to upload (write) a file [GH-76](https://github.com/fog/fog-aliyun/pull/76) - upgrade deprecated code [GH-74](https://github.com/fog/fog-aliyun/pull/74) - support https scheme [GH-71](https://github.com/fog/fog-aliyun/pull/71) - [Enhance tests][Files & Directory scenarios]Test that it is possible to destroy a file/directory [GH-69](https://github.com/fog/fog-aliyun/pull/69) - improve fog/integration_spec [GH-68](https://github.com/fog/fog-aliyun/pull/68) - Implement basic integration tests [GH-66](https://github.com/fog/fog-aliyun/pull/66) ## 0.3.10 (May 07, 2020) IMPROVEMENTS: - Set max limitation to 1000 when get objects [GH-64](https://github.com/fog/fog-aliyun/pull/64) ## 0.3.9 (May 07, 2020) BUG FIXES: - diectories.get supports options to filter the specified objects [GH-62](https://github.com/fog/fog-aliyun/pull/62) fog-aliyun-0.4.0/CODE_OF_CONDUCT.md000066400000000000000000000026321427710760200163750ustar00rootroot00000000000000# 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.4.0/Gemfile000066400000000000000000000001761427710760200150720ustar00rootroot00000000000000# frozen_string_literal: true source 'https://rubygems.org' # Specify your gem's dependencies in fog-aliyun.gemspec gemspec fog-aliyun-0.4.0/LICENSE.txt000066400000000000000000000020641427710760200154200ustar00rootroot00000000000000The 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.4.0/README.md000066400000000000000000000231541427710760200150570ustar00rootroot00000000000000# 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). ## Testing To run test suite use the following command: ``` rake spec ``` ### Code coverage To run test suite with code coverage: ``` export COVERAGE=true rake spec ``` The result will be generated in `coverage` folder. ### Integration tests To run integration tests please prepare a set of AliCloud credentials to be used by integration tests. Define the credentials and bucket in `~/.fog` file in using following format: ``` default: aliyun_accesskey_id: "...access key..." # You can create a set of credentials aliyun_accesskey_secret: "...secret..." # using Alicloud console portal aliyun_region_id: "...region name..." # Example: cn-shanghai aliyun_oss_bucket: "...name of the bucket..." # Example: fog-integration-test-bucket ``` WARNING: Do NOT use any productive account credentials and buckets for the testing, it may be harmful to your data! The tests are using [https://github.com/aliyun/aliyun-cli#installation](Aliyun CLI) to setup integration bucket and content for tests, please install it locally before running integration tests. Aliyun CLI will be configured automatically as part of test execution using the credentials provided for fog connection. Then run the test suite with `INTEGRATION` environment variable to activate integration tests: ``` export INTEGRATION=true rake spec ``` ### Performance test Performance tests are providing memory consumption report for download/upload operations. ``` export PERFORMANCE=true rake spec ``` ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). fog-aliyun-0.4.0/Rakefile000066400000000000000000000002211427710760200152330ustar00rootroot00000000000000# frozen_string_literal: true require 'bundler/gem_tasks' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) task default: :spec fog-aliyun-0.4.0/bin/000077500000000000000000000000001427710760200143435ustar00rootroot00000000000000fog-aliyun-0.4.0/bin/console000077500000000000000000000005551427710760200157400ustar00rootroot00000000000000#!/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.4.0/bin/setup000066400000000000000000000001631427710760200154260ustar00rootroot00000000000000#!/bin/bash set -euo pipefail IFS=$'\n\t' bundle install # Do any other automated setup that you need to do here fog-aliyun-0.4.0/fog-aliyun.gemspec000066400000000000000000000030331427710760200172110ustar00rootroot00000000000000# 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, Guimin He'] spec.email = ['dengqinsi@sina.com', 'guimin.hgm@alibaba-inc.com'] spec.summary = 'Fog provider for Alibaba Cloud 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', '~> 3.4' spec.add_development_dependency 'pry-nav' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec' spec.add_development_dependency 'rubocop' spec.add_development_dependency 'simplecov' spec.add_development_dependency 'memory_profiler' spec.add_development_dependency 'aliyun-sdk', '~> 0.8.0' spec.add_dependency 'addressable', '~> 2.8.0' spec.add_dependency 'aliyun-sdk', '~> 0.8.0' 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.4.0/lib/000077500000000000000000000000001427710760200143415ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/000077500000000000000000000000001427710760200151145ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun.rb000066400000000000000000000006571427710760200167520ustar00rootroot00000000000000# frozen_string_literal: true require 'fog/core' require 'fog/json' require File.expand_path('../aliyun/version', __FILE__) module Fog module Aliyun extend Fog::Provider # Services autoload :Compute, File.expand_path('../aliyun/compute', __FILE__) autoload :Storage, File.expand_path('../aliyun/storage', __FILE__) service(:compute, 'Compute') service(:storage, 'Storage') end end fog-aliyun-0.4.0/lib/fog/aliyun/000077500000000000000000000000001427710760200164155ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun/compute.rb000066400000000000000000000377361427710760200204360ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 model :flavor collection :flavors ## 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 # PublicIpAddress request :allocate_public_ip_address 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 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 = Addressable::URI.encode_component(parTimeFormat, Addressable::URI::CharacterClasses::UNRESERVED + '|') '?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 defaultAliyunQueryParameters(action, sigNonce, time) { 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: time.strftime('%Y-%m-%dT%H:%M:%SZ') } end def defaultAliyunVPCUri(action, sigNonce, time) parTimeFormat = time.strftime('%Y-%m-%dT%H:%M:%SZ') urlTimeFormat = Addressable::URI.encode_component(parTimeFormat, Addressable::URI::CharacterClasses::UNRESERVED + '|') '?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 defaultParameters(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 # This method should be considered deprecated and replaced with sign_without_encoding, which is better for using querystring hashes and not # building querystrings with string concatination. def sign(accessKeySecret, parameters) signature = sign_without_encoding(accessKeySecret, parameters) Addressable::URI.encode_component(signature, Addressable::URI::CharacterClasses::UNRESERVED + '|') end def sign_without_encoding(accessKeySecret, parameters) sortedParameters = parameters.sort canonicalizedQueryString = '' sortedParameters.each do |k, v| canonicalizedQueryString += '&' + Addressable::URI.encode_component(k, Addressable::URI::CharacterClasses::UNRESERVED + '|') + '=' + Addressable::URI.encode_component(v, Addressable::URI::CharacterClasses::UNRESERVED + '|') end canonicalizedQueryString[0] = '' stringToSign = 'GET&%2F&' + Addressable::URI.encode_component(canonicalizedQueryString, Addressable::URI::CharacterClasses::UNRESERVED + '|') key = accessKeySecret + '&' digVer = OpenSSL::Digest.new('sha1') digest = OpenSSL::HMAC.digest(digVer, key, stringToSign) signature = Base64.encode64(digest) signature[-1] = '' signature end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/models/000077500000000000000000000000001427710760200177005ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun/models/compute/000077500000000000000000000000001427710760200213545ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun/models/compute/eip_address.rb000066400000000000000000000034021427710760200241620ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/eip_addresses.rb000066400000000000000000000013741427710760200245200ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/flavor.rb000066400000000000000000000024251427710760200231750ustar00rootroot00000000000000require 'fog/core/model' module Fog module Compute class Aliyun class Flavor < Fog::Model attribute :base_line_credit, aliases: 'BaseLineCredit' attribute :cpu_core_count, aliases: 'CpuCoreCount' attribute :eni_private_ip_quantitiy, aliases: 'EniPrivateIpAddressQuantity' attribute :eni_quantity, aliases: 'EniQuantity' attribute :gpu_amount, aliases: 'GPUAmount' attribute :gpu_spec, aliases: 'GPUSpec' attribute :intial_credit, aliases: 'IntialCredit' attribute :instance_bandwidth_rx, aliases: 'InstanceBandwidthRx' attribute :instance_bandwidth_tx, aliases: 'InstanceBandwidthTx' attribute :instance_family_level, aliases: 'InstanceFamilyLevel' attribute :instance_pps_rx, aliases: 'InstancePpsRx' attribute :instance_pps_tx, aliases: 'InstancePpsTx' attribute :instance_type_family, alieses: 'InstanceTypeFamily' attribute :instance_type_id, aliases: 'InstanceTypeId' attribute :local_storage_amount, aliases: 'LocalStorageAmount' attribute :local_storage_capacity, aliases: 'LocalStorageCapacity' attribute :local_storage_category, aliases: 'LocalStorageCategory' attribute :memory_size, alieses: 'MemorySize' end end end end fog-aliyun-0.4.0/lib/fog/aliyun/models/compute/flavors.rb000066400000000000000000000004561427710760200233620ustar00rootroot00000000000000module Fog module Compute class Aliyun class Flavors < Fog::Collection model Fog::Compute::Aliyun::Flavor def all data = Fog::JSON.decode(service.list_server_types.body)['InstanceTypes']['InstanceType'] load(data) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/models/compute/image.rb000066400000000000000000000043041427710760200227640ustar00rootroot00000000000000# 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) unless attributes['DiskDeviceMappings']['DiskDeviceMapping'].empty? self.snapshot_id = attributes['DiskDeviceMappings']['DiskDeviceMapping'][0]['SnapshotId'] end 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.4.0/lib/fog/aliyun/models/compute/images.rb000066400000000000000000000014371427710760200231530ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/route_entry.rb000066400000000000000000000027201427710760200242610ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/route_entrys.rb000066400000000000000000000022301427710760200244400ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/route_table.rb000066400000000000000000000031021427710760200242020ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/route_tables.rb000066400000000000000000000012711427710760200243720ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/security_group.rb000066400000000000000000000050601427710760200247650ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/security_group_rule.rb000066400000000000000000000037621427710760200260230ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/security_group_rules.rb000066400000000000000000000013741427710760200262030ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/security_groups.rb000066400000000000000000000015061427710760200251510ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/server.rb000066400000000000000000000105651427710760200232160ustar00rootroot00000000000000# 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' attribute :vswitch_id, aliases: 'VSwitchId' attribute :key_pair_name, aliases: 'KeyPairName' attribute :user_data, aliases: 'UserData' 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 def save(options = {}) requires :image_id, :security_group_ids, :type options[:VSwitchId] = vswitch_id if vswitch_id options[:KeyPairName] = key_pair_name if key_pair_name options[:UserData] = user_data if user_data options[:InstanceName] = name if name data = Fog::JSON.decode(service.create_server(image_id, security_group_ids, type, options).body) merge_attributes(data) 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.4.0/lib/fog/aliyun/models/compute/servers.rb000066400000000000000000000031071427710760200233730ustar00rootroot00000000000000# 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 = {}) data = Fog::JSON.decode(service.list_servers(options).body)['Instances']['Instance'] load(data) 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.4.0/lib/fog/aliyun/models/compute/snapshot.rb000066400000000000000000000031201427710760200235340ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/snapshots.rb000066400000000000000000000023721427710760200237270ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/volume.rb000066400000000000000000000063501427710760200232140ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/volumes.rb000066400000000000000000000106671427710760200234050ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/vpc.rb000066400000000000000000000041651427710760200224770ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/vpcs.rb000066400000000000000000000036561427710760200226660ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/vrouter.rb000066400000000000000000000021501427710760200234050ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/vrouters.rb000066400000000000000000000031561427710760200235770ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/vswitch.rb000066400000000000000000000036021427710760200233710ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/compute/vswitches.rb000066400000000000000000000034451427710760200237260ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/models/storage/000077500000000000000000000000001427710760200213445ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun/models/storage/directories.rb000066400000000000000000000025521427710760200242110ustar00rootroot00000000000000# frozen_string_literal: true require 'fog/core/collection' require 'fog/aliyun/models/storage/directory' module Fog module Aliyun class Storage class Directories < Fog::Collection model Fog::Aliyun::Storage::Directory def all buckets = service.get_service[0] return nil if buckets.size < 1 data = [] i = 0 buckets.each do |b| data[i] = { key: b.name } i += 1 end load(data) end def get(key, options = {}) data = service.get_bucket(key, options) directory = new(:key => key, :is_persisted => true) options = data[1] options[:max_keys] = options[:limit] directory.files.merge_attributes(options) objects = [] i = 0 data[0].each do |o| objects[i] = { 'Key' => o.key, 'Type' => o.type, 'Size' => o.size, 'ETag' => o.etag, 'LastModified' => o.last_modified } i += 1 end directory.files.load(objects) directory rescue AliyunOssSdk::ServerError => error if error.error_code == "NoSuchBucket" nil else raise(error) end end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/models/storage/directory.rb000066400000000000000000000065301427710760200237010ustar00rootroot00000000000000# frozen_string_literal: true require 'fog/core/model' require 'fog/aliyun/models/storage/files' module Fog module Aliyun class Storage class Directory < Fog::Model VALID_ACLS = ['private', 'public-read', 'public-read-write'] attr_reader :acl identity :key, :aliases => ['Key', 'Name', 'name'] attribute :creation_date, :aliases => 'CreationDate', :type => 'time' def acl=(new_acl) unless VALID_ACLS.include?(new_acl) raise ArgumentError.new("acl must be one of [#{VALID_ACLS.join(', ')}]") else @acl = new_acl end end def destroy requires :key service.delete_bucket(key) true rescue AliyunOssSdk::ServerError => error if error.error_code == "NoSuchBucket" false else raise(error) end end def destroy!(options = {}) requires :key options = { timeout: Fog.timeout, interval: Fog.interval, }.merge(options) begin clear! Fog.wait_for(options[:timeout], options[:interval]) { objects_keys.size == 0 } service.delete_bucket(key) true rescue AliyunOssSdk::ServerError false end end def location region = @aliyun_region_id region ||= Storage::DEFAULT_REGION @location = (bucket_location || 'oss-' + region) end # NOTE: you can't change the region once the bucket is created def location=(new_location) new_location = 'oss-' + new_location unless new_location.start_with?('oss-') @location = new_location end def files @files ||= begin Fog::Aliyun::Storage::Files.new( directory: self, service: service ) end end # TODO def public=(new_public) nil end # TODO def public_url nil end def save requires :key options = {} options['x-oss-acl'] = acl if acl # https://help.aliyun.com/document_detail/31959.html # if !persisted? # # There is a sdk bug that location can not be set # options[:location] = location # end service.put_bucket(key, options) attributes[:is_persisted] = true true end def persisted? # is_persisted is true in case of directories.get or after #save # creation_date is set in case of directories.all attributes[:is_persisted] || !!attributes[:creation_date] end private def bucket_location requires :key return nil unless persisted? service.get_bucket_location(key) end def objects_keys requires :key bucket_query = service.get_bucket(key) object_keys = [] i = 0 bucket_query[0].each do |o| object_keys[i] = o.key i += 1 end object_keys end def clear! requires :key service.delete_multiple_objects(key, objects_keys) if objects_keys.size > 0 end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/models/storage/file.rb000066400000000000000000000162521427710760200226160ustar00rootroot00000000000000# frozen_string_literal: true require 'fog/core/model' module Fog module Aliyun class Storage class File < Fog::Model identity :key, aliases: ['Key', 'Name', 'name'] attr_writer :body attribute :cache_control, aliases: 'Cache-Control' attribute :content_encoding, aliases: 'Content-Encoding' attribute :date, aliases: 'Date' attribute :content_length, aliases: ['Content-Length', 'Size'], type: :integer attribute :content_md5, aliases: 'Content-MD5' attribute :content_type, aliases: 'Content-Type' attribute :connection, aliases: 'Connection' attribute :content_disposition, aliases: 'Content-Disposition' attribute :etag, aliases: ['Etag', 'ETag'] attribute :expires, aliases: 'Expires' attribute :metadata attribute :owner, aliases: 'Owner' 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', 'x_oss_object_type'] # @note Chunk size to use for multipart uploads. # Use small chunk sizes to minimize memory. E.g. 5242880 = 5mb attr_reader :multipart_chunk_size def multipart_chunk_size=(mp_chunk_size) raise ArgumentError.new("minimum multipart_chunk_size is 5242880") if mp_chunk_size < 5242880 @multipart_chunk_size = mp_chunk_size end def acl requires :directory, :key service.get_object_acl(directory.key, key) end def acl=(new_acl) valid_acls = ['private', 'public-read', 'public-read-write', 'default'] unless valid_acls.include?(new_acl) raise ArgumentError.new("acl must be one of [#{valid_acls.join(', ')}]") end @acl = new_acl end def body return attributes[:body] if attributes[:body] return '' unless last_modified file = collection.get(identity) if file attributes[:body] = file.body else attributes[:body] = '' end end def body=(new_body) attributes[:body] = new_body end def directory @directory end # Copy object from one bucket to other bucket. # # required attributes: directory, key # # @param target_directory_key [String] # @param target_file_key [String] # @param options [Hash] options for copy_object method # @return [String] Fog::Aliyun::Files#head status of directory contents # def copy(target_directory_key, target_file_key, options = {}) requires :directory, :key service.copy_object(directory.key, key, target_directory_key, target_file_key, options) target_directory = service.directories.new(:key => target_directory_key) target_directory.files.head(target_file_key) end def destroy(options = {}) requires :directory, :key # TODO support versionId # attributes[:body] = nil if options['versionId'] == version service.delete_object(directory.key, key, options) true end remove_method :metadata def metadata attributes.reject {|key, value| !(key.to_s =~ /^x-oss-/)} end remove_method :metadata= def metadata=(new_metadata) merge_attributes(new_metadata) end remove_method :owner= def owner=(new_owner) if new_owner attributes[:owner] = { :display_name => new_owner['DisplayName'] || new_owner[:display_name], :id => new_owner['ID'] || new_owner[:id] } end end # Set Access-Control-List permissions. # # valid new_publics: public_read, private # # @param [String] new_public # @return [String] new_public # def public=(new_public) if new_public @acl = 'public-read' else @acl = 'private' end 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] No need to use # @return [String] url # def url(expires, options = {}) requires :key service.get_object_http_url_public(directory.key, key, expires) end def save(options = {}) requires :body, :directory, :key options['x-oss-object-acl'] ||= @acl if @acl options['Cache-Control'] = cache_control if cache_control options['Content-Disposition'] = content_disposition if content_disposition options['Content-Encoding'] = content_encoding if content_encoding options['Content-MD5'] = content_md5 if content_md5 options['Content-Type'] = content_type if content_type options['Expires'] = expires if expires options.merge!(metadata) self.multipart_chunk_size = 5242880 if !multipart_chunk_size && Fog::Storage.get_body_size(body) > 5368709120 if multipart_chunk_size && Fog::Storage.get_body_size(body) >= multipart_chunk_size && body.respond_to?(:read) multipart_save(options) else service.put_object(directory.key, key, body, options) end self.etag = self.etag.gsub('"','') if self.etag self.content_length = Fog::Storage.get_body_size(body) self.content_type ||= Fog::Storage.get_content_type(body) true end private def directory=(new_directory) @directory = new_directory end def multipart_save(options) # Initiate the upload upload_id = service.initiate_multipart_upload(directory.key, key, options) # Store ETags of upload parts part_tags = [] # Upload each part # TODO: optionally upload chunks in parallel using threads # (may cause network performance problems with many small chunks) # TODO: Support large chunk sizes without reading the chunk into memory if body.respond_to?(:rewind) body.rewind rescue nil end while (chunk = body.read(multipart_chunk_size)) do part_upload = service.upload_part(directory.key, key, upload_id, part_tags.size + 1, chunk) part_tags << part_upload end if part_tags.empty? #it is an error to have a multipart upload with no parts part_upload = service.upload_part(directory.key, key, upload_id, 1, '') part_tags << part_upload end rescue # Abort the upload & reraise service.abort_multipart_upload(directory.key, key, upload_id) if upload_id raise else # Complete the upload service.complete_multipart_upload(directory.key, key, upload_id, part_tags) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/models/storage/files.rb000066400000000000000000000077001427710760200227770ustar00rootroot00000000000000# frozen_string_literal: true require 'fog/core/collection' require 'fog/aliyun/models/storage/file' require 'aliyun/oss' module Fog module Aliyun class Storage class Files < Fog::Collection attribute :directory attribute :limit attribute :prefix, :aliases => 'Prefix' attribute :path attribute :common_prefixes, :aliases => 'CommonPrefixes' attribute :delimiter, :aliases => 'Delimiter' attribute :is_truncated, :aliases => 'IsTruncated' attribute :marker, :aliases => 'Marker' attribute :max_keys, :aliases => ['MaxKeys', 'max-keys'] model Fog::Aliyun::Storage::File def all(options = {}) requires :directory options = { 'delimiter': delimiter, 'marker': marker, 'max-keys': max_keys.to_i, 'prefix': prefix }.merge!(options) options = options.reject {|key,value| value.nil? || value.to_s.empty?} merge_attributes(options) parent = directory.collection.get( directory.key, options ) if parent merge_attributes(parent.files.attributes) load(parent.files.map {|file| file.attributes}) else nil end end alias_method :each_file_this_page, :each def each if !block_given? self else subset = dup.all subset.each_file_this_page { |f| yield f } while subset.is_truncated subset = subset.all(marker: subset.last.key) subset.each_file_this_page { |f| yield f } end self end end def get(key, options = {}, &block) requires :directory begin data = service.get_object(directory.key, key, options, &block) normalize_headers(data) file_data = data.headers.merge({ :body => data.body, :key => key }) new(file_data) rescue Exception => error if error.respond_to?(:http_code) && error.http_code.to_i == 404 nil else raise(error) end end end # @param options[Hash] No need to use def get_url(key, options = {}) requires :directory service.get_object_http_url_public(directory.key, key, 3600) end # @param options[Hash] No need to use def get_http_url(key, expires, options = {}) requires :directory service.get_object_http_url_public(directory.key, key, expires) end # @param options[Hash] No need to use def get_https_url(key, expires, options = {}) requires :directory service.get_object_https_url_public(directory.key, key, expires) end def head(key, options = {}) requires :directory begin data = service.head_object(directory.key, key, options) normalize_headers(data) file_data = data.headers.merge({ :key => key }) new(file_data) rescue Exception => error if error.respond_to?(:http_code) && error.http_code.to_i == 404 nil else raise(error) end end end def new(attributes = {}) requires :directory super({ :directory => directory }.merge!(attributes)) end def normalize_headers(data) data.headers[:last_modified] = Time.parse(data.headers[:last_modified]) data.headers[:etag] = data.headers[:etag].gsub('"','') end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/000077500000000000000000000000001427710760200202705ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun/requests/compute/000077500000000000000000000000001427710760200217445ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun/requests/compute/allocate_eip_address.rb000066400000000000000000000036341427710760200264250ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/allocate_public_ip_address.rb000066400000000000000000000024021427710760200276060ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/associate_eip_address.rb000066400000000000000000000030301427710760200266020ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/attach_disk.rb000066400000000000000000000050151427710760200245500ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(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 += Addressable::URI.encode_component(device, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/create_disk.rb000066400000000000000000000114301427710760200245450ustar00rootroot00000000000000# 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 = defaultParameters(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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/create_image.rb000066400000000000000000000047371427710760200247110ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/create_security_group.rb000066400000000000000000000046171427710760200267070ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/create_security_group_egress_ip_rule.rb000066400000000000000000000041651427710760200317740ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['SecurityGroupId'] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters['DestCidrIp'] = destCidrIp pathUrl += '&DestCidrIp=' pathUrl += Addressable::URI.encode_component(destCidrIp, Addressable::URI::CharacterClasses::UNRESERVED + '|') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/create_security_group_egress_sg_rule.rb000066400000000000000000000044301427710760200317700ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(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 += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/create_security_group_ip_rule.rb000066400000000000000000000041621427710760200304210ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['SecurityGroupId'] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters['SourceCidrIp'] = sourceCidrIp pathUrl += '&SourceCidrIp=' pathUrl += Addressable::URI.encode_component(sourceCidrIp, Addressable::URI::CharacterClasses::UNRESERVED + '|') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/create_security_group_sg_rule.rb000066400000000000000000000044711427710760200304250ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(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 += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/create_server.rb000066400000000000000000000166501427710760200251320ustar00rootroot00000000000000# 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 = defaultParameters(_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 end _InternetMaxBandwidthIn = options[:InternetMaxBandwidthIn] if _InternetMaxBandwidthIn _parameters['InternetMaxBandwidthIn'] = _InternetMaxBandwidthIn _pathURL += '&InternetMaxBandwidthIn=' + _InternetMaxBandwidthIn end _InternetMaxBandwidthOut = options[:InternetMaxBandwidthOut] if _InternetMaxBandwidthOut _parameters['InternetMaxBandwidthOut'] = _InternetMaxBandwidthOut _pathURL += '&InternetMaxBandwidthOut=' + _InternetMaxBandwidthOut end _KeyPairName = options[:KeyPairName] if _KeyPairName _parameters['KeyPairName'] = _KeyPairName _pathURL += '&KeyPairName=' + _KeyPairName end _UserData = options[:UserData] if _UserData _parameters['UserData'] = _UserData _pathURL += '&UserData=' + _UserData 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.4.0/lib/fog/aliyun/requests/compute/create_snapshot.rb000066400000000000000000000023441427710760200254560ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/create_vpc.rb000066400000000000000000000025051427710760200244060ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['CidrBlock'] = cidrBlock pathUrl += '&CidrBlock=' pathUrl += Addressable::URI.encode_component(cidrBlock, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/create_vpn_connection.rb000066400000000000000000000033251427710760200266410ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/requests/compute/create_vpn_customergateway.rb000066400000000000000000000023741427710760200277300ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/requests/compute/create_vswitch.rb000066400000000000000000000030741427710760200253070ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['VpcId'] = vpcId pathUrl += '&VpcId=' pathUrl += vpcId parameters['CidrBlock'] = cidrBlock pathUrl += '&CidrBlock=' pathUrl += Addressable::URI.encode_component(cidrBlock, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/delete_disk.rb000066400000000000000000000021721427710760200245470ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/delete_image.rb000066400000000000000000000015451427710760200247020ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/delete_security_group.rb000066400000000000000000000027641427710760200267070ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/delete_security_group_egress_ip_rule.rb000066400000000000000000000041621427710760200317700ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['SecurityGroupId'] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters['DestCidrIp'] = destCidrIp pathUrl += '&DestCidrIp=' pathUrl += Addressable::URI.encode_component(destCidrIp, Addressable::URI::CharacterClasses::UNRESERVED + '|') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/delete_security_group_egress_sg_rule.rb000066400000000000000000000044251427710760200317730ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(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 += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/delete_security_group_ip_rule.rb000066400000000000000000000041561427710760200304230ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['SecurityGroupId'] = securitygroup_id pathUrl += '&SecurityGroupId=' pathUrl += securitygroup_id parameters['SourceCidrIp'] = sourceCidrIp pathUrl += '&SourceCidrIp=' pathUrl += Addressable::URI.encode_component(sourceCidrIp, Addressable::URI::CharacterClasses::UNRESERVED + '|') nicType ||= 'intranet' parameters['NicType'] = nicType pathUrl += '&NicType=' pathUrl += nicType portRange = option[:portRange] portRange ||= '-1/-1' parameters['PortRange'] = portRange pathUrl += '&PortRange=' pathUrl += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/delete_security_group_sg_rule.rb000066400000000000000000000044651427710760200304270ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(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 += Addressable::URI.encode_component(portRange, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/delete_server.rb000066400000000000000000000027531427710760200251300ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/delete_snapshot.rb000066400000000000000000000015761427710760200254630ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/delete_vpc.rb000066400000000000000000000017041427710760200244050ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/delete_vpn_connection.rb000066400000000000000000000020621427710760200266350ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/requests/compute/delete_vpn_customergateway.rb000066400000000000000000000021261427710760200277220ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/requests/compute/delete_vswitch.rb000066400000000000000000000017621427710760200253100ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/detach_disk.rb000066400000000000000000000024111427710760200245310ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(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 += Addressable::URI.encode_component(device, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/join_security_group.rb000066400000000000000000000017431427710760200264000ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/leave_security_group.rb000066400000000000000000000017461427710760200265400ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/list_disks.rb000066400000000000000000000122011427710760200244350ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_eip_addresses.rb000066400000000000000000000032421427710760200261370ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/list_images.rb000066400000000000000000000045261427710760200246000ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_route_tables.rb000066400000000000000000000036541427710760200260240ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_security_group_rules.rb000066400000000000000000000044301427710760200276220ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_security_groups.rb000066400000000000000000000043761427710760200266040ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_server_types.rb000066400000000000000000000033631427710760200260630ustar00rootroot00000000000000# 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 = defaultParameters(_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 = defaultParameters(_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 = 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.4.0/lib/fog/aliyun/requests/compute/list_servers.rb000066400000000000000000000044051427710760200250200ustar00rootroot00000000000000# 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 = defaultParameters(_action, _sigNonce, _time) _query_parameters = defaultAliyunQueryParameters(_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 _query_parameters[:InstanceIds] = _InstanceStr end unless _VpcId.nil? _parameters['VpcId'] = _VpcId _query_parameters[:VpcId] = _VpcId end unless _SecurityGroupId.nil? _parameters['SecurityGroupId'] = _SecurityGroupId _query_parameters[:SecurityGroupId] = _SecurityGroupId end unless _PageNumber.nil? _parameters['PageNumber'] = _PageNumber _query_parameters[:PageNumber] = _PageNumber end _PageSize ||= '50' _parameters['PageSize'] = _PageSize _query_parameters[:PageSize] = _PageSize _signature = sign_without_encoding(@aliyun_accesskey_secret, _parameters) _query_parameters[:Signature] = _signature request( expects: [200, 203], method: 'GET', query: _query_parameters ) 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.4.0/lib/fog/aliyun/requests/compute/list_snapshots.rb000066400000000000000000000052641427710760200253550ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_vpcs.rb000066400000000000000000000024461427710760200243050ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_vpn_connections.rb000066400000000000000000000025651427710760200265410ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/requests/compute/list_vpn_customergateways.rb000066400000000000000000000022351427710760200276170ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/requests/compute/list_vpn_gateways.rb000066400000000000000000000024761427710760200260440ustar00rootroot00000000000000# 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.4.0/lib/fog/aliyun/requests/compute/list_vrouters.rb000066400000000000000000000033641427710760200252230ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_vswitchs.rb000066400000000000000000000026671427710760200252110ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/list_zones.rb000066400000000000000000000021741427710760200244660ustar00rootroot00000000000000# 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 = defaultParameters(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.4.0/lib/fog/aliyun/requests/compute/modify_vpc.rb000066400000000000000000000046061427710760200244360ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['VpcId'] = vpcId pathUrl += '&VpcId=' pathUrl += Addressable::URI.encode_component(vpcId, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/modify_vswitch.rb000066400000000000000000000025471427710760200253370ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' 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 = defaultParameters(action, sigNonce, time) pathUrl = defaultAliyunUri(action, sigNonce, time) parameters['VSwitchId'] = vSwitchId pathUrl += '&VSwitchId=' pathUrl += Addressable::URI.encode_component(vpcId, Addressable::URI::CharacterClasses::UNRESERVED + '|') 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.4.0/lib/fog/aliyun/requests/compute/reboot_server.rb000066400000000000000000000020571427710760200251550ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/release_eip_address.rb000066400000000000000000000015731427710760200262610ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/start_server.rb000066400000000000000000000020321427710760200250110ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/stop_server.rb000066400000000000000000000020261427710760200246440ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/compute/unassociate_eip_address.rb000066400000000000000000000030371427710760200271540ustar00rootroot00000000000000# 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 = defaultParameters(_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.4.0/lib/fog/aliyun/requests/storage/000077500000000000000000000000001427710760200217345ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/abort_multipart_upload.rb000066400000000000000000000011651427710760200270400ustar00rootroot00000000000000 module Fog module Aliyun class Storage class Real # # Abort a multipart upload # # @param [String] bucket_name Name of bucket to abort multipart upload on # @param [String] object_name Name of object to abort multipart upload on # @param [String] upload_id Id of upload to add part to # # @see https://help.aliyun.com/document_detail/31996.html # def abort_multipart_upload(bucket_name, object_name, upload_id) @oss_protocol.abort_multipart_upload(bucket_name, object_name, upload_id) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/complete_multipart_upload.rb000066400000000000000000000013261427710760200275400ustar00rootroot00000000000000 module Fog module Aliyun class Storage class Real # Complete a multipart upload # # @param [String] bucket_name Name of bucket to complete multipart upload for # @param [String] object_name Name of object to complete multipart upload for # @param [String] upload_id Id of upload to add part to # @param [Array] parts Array of etag and number as Strings for parts # # @see https://help.aliyun.com/document_detail/31995.html # def complete_multipart_upload(bucket_name, object_name, upload_id, parts) @oss_protocol.complete_multipart_upload(bucket_name, object_name, upload_id, parts) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/copy_object.rb000066400000000000000000000017651427710760200245720ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real # Copy object # # ==== Parameters # * source_bucket_name<~String> - Name of source bucket # * source_object_name<~String> - Name of source object # * target_bucket_name<~String> - Name of bucket to create copy in # * target_object_name<~String> - Name for new copy of object # * options<~Hash> - Additional headers options={} def copy_object(source_bucket_name, source_object_name, target_bucket_name, target_object_name, options = {}) headers = { 'x-oss-copy-source' => "/#{source_bucket_name}#{object_to_path(source_object_name)}" }.merge!(options) resources = { :bucket => target_bucket_name, :object => target_object_name } http_options = { :headers => headers } @oss_http.put(resources, http_options) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/delete_bucket.rb000066400000000000000000000005551427710760200250650ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real # Delete an existing bucket # # ==== Parameters # * bucket_name<~String> - Name of bucket to delete # def delete_bucket(bucket_name) @oss_protocol.delete_bucket(bucket_name) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/delete_multiple_objects.rb000066400000000000000000000011021427710760200271410ustar00rootroot00000000000000module Fog module Aliyun class Storage class Real # Delete multiple objects from OSS # # @param bucket_name [String] Name of bucket containing object to delete # @param object_names [Array] Array of object names to delete # # @see https://help.aliyun.com/document_detail/31983.html def delete_multiple_objects(bucket_name, object_names, options = {}) bucket = @oss_client.get_bucket(bucket_name) bucket.batch_delete_objects(object_names, options) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/delete_object.rb000066400000000000000000000012741427710760200250550ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real # Delete an existing object # # ==== Parameters # * bucket_name<~String> - Name of bucket to delete # * object_name<~String> - Name of object to delete # def delete_object(bucket_name, object_name, options = {}) # TODO Support versionId # if version_id = options.delete('versionId') # query = {'versionId' => version_id} # else # query = {} # end @oss_http.delete({:bucket => bucket_name, :object => object_name}, {:headers => options}) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/get_bucket.rb000066400000000000000000000025341427710760200244010ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real def bucket_exists?(bucket_name) @oss_client.bucket_exists?(bucket_name) end def get_bucket(bucket_name, options = {}) unless bucket_name raise ArgumentError.new('bucket_name is required') end # Set the GetBucket max limitation to 1000 maxKeys = options[:max_keys] || 1000 maxKeys = maxKeys.to_i maxKeys = [maxKeys, 1000].min options[:limit] = maxKeys options.delete(:max_keys) @oss_protocol.list_objects(bucket_name, options) end def get_bucket_acl(bucket_name) @oss_protocol.get_bucket_acl(bucket_name) end def get_bucket_CORSRules(bucket_name) @oss_protocol.get_bucket_cors(bucket_name) end def get_bucket_lifecycle(bucket_name) @oss_protocol.get_bucket_lifecycle(bucket_name) end def get_bucket_logging(bucket_name) @oss_protocol.get_bucket_logging(bucket_name) end def get_bucket_referer(bucket_name) @oss_protocol.get_bucket_referer(bucket_name) end def get_bucket_website(bucket_name) @oss_protocol.get_bucket_website(bucket_name) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/get_bucket_location.rb000066400000000000000000000015761427710760200262760ustar00rootroot00000000000000require 'nokogiri' module Fog module Aliyun class Storage class Real # Get location constraint for an OSS bucket # # @param bucket_name [String] name of bucket to get location constraint for # # @see https://help.aliyun.com/document_detail/31967.html # # note: The OSS Ruby sdk does not support get_bucket_location and there needs to parse response def get_bucket_location(bucket_name) data = @oss_http.get({:bucket => bucket_name, :sub_res => { 'location' => nil} }, {}) doc = parse_xml(data.body) doc.at_css("LocationConstraint").text end private def parse_xml(content) doc = Nokogiri::XML(content) do |config| config.options |= Nokogiri::XML::ParseOptions::NOBLANKS end doc end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/get_object.rb000066400000000000000000000026661427710760200244000ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real # Get details for object # # ==== Parameters # * object_name<~String> - Name of object to look for # def get_object(bucket_name, object_name, options = {}, &block) options = options.reject { |_key, value| value.nil? } unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end # Using OSS ruby SDK to fix performance issue http_options = { :headers => {} } http_options[:query] = options.delete('query') || {} http_options[:headers].merge!(options) if options['If-Modified-Since'] http_options[:headers]['If-Modified-Since'] = Fog::Time.at(options['If-Modified-Since'].to_i).to_date_header end if options['If-Unmodified-Since'] http_options[:headers]['If-Unmodified-Since'] = Fog::Time.at(options['If-Unmodified-Since'].to_i).to_date_header end if block_given? http_options[:response_block] = Proc.new {} end resources = { :bucket => bucket_name, :object => object_name } @oss_http.get(resources, http_options, &block) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/get_object_acl.rb000066400000000000000000000016741427710760200252150ustar00rootroot00000000000000module Fog module Aliyun class Storage class Real # Get access control list for an S3 object # # @param bucket_name [String] name of bucket containing object # @param object_name [String] name of object to get access control list for # @param options [Hash] # @option options versionId [String] specify a particular version to retrieve def get_object_acl(bucket_name, object_name, options = {}) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end # At present, sdk does not support versionId # if version_id = options.delete('versionId') # query['versionId'] = version_id # end @oss_protocol.get_object_acl(bucket_name, object_name) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/get_object_http_url.rb000066400000000000000000000026241427710760200263130ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' module Fog module Aliyun class Storage class Real # Get an expiring object http url # # ==== Parameters # * bucket_name<~String> - Name of bucket # * object_name<~String> - Name of object to get expiring url for # * expires<~Integer> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object def get_object_http_url_public(bucket_name, object_name, expires) bucket = @oss_client.get_bucket(bucket_name) acl = bucket.acl() if acl == 'private' expires_time = (Time.now.to_i + (expires.nil? ? 0 : expires.to_i)).to_s resource = bucket_name + '/' + object_name signature = sign('GET', expires_time, nil, resource) 'http://' + bucket_name + '.' + @host + '/' + object_name + '?OSSAccessKeyId=' + @aliyun_accesskey_id + '&Expires=' + expires_time + '&Signature=' + Addressable::URI.encode_component(signature, Addressable::URI::CharacterClasses::UNRESERVED + '|') elsif acl == 'public-read' || acl == 'public-read-write' 'http://' + bucket_name + '.' + @host + '/' + object_name else 'acl is wrong with value:' + acl end end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/get_object_https_url.rb000066400000000000000000000026511427710760200264760ustar00rootroot00000000000000# frozen_string_literal: true require 'addressable' module Fog module Aliyun class Storage class Real # Get an expiring object https url from Cloud Files # # ==== Parameters # * bucket_name<~String> - Name of bucket # * object_name<~String> - Name of object to get expiring url for # * expires<~Integer> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object def get_object_https_url_public(bucket_name, object_name, expires) bucket = @oss_client.get_bucket(bucket_name) acl = bucket.acl() if acl == 'private' expires_time = (Time.now.to_i + (expires.nil? ? 0 : expires.to_i)).to_s resource = bucket_name + '/' + object_name signature = sign('GET', expires_time, nil, resource) 'https://' + bucket_name + '.' + @host + '/' + object_name + '?OSSAccessKeyId=' + @aliyun_accesskey_id + '&Expires=' + expires_time + '&Signature=' + Addressable::URI.encode_component(signature, Addressable::URI::CharacterClasses::UNRESERVED + '|') elsif acl == 'public-read' || acl == 'public-read-write' 'https://' + bucket_name + '.' + @host + '/' + object_name else 'acl is wrong with value:' + acl end end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/get_service.rb000066400000000000000000000003561427710760200245640ustar00rootroot00000000000000module Fog module Aliyun class Storage class Real # List information about OSS buckets for authorized user # def get_service @oss_protocol.list_buckets end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/head_object.rb000066400000000000000000000024251427710760200245130ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real # Get headers for object # # ==== Parameters # * object_name<~String> - Name of object to look for # def head_object(bucket_name, object_name, options={}) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end # Currently, the ruby sdk does not support versionId # if version_id = options.delete('versionId') # query = {'versionId' => version_id} # end headers = {} headers['If-Modified-Since'] = Fog::Time.at(options['If-Modified-Since'].to_i).to_date_header if options['If-Modified-Since'] headers['If-Unmodified-Since'] = Fog::Time.at(options['If-Unmodified-Since'].to_i).to_date_header if options['If-Modified-Since'] headers.merge!(options) resources = { :bucket => bucket_name, :object => object_name } http_options = { :headers => headers } @oss_http.head(resources, http_options) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/initiate_multipart_upload.rb000066400000000000000000000010551427710760200275350ustar00rootroot00000000000000module Fog module Aliyun class Storage class Real # Initiate a multipart upload # # @param bucket_name [String] Name of bucket to create # @param object_name [String] Name of object to create # @param options [Hash] # # @see https://help.aliyun.com/document_detail/31992.html # def initiate_multipart_upload(bucket_name, object_name, options = {}) @oss_protocol.initiate_multipart_upload(bucket_name, object_name, options) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/list_buckets.rb000066400000000000000000000006331427710760200247560ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real def list_buckets(options = {}) maxKeys = options[:max_keys] || 1000 maxKeys = maxKeys.to_i maxKeys = [maxKeys, 1000].min options[:limit] = maxKeys options.delete(:max_keys) @oss_protocol.list_buckets(options) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/list_objects.rb000066400000000000000000000013611427710760200247460ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real def list_objects(bucket_name, options = {}) maxKeys = options[:max_keys] || 1000 maxKeys = maxKeys.to_i maxKeys = [maxKeys, 1000].min options[:limit] = maxKeys options.delete(:max_keys) @oss_protocol.list_objects(bucket_name, options) end def list_multipart_uploads(bucket_name, _options = {}) @oss_protocol.list_multipart_uploads(bucket_name, _options) end def list_parts(bucket_name, object_name, upload_id, _options = {}) @oss_protocol.list_parts(bucket_name, object_name, upload_id, _options) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/put_bucket.rb000066400000000000000000000003631427710760200244300ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real def put_bucket(bucket_name, options = {}) @oss_protocol.create_bucket(bucket_name, options) end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/put_object.rb000066400000000000000000000017101427710760200244160ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun class Storage class Real # Put details for object # # ==== Parameters # * bucket_name<~String> - Name of bucket to look for # * object_name<~String> - Object of object to look for # * data<~File> # * options<~Hash> # def put_object(bucket_name, object_name, data, options = {}) if data.is_a? ::File @oss_protocol.put_object(bucket_name, object_name, options)do |sw| while line = data.read(16*1024) sw.write(line) end end else content=StringIO.new(data.dup) @oss_protocol.put_object(bucket_name, object_name, options)do |sw| while line=content.read(16*1024) sw.write(line) end end content.close end end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/requests/storage/upload_part.rb000066400000000000000000000014131427710760200245720ustar00rootroot00000000000000 module Fog module Aliyun class Storage class Real # Upload a part for a multipart upload # # @param bucket_name [String] Name of bucket to add part to # @param object_name [String] Name of object to add part to # @param upload_id [String] Id of upload to add part to # @param part_number [String] Index of part in upload # @param data [File||String] Content for part # # @see https://help.aliyun.com/document_detail/31993.html # def upload_part(bucket_name, object_name, upload_id, part_number, data) @oss_protocol.upload_part(bucket_name, object_name, upload_id, part_number) do |sw| sw.write(data) end end end end end end fog-aliyun-0.4.0/lib/fog/aliyun/storage.rb000066400000000000000000000206031427710760200204070ustar00rootroot00000000000000# frozen_string_literal: true require 'xmlsimple' require 'aliyun/oss' # Using Aliyun OSS Ruby SDK AliyunOssSdk= Aliyun::OSS module Fog module Aliyun class Storage < Fog::Service COMPLIANT_BUCKET_NAMES = /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ DEFAULT_REGION = 'cn-hangzhou' DEFAULT_SCHEME = 'https' DEFAULT_SCHEME_PORT = { 'http' => 80, 'https' => 443 }.freeze recognizes :aliyun_oss_endpoint, :aliyun_oss_location, :aliyun_region_id, :aliyun_oss_sdk_log_path 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 :delete_multiple_objects request :get_bucket request :get_bucket_location request :get_object request :get_object_acl request :get_object_http_url request :get_object_https_url request :head_object request :put_bucket request :put_object request :get_service request :list_buckets request :list_objects request :initiate_multipart_upload request :upload_part request :complete_multipart_upload request :abort_multipart_upload 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 attr_reader :aliyun_oss_sdk_log_path 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] @aliyun_oss_sdk_log_path=options[:aliyun_oss_sdk_log_path] if @aliyun_oss_sdk_log_path && !::File.exist?(@aliyun_oss_sdk_log_path) `touch #{@aliyun_oss_sdk_log_path}` end ENV["ALIYUN_OSS_SDK_LOG_PATH"] = @aliyun_oss_sdk_log_path # 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 @oss_client = AliyunOssSdk::Client.new( :endpoint => @aliyun_oss_endpoint, :access_key_id => @aliyun_accesskey_id, :access_key_secret => @aliyun_accesskey_secret ) # initiate a aliyun oss ruby sdk config and using sdk http to invoke the OSS openapi @oss_config = AliyunOssSdk::Config.new( :endpoint => @aliyun_oss_endpoint, :access_key_id => @aliyun_accesskey_id, :access_key_secret => @aliyun_accesskey_secret ) @oss_http = AliyunOssSdk::HTTP.new(@oss_config) @oss_protocol = AliyunOssSdk::Protocol.new(@oss_config) 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 object_to_path(object_name=nil) '/' + escape(object_name.to_s).gsub('%2F','/') end def escape(string) string.gsub(/([^a-zA-Z0-9_.\-~\/]+)/) { "%" + $1.unpack("H2" * $1.bytesize).join("%").upcase } end def request(params) method = params[:method] time = Time.new.utc date = time.strftime('%a, %d %b %Y %H:%M:%S GMT') 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 = '' if params[:headers] params[:headers].each do |k, v| headers += "#{k}:#{v}\n" if k != 'Range' end end signature = sign(method, date, contentType, params[:resource], headers) response = @connection.request(params.merge(headers: { 'Content-Type' => contentType, 'Authorization' => 'OSS ' + @aliyun_accesskey_id + ':' + signature, 'Date' => date }.merge!(params[:headers] || {}), path: "#{@path}/#{params[:path]}", query: params[:query])) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Aliyun::Storage::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.4.0/lib/fog/aliyun/version.rb000066400000000000000000000001321427710760200204230ustar00rootroot00000000000000# frozen_string_literal: true module Fog module Aliyun VERSION = '0.4.0' end end fog-aliyun-0.4.0/lib/fog/bin/000077500000000000000000000000001427710760200156645ustar00rootroot00000000000000fog-aliyun-0.4.0/lib/fog/bin/aliyun.rb000066400000000000000000000014401427710760200175110ustar00rootroot00000000000000# frozen_string_literal: true class Aliyun < Fog::Bin class << self def class_for(key) case key when :storage Fog::Aliyun::Storage 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.4.0/spec/000077500000000000000000000000001427710760200145255ustar00rootroot00000000000000fog-aliyun-0.4.0/spec/fog/000077500000000000000000000000001427710760200153005ustar00rootroot00000000000000fog-aliyun-0.4.0/spec/fog/aliyun_spec.rb000066400000000000000000000016021427710760200201370ustar00rootroot00000000000000# frozen_string_literal: true require 'spec_helper' require 'addressable' 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 it 'encodes uris' do all_ascii_chars_plus_space = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ' # The above string encoded with URI.encode(all_ascii_chars_plus_space, '/[^!*\'()\;?:@#&%=+$,{}[]<>`" '): uri_encoded_string = '%21%22%23%24%25%26%27%28%29%2A%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B|%7D~%20' encoded_string = Addressable::URI.encode_component(all_ascii_chars_plus_space, Addressable::URI::CharacterClasses::UNRESERVED + '|') expect(encoded_string).to eq(uri_encoded_string) end end fog-aliyun-0.4.0/spec/fog/blobstore_spec.rb000066400000000000000000000072321427710760200206360ustar00rootroot00000000000000require 'spec_helper' require 'find' describe 'blobstore tests', :blobstore => true do before(:all) do @conn = Fog::Storage[:aliyun] Fog::Logger.debug('Initializing Aliyun CLI for blobstore test population...') system("aliyun configure set --language en --region #{@conn.aliyun_region_id} --access-key-id #{@conn.aliyun_accesskey_id} --access-key-secret #{@conn.aliyun_accesskey_secret}") end before(:each) do Fog::Logger.debug("Initializing oss bucket for tests: #{@conn.aliyun_oss_bucket}") system("aliyun oss rm --bucket oss://#{@conn.aliyun_oss_bucket} -r -f > /dev/null || exit 0") system("aliyun oss mb oss://#{@conn.aliyun_oss_bucket} > /dev/null") end it 'blobstore cp_to_blobstore' do files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) files.create :key=>"file1",:body=>"hello" files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(1) files.create :key=>"file2",:body=>::File.open("spec/fog/lorem.txt","r") files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(2) end it 'blobstore exists' do files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.head("file1")).to eq(nil) files.create :key=>"file1",:body=>"hello" expect(files.head("file1")).not_to eq(nil) end it 'blobstore download_from_blobstore' do files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) files.create :key=>"file1",:body=>"hello" files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(1) File.open("1.txt","wb") do |file| files.get("file1") do |*chunk| file.write(chunk[0]) end end end it 'blobstore cp_r_to_blobstore' do files=@conn.directories.get(@conn.aliyun_oss_bucket).files Find.find("spec/fog").each do |path| next unless File.file? path next unless path.include? ".txt" files.create :key=>path,:body=>File.open(path,"r") unless files.head(path) end files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(2) end it 'blobstore cp_file_between_keys' do files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) files.create :key=>"file1",:body=>"hello" files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(1) files.get("file1").copy(@conn.aliyun_oss_bucket,"file2") files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(2) end it 'blobstore delete_all' do files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) files.create :key=>"file1",:body=>"hello" files.create :key=>"file2",:body=>"hello2" files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(2) files.each { |file| file.destroy } files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) end it 'blobstore delete part' do files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) files.create :key=>"dir1/file1",:body=>"hello" files.create :key=>"dir1/file2",:body=>"hello2" files.create :key=>"dir2/file1",:body=>"hello" files.create :key=>"dir2/file2",:body=>"hello2" files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(4) files=@conn.directories.get(@conn.aliyun_oss_bucket,prefix:"dir1").files files.each { |file| file.destroy } files=@conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(2) end endfog-aliyun-0.4.0/spec/fog/integration_spec.rb000066400000000000000000000635601427710760200211740ustar00rootroot00000000000000# frozen_string_literal: true require 'tempfile' require 'spec_helper' DIRECTORY_TEST_PREFIX='fog-aliyun-integration-' describe 'Integration tests', :integration => true do before(:all) do @conn = Fog::Storage[:aliyun] Fog::Logger.debug('Initializing Aliyun CLI for integration test population...') system("aliyun configure set --language en --region #{@conn.aliyun_region_id} --access-key-id #{@conn.aliyun_accesskey_id} --access-key-secret #{@conn.aliyun_accesskey_secret}") end before(:each) do Fog::Logger.debug("Initializing oss bucket for tests: #{@conn.aliyun_oss_bucket}") system("aliyun oss rm --bucket oss://#{@conn.aliyun_oss_bucket} -r -f > /dev/null || exit 0") system("aliyun oss mb oss://#{@conn.aliyun_oss_bucket} > /dev/null") end it 'Should get all of directories' do # nested directories directories = @conn.directories.all expect(directories.length).to be > 0 end it 'Should get directory and its files' do # nested directories system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir/dir1/dir2/dir3 > /dev/null") system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir2/dir1 > /dev/null") directory = @conn.directories.get(@conn.aliyun_oss_bucket) # TODO checking other attributes of directory expect(directory.key).to eq(@conn.aliyun_oss_bucket) expect(directory.location).to eq('oss-' + @conn.aliyun_region_id) # TODO checking other methods of directory files = directory.files expect(files.length).to eq(2) # TODO test directories.get options, like prefix, max_keys and so on files = @conn.directories.get(@conn.aliyun_oss_bucket,prefix:"test_dir2").files expect(files.length).to eq(1) files = @conn.directories.get(@conn.aliyun_oss_bucket,max_keys:"1").files expect(files.length).to eq(1) system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir3/dir1 > /dev/null") system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir4/dir1 > /dev/null") files = @conn.directories.get(@conn.aliyun_oss_bucket,marker:"test_dir2").files expect(files.length).to eq(3) files = @conn.directories.get(@conn.aliyun_oss_bucket,delimiter:"/").files expect(files.length).to eq(0) files = @conn.directories.get(@conn.aliyun_oss_bucket,prefix:"test_dir2/dir1/",delimiter:"/").files expect(files.length).to eq(1) end it 'Should create a new directory' do directory_key = DIRECTORY_TEST_PREFIX + 'create-' + rand(100).to_s @conn.directories.create :key => directory_key # TODO support parameter :location : @conn.directories.create :key => directory_key, :location => "oss-eu-central-1" directory = @conn.directories.get(directory_key) expect(directory.key).to eq(directory_key) # TODO checking other attributes of directory expect(directory.location).to eq('oss-' + @conn.aliyun_region_id) # TODO checking other methods of directory files = directory.files expect(files.length).to eq(0) directory.destroy! directory = @conn.directories.get(directory_key) expect(directory).to eq(nil) end it 'Should delete directory' do directory_key = @conn.aliyun_oss_bucket + '-delete' system("aliyun oss mb oss://#{directory_key} > /dev/null") directory = @conn.directories.get(directory_key) expect(directory.key).to eq(directory_key) # TODO checking other attributes of directory files = directory.files expect(files.length).to eq(0) directory.destroy directory = @conn.directories.get(directory_key) expect(directory).to eq(nil) end it 'Should delete! directory' do directory_key = @conn.aliyun_oss_bucket + '-delete-2' system("aliyun oss mb oss://#{directory_key} > /dev/null") system("aliyun oss mkdir oss://#{directory_key}/test_dir/dir1/dir2/dir3 > /dev/null") system("aliyun oss mkdir oss://#{directory_key}/test_dir2/dir1 > /dev/null") directory = @conn.directories.get(directory_key) expect(directory.key).to eq(directory_key) # TODO checking other attributes of directory files = directory.files expect(files.length).to eq(2) directory.destroy! directory = @conn.directories.get(directory_key) expect(directory).to eq(nil) end it 'Should get all of files: test files.all' do directory_key = @conn.aliyun_oss_bucket file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss mkdir oss://#{directory_key}/test_dir1 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir1/test_file1 > /dev/null") system("aliyun oss mkdir oss://#{directory_key}/test_dir2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir2/test_file2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file3 > /dev/null") files = @conn.directories.get(directory_key).files expect(files.length).to eq(5) expect(files.all.length).to eq(5) # TODO support more filter, like delimiter,marker,prefix, max_keys expect(files.all(delimiter:"/").length).to eq(1) expect(files.all(marker:"test_dir2").length).to eq(3) expect(files.all(prefix:"test_dir1").length).to eq(2) expect(files.all(max_keys:"3").length).to eq(3) expect(files.all(prefix:"test_dir1",max_keys:"1").length).to eq(1) expect(files.all(prefix:"test_dir1/",delimiter:"/").length).to eq(2) ensure file.close file.unlink end end it 'Should iteration all files: test files.each' do directory_key = @conn.aliyun_oss_bucket file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss mkdir oss://#{directory_key}/test_dir1 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir1/test_file1 > /dev/null") system("aliyun oss mkdir oss://#{directory_key}/test_dir2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir2/test_file2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file3 > /dev/null") files = @conn.directories.get(directory_key).files # TODO test block expect(files.each.size).to eq(5) files.each { |f| expect(f.key).not_to eq(nil) } ensure file.close file.unlink end end it 'Should get the specified file: test files.get' do directory_key = @conn.aliyun_oss_bucket file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss mkdir oss://#{directory_key}/test_dir1 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir1/test_file1 > /dev/null") system("aliyun oss mkdir oss://#{directory_key}/test_dir2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir2/test_file2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file3 > /dev/null") files = @conn.directories.get(directory_key).files get_file = files.get("test_file3") expect(get_file.key).to eq("test_file3") # TODO checking all of file attributes and more files get_file=files.get('test_dir1/test_file1') expect(get_file.key).to eq("test_dir1/test_file1") expect(get_file.date).not_to eq(nil) expect(get_file.etag).not_to eq(nil) expect(get_file.last_modified).not_to eq(nil) get_file=files.get('test_dir1/') expect(get_file.key).to eq("test_dir1/") expect(get_file.date).not_to eq(nil) expect(get_file.etag).not_to eq(nil) expect(get_file.last_modified).not_to eq(nil) ensure file.close file.unlink end end it 'Should get specified file: test files.get_https_url' do files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) files.create :key=> "file1" ,:body=> File.open("spec/fog/lorem.txt","r") files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.get_https_url("file1",3600)).not_to eq(nil) expect(files.get_url("file1")).not_to eq(nil) expect(files.get_http_url("file1",3600)).not_to eq(nil) end it 'Should head the specified file: test files.head' do directory_key = @conn.aliyun_oss_bucket file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss mkdir oss://#{directory_key}/test_dir1 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir1/test_file1 > /dev/null") system("aliyun oss mkdir oss://#{directory_key}/test_dir2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_dir2/test_file2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file3 > /dev/null") files = @conn.directories.get(directory_key).files head_file = files.head("test_file3") expect(head_file.key).to eq("test_file3") # TODO checking all of file attributes and more files head_file=files.head('test_dir1/test_file1') expect(head_file.key).to eq("test_dir1/test_file1") expect(head_file.date).not_to eq(nil) expect(head_file.etag).not_to eq(nil) expect(head_file.last_modified).not_to eq(nil) head_file=files.head('test_dir1/') expect(head_file.key).to eq("test_dir1/") expect(head_file.date).not_to eq(nil) expect(head_file.etag).not_to eq(nil) expect(head_file.last_modified).not_to eq(nil) ensure file.close file.unlink end end it 'Should get the specified file acl: test file.acl' do directory_key = @conn.aliyun_oss_bucket file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file > /dev/null") files = @conn.directories.get(directory_key).files expect(files[0].acl).to eq("default") # TODO checking other acl and set acl files[0].acl='public-read' ensure file.close file.unlink end end it 'Should copy a new directory: test file.copy' do source_directory_key = @conn.aliyun_oss_bucket target_directory_key = DIRECTORY_TEST_PREFIX + 'create-' + rand(100).to_s file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss mb oss://#{target_directory_key} > /dev/null") system("aliyun oss cp #{file.path} oss://#{source_directory_key}/test_file > /dev/null") files = @conn.directories.get(source_directory_key).files files[0].copy(target_directory_key, "target_test_file") files = @conn.directories.get(target_directory_key).files expect(files[0].key).to eq("target_test_file") # TODO checking other acl and set acl directory = @conn.directories.get(target_directory_key) directory.acl='public-read-write' expect(directory.acl).to eq('public-read-write') ensure file.close file.unlink files = @conn.directories.get(target_directory_key).files files.each { |f| f.destroy } @conn.delete_bucket (target_directory_key) end end it 'Should delete the specified file: test file.destroy' do directory_key = @conn.aliyun_oss_bucket file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file > /dev/null") files = @conn.directories.get(directory_key).files expect(files[0].key).to eq("test_file") files[0].destroy files = @conn.directories.get(directory_key).files expect(files.size).to eq(0) # TODO checking more files system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file1 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file2 > /dev/null") system("aliyun oss cp #{file.path} oss://#{directory_key}/test_file3 > /dev/null") files = @conn.directories.get(directory_key).files files[0].destroy files[1].destroy files = @conn.directories.get(directory_key).files expect(files.size).to eq(1) ensure file.close file.unlink end end it 'Should create the specified file: test file.save' do files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(0) files.create :key=> "file1" ,:body=> File.open("spec/fog/lorem.txt","r") files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(1) if !File.exist?("morethan100m") system("wget https://bosh.oss-cn-hangzhou.aliyuncs.com/fog/morethan100m -O morethan100m --show-progress") end files.create :key=> "file2", :body=> File.open("morethan100m","r") files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.size).to eq(2) end it 'Should get the specified file: test file.url' do files = @conn.directories.get(@conn.aliyun_oss_bucket).files files.create :key=> "file1" ,:body=> File.open("spec/fog/lorem.txt","r") expect(files.get("file1").url(3600)).not_to eq(nil) end it 'Should get nested directories and files in nested directory' do # nested directories system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir/dir1/dir2/dir3 > /dev/null") directory = @conn.directories.get(@conn.aliyun_oss_bucket) files = directory.files expect(files.length).to eq(1) expect(files.empty?).to eq(false) expect(files.head('test_dir/dir1/notExistFile')).to eq(nil) file=files.get('test_dir/dir1/dir2/dir3/') expect(file.key).to eq("test_dir/dir1/dir2/dir3/") file.destroy # nested files in nested directory file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir/dir1/dir2 > /dev/null") system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/test_dir/dir1/dir2/test_file > /dev/null") files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(2) expect(files.empty?).to eq(false) expect(files.get("test_dir/dir1/dir2/").key).to eq("test_dir/dir1/dir2/") expect(files.get("test_dir/dir1/dir2/test_file").key).to eq("test_dir/dir1/dir2/test_file") files.get("test_dir/dir1/dir2/").destroy files.get("test_dir/dir1/dir2/test_file").destroy ensure file.close file.unlink end end it 'Should getting bucket when directory exists named with the same name as a bucket' do system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/#{@conn.aliyun_oss_bucket} > /dev/null") files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(1) expect(files.get(@conn.aliyun_oss_bucket+"/").key).to eq(@conn.aliyun_oss_bucket+"/") files[0].destroy end it 'test get file that not exists' do directory = @conn.directories.get(@conn.aliyun_oss_bucket) files = directory.files file = files.get('test_dir/test_file_not_exists') expect(file).to eq(nil) end it 'Should find 2 tests file in the root of bucket' do file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/test_file1 > /dev/null") system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/test_file2 > /dev/null") files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(2) expect(files.all.length).to eq(2) expect(files.empty?).to eq(false) expect(files[0].key).to eq("test_file1") expect(files[1].key).to eq("test_file2") expect(files.get("test_file1").key).to eq("test_file1") expect(files.get("test_file2").key).to eq("test_file2") ensure file.close file.unlink end end it 'Should delete 2 tests file in the root of bucket' do file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/test_file1 > /dev/null") system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/test_file2 > /dev/null") files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(2) expect(files.all.length).to eq(2) expect(files.empty?).to eq(false) files[0].destroy expect(@conn.directories.get(@conn.aliyun_oss_bucket).files.length).to eq(1) files[1].destroy expect(@conn.directories.get(@conn.aliyun_oss_bucket).files.length).to eq(0) ensure file.close file.unlink end end it 'Should create a file and update in-place when putting string content to an object.' do # Ensure there is no any file files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(0) # Create a new file files.create :key => 'test_file_save', :body => "Hello World!" files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(1) expect(files[0].key).to eq("test_file_save") expect(files.get("test_file_save").content_length).to eq(12) # Update the file in-place files.create :key => 'test_file_save', :body => 'Hello World!Hello World!' files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(1) expect(files[0].key).to eq("test_file_save") expect(files.get("test_file_save").content_length).to eq(24) # Delete the file in-place files[0].destroy expect(@conn.directories.get(@conn.aliyun_oss_bucket).files.length).to eq(0) end it 'Should create a file and update in-place when putting a file to an object.' do # Ensure there is no any file files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(0) # Create a new file files.create :key => 'test_file_save', :body => File.open('./spec/fog/lorem.txt') files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(1) expect(files[0].key).to eq("test_file_save") expect(files.get("test_file_save").content_length).to eq(446) # Update the file in-place files.create :key => 'test_file_save', :body => File.open('./spec/fog/lorem2.txt') files = @conn.directories.get(@conn.aliyun_oss_bucket).files expect(files.length).to eq(1) expect(files[0].key).to eq("test_file_save") expect(files.get("test_file_save").content_length).to eq(14) # Delete the file in-place files[0].destroy expect(@conn.directories.get(@conn.aliyun_oss_bucket).files.length).to eq(0) end it 'Should find 1000 tests file in the test directory' do file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir > /dev/null") files_count=1000 files_count.times do |n| system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/test_dir/test_file#{n} > /dev/null") end bucket = @conn.directories.get(@conn.aliyun_oss_bucket) dir = bucket.files.get("test_dir/").directory files = dir.files expect(files.length).to eq(files_count) expect(files.empty?).to eq(false) # In AWS the first item is directory, so result will have directory + 999 files (files_count - 1).times do |n| expect(files.get("test_dir/test_file#{n}").key).to eq("test_dir/test_file#{n}") end ensure file.close file.unlink end end it 'Should find directory using bucket name and prefix when bucket with the same name as directory exists' do file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin dir_name=rand(36**16).to_s(36) system("aliyun oss mb oss://#{dir_name} > /dev/null") system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/#{dir_name} > /dev/null") system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/#{dir_name}/test_file > /dev/null") bucket = @conn.directories.get(@conn.aliyun_oss_bucket, prefix: dir_name) expect(bucket.files.size).to eq(2) # test dir + test file ensure file.close file.unlink end end it 'Should find directory using bucket name and prefix when bucket with the same name as directory exists without prefix' do file = Tempfile.new('fog-upload-file') file.write("Hello World!") begin dir_name=rand(36**16).to_s(36) system("aliyun oss mb oss://#{dir_name} > /dev/null") system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/#{dir_name} > /dev/null") system("aliyun oss appendfromfile #{file.path} oss://#{@conn.aliyun_oss_bucket}/#{dir_name}/test_file > /dev/null") directory = @conn.directories.get(dir_name) expect(directory.files.size).to eq(0) # test file ensure file.close file.unlink end end it 'Should error is thrown when trying to access non-existing bucket' do bucket_name='test-bucket'+rand(36**16).to_s(36) begin @conn.get_bucket bucket_name rescue Exception => e expect(e.error_code).to eq("NoSuchBucket") end end it 'Should error is thrown when trying to create already existing bucket' do bucket_name="test-bucket"+rand(36**16).to_s(36) begin @conn.put_bucket bucket_name @conn.put_bucket bucket_name rescue Exception => e expect(e.error_code).to eq("BucketAlreadyExists") ensure @conn.delete_bucket bucket_name end end it 'Should possible to list all buckets' do b1=rand(36**16).to_s(36) b2=rand(36**16).to_s(36) b3=rand(36**16).to_s(36) b4=rand(36**16).to_s(36) b5=rand(36**16).to_s(36) b6=rand(36**16).to_s(36) @conn.put_bucket('bucket-test'+b1) @conn.put_bucket('bucket-test2'+b2) @conn.put_bucket('file-test'+b3) @conn.put_bucket('file-test2'+b4) @conn.put_bucket('directory-test'+b5) @conn.put_bucket('directory-test2'+b6) buckets=@conn.list_buckets[0] expect(buckets.length).to be >= 6 buckets=(@conn.list_buckets :prefix=>"bucket")[0] expect(buckets.length).to be >=2 buckets=(@conn.list_buckets :marker=>"file-t")[0] expect(buckets.length).to be >=4 buckets=(@conn.list_buckets :max_keys=>"6")[0] expect(buckets.length).to be(6) #delete created bucket @conn.delete_bucket('bucket-test'+b1) @conn.delete_bucket('bucket-test2'+b2) @conn.delete_bucket('file-test'+b3) @conn.delete_bucket('file-test2'+b4) @conn.delete_bucket('directory-test'+b5) @conn.delete_bucket('directory-test2'+b6) end it 'Should can be accessed using valid credentials' do expect(@conn.list_objects(@conn.aliyun_oss_bucket)).not_to eq(nil) end it 'Should cannot be accessed using incorrect credentials' do @conn = Fog::Storage.new({ :aliyun_accesskey_id => rand(36**16).to_s(36), :aliyun_accesskey_secret => rand(36**16).to_s(36), :provider => "Aliyun", :aliyun_oss_bucket => @conn.aliyun_oss_bucket }) begin @conn.list_objects(@conn.aliyun_oss_bucket) rescue Exception => e expect(e.error_code).to include("InvalidAccessKeyId") end end it 'Should get bucket operation' do expect(@conn.get_bucket_acl(@conn.aliyun_oss_bucket)).to eq("private") begin @conn.get_bucket_CORSRules(@conn.aliyun_oss_bucket) rescue Exception => e expect(e.error_code).to eq("NoSuchCORSConfiguration") end begin @conn.get_bucket_lifecycle(@conn.aliyun_oss_bucket) rescue Exception => e expect(e.error_code).to eq("NoSuchLifecycle") end expect(@conn.get_bucket_referer(@conn.aliyun_oss_bucket).allow_empty).to eq(true) begin @conn.get_bucket_website(@conn.aliyun_oss_bucket) rescue Exception => e expect(e.error_code).to eq("NoSuchWebsiteConfiguration") end expect(@conn.get_bucket_logging(@conn.aliyun_oss_bucket)).not_to eq(nil) end it 'Should list object operation' do system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir1/test_sub_dir > /dev/null") system("aliyun oss mkdir oss://#{@conn.aliyun_oss_bucket}/test_dir2/test_sub_dir > /dev/null") expect(@conn.list_objects(@conn.aliyun_oss_bucket,:prefix=>"test_dir1")[0].size).to eq(1) expect(@conn.list_objects(@conn.aliyun_oss_bucket,:marker=>"test_dir1")[0].size).to eq(2) upload_id=@conn.initiate_multipart_upload(@conn.aliyun_oss_bucket,"test_file1") expect(@conn.list_multipart_uploads(@conn.aliyun_oss_bucket)).not_to eq(nil) f=File.open("spec/fog/lorem.txt","r") @conn.upload_part(@conn.aliyun_oss_bucket, "test_file1", upload_id, 1, f.read) f.close expect(@conn.list_parts(@conn.aliyun_oss_bucket,"test_file1",upload_id)[0].size).to eq(1) @conn.abort_multipart_upload(@conn.aliyun_oss_bucket,"test_file1",upload_id) end # Test region is selected according to provider configuration # check default region is used if no region provided explicitly # There is need to set a env variable to support setting oss default bucket if ENV['ALIYUN_OSS_DEFAULT_BUCKET'] default_bucket = ENV['ALIYUN_OSS_DEFAULT_BUCKET'] it 'Should create a new directory' do bucket = @conn.directories.get(@conn.aliyun_oss_bucket) bucket.files.create :key => 'test_dir/' expect(bucket.files.get("test_dir/").key).to eq("test_dir/") expect(bucket.key[0]).to eq(@conn.aliyun_oss_bucket) @conn = Fog::Storage.new({ :aliyun_accesskey_id => @conn.aliyun_accesskey_id, :aliyun_accesskey_secret => @conn.aliyun_accesskey_secret, :provider => "Aliyun", :aliyun_oss_bucket => default_bucket }) bucket = @conn.directories.get(@conn.aliyun_oss_bucket) bucket.files.create :key => 'test_dir/' expect(bucket.files.get("test_dir/").key).to eq("test_dir/") expect(bucket.key[0]).to eq(default_bucket) end end endfog-aliyun-0.4.0/spec/fog/lorem.txt000066400000000000000000000006761427710760200171700ustar00rootroot00000000000000Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.fog-aliyun-0.4.0/spec/fog/lorem2.txt000066400000000000000000000000161427710760200172360ustar00rootroot00000000000000Updated Lorem.fog-aliyun-0.4.0/spec/fog/performance_spec.rb000066400000000000000000000164071427710760200211500ustar00rootroot00000000000000# frozen_string_literal: true require 'tempfile' require 'spec_helper' require 'benchmark' require 'memory_profiler' describe 'Performance tests', :performance => true do before(:all) do @conn = Fog::Storage[:aliyun] Fog::Logger.debug('Initializing Aliyun CLI for integration test population...') system("aliyun configure set --language en --region #{@conn.aliyun_region_id} --access-key-id #{@conn.aliyun_accesskey_id} --access-key-secret #{@conn.aliyun_accesskey_secret}") end before(:each) do Fog::Logger.debug("Initializing oss bucket for tests: #{@conn.aliyun_oss_bucket}") system("aliyun oss rm --bucket oss://#{@conn.aliyun_oss_bucket} -r -f > /dev/null || exit 0") system("aliyun oss mb oss://#{@conn.aliyun_oss_bucket} > /dev/null") end it 'Should upload 5 mb string' do content="A"*5*1024*1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => content end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end it 'Should upload 5 mb file' do f=File.open("1.txt","w+") content="A"*1024*1024 5.times.each do f.write(content) end f.seek(0) directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => f end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true f.close File.delete("1.txt") end it 'Should upload 10 mb string' do content="A"*10*1024*1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => content end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end it 'Should upload 10 mb file' do f=File.open("1.txt","w+") content="A"*1024*1024 10.times.each { f.write(content) } f.seek(0) directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => f end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true f.close File.delete("1.txt") end it 'Should upload 50 mb string' do content="A"*50*1024*1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => content end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end it 'Should upload 50 mb file' do f=File.open("1.txt","w+") content="A"*1024*1024 50.times.each{ f.write(content) } f.seek(0) directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => f end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true f.close File.delete("1.txt") end it 'Should upload 100 mb string' do content="A"*100*1024*1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => content end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end it 'Should upload 100 mb file' do f=File.open("1.txt","w+") content="A"*1024*1024 100.times.each{ f.write(content) } f.seek(0) directory = @conn.directories.get(@conn.aliyun_oss_bucket) Benchmark.bm(9) do |benchmark| benchmark.report('Upload file time:') do @memReport = MemoryProfiler.report do directory.files.create :key => 'test_dir/test_file1', :body => f end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true f.close File.delete("1.txt") end it 'Should download 5 mb file' do content = "A" * 5 * 1024 * 1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) directory.files.create :key => 'test_dir/test_file1', :body => content Benchmark.bm(9) do |benchmark| benchmark.report('Download file time:') do @memReport = MemoryProfiler.report do files = directory.files file = files.get('test_dir/test_file1') file.body end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end it 'Should download 10 mb file' do content = "A" * 10 * 1024 * 1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) directory.files.create :key => 'test_dir/test_file1', :body => content Benchmark.bm(9) do |benchmark| benchmark.report('Download file time:') do @memReport = MemoryProfiler.report do files = directory.files file = files.get('test_dir/test_file1') file.body end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end it 'Should download 50 mb file' do content="A"*50*1024*1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) directory.files.create :key => 'test_dir/test_file1', :body => content Benchmark.bm(9) do |benchmark| benchmark.report('Download file time:') do @memReport = MemoryProfiler.report do files = directory.files file = files.get('test_dir/test_file1') file.body end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end it 'Should download 100 mb file' do content="A"*100*1024*1024 directory = @conn.directories.get(@conn.aliyun_oss_bucket) directory.files.create :key => 'test_dir/test_file1', :body => content Benchmark.bm(9) do |benchmark| benchmark.report('Download file time:') do @memReport = MemoryProfiler.report do files = directory.files file = files.get('test_dir/test_file1') file.body end end end @memReport.pretty_print :detailed_report => true, :scale_bytes => true end endfog-aliyun-0.4.0/spec/spec_helper.rb000066400000000000000000000010121427710760200173350ustar00rootroot00000000000000# frozen_string_literal: true if ENV['COVERAGE'] require 'simplecov' SimpleCov.start do add_filter 'test' end end if !ENV['INTEGRATION'] RSpec.configure do |c| c.filter_run_excluding :integration => true end end if !ENV['PERFORMANCE'] RSpec.configure do |c| c.filter_run_excluding :performance => true end end if !ENV['BLOBSTORE'] RSpec.configure do |c| c.filter_run_excluding :blobstore => true end end $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'fog/aliyun'