s3-client 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 4cf1d0b275e685af128afca81c1cbd26ac213209
4
+ data.tar.gz: b1846d86259e5aa9864885fa3974c4e0fd38cc3f
5
+ SHA512:
6
+ metadata.gz: b5f73d5ba9d415266928e66df11dcc287e15011e4047c8a855c96855589c43df4717c9d8b5d90b6a53edc485df68d803cdd7e6625ffed1d9deac8dfa6eb27ebd
7
+ data.tar.gz: 017ffabe31a5f2ee5c9925f29c34ef9eac911fe2ab73ce946daf2c9a94ccd36580f417a2e22710d82af020e4fa25b49155ddcdcebcf4cfe0cc7b2e1e7b5e2d60
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ lib/bundler/man
11
+ pkg
12
+ rdoc
13
+ spec/reports
14
+ test/tmp
15
+ test/version_tmp
16
+ tmp
17
+ .DS_Store
18
+ .idea
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
4
+
5
+ group :test do
6
+ gem 'timecop'
7
+ gem 'pry', '< 0.10.0'
8
+ gem 'pry-byebug'
9
+ gem 'webmock'
10
+ gem 'simplecov'
11
+ gem 'simplecov-rcov'
12
+ gem 'spork'
13
+ end
@@ -0,0 +1,174 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
@@ -0,0 +1,40 @@
1
+ # -*- encoding: utf-8 -*-
2
+ #
3
+ #require "bundler/setup"
4
+
5
+ # gem install tasks, but remove "release"
6
+ #Rake::Task[:release].clear
7
+
8
+ #$:.unshift File.expand_path("../lib", __FILE__)
9
+ require 'bundler/gem_tasks'
10
+ require "rspec/core/rake_task"
11
+
12
+ RSpec::Core::RakeTask.new(:spec)
13
+ task :default => :spec
14
+
15
+
16
+ task :doc => "document:build"
17
+
18
+ namespace :spec do
19
+ [:api, :client, :models].each do |dir|
20
+ desc "Run #{dir} spec"
21
+ RSpec::Core::RakeTask.new(dir) do |t|
22
+ t.pattern = "spec/#{dir}/*_spec.rb"
23
+ end
24
+ end
25
+
26
+ task :without_sample => ['spec:api', 'spec:client', 'spec:models']
27
+ end
28
+
29
+ namespace :document do
30
+ task :build do
31
+ docpath = "../documents/parser"
32
+ if Dir.exist? docpath
33
+ pid = spawn("yard", "-o", docpath, STDERR => STDOUT)
34
+ Process.waitpid pid
35
+ else
36
+ puts "You don't have #{docpath} directory."
37
+ puts "Can't create a new document."
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,11 @@
1
+ defaults: &defaults
2
+ endpoint: 'https://s3.ap-northeast-1.amazonaws.com'
3
+ force_path_style: false
4
+ debug: false
5
+ location: ap-northeast-1
6
+
7
+ test:
8
+ <<: *defaults
9
+ endpoint: 'http://localhost:9292'
10
+ force_path_style: true
11
+ location: localhost
@@ -0,0 +1,31 @@
1
+ require 'driver'
2
+ require 's3/settings'
3
+ require 's3/version'
4
+ require 'active_support/core_ext/object/blank'
5
+ require 'active_support/core_ext/object/try'
6
+ require 'active_support/core_ext/object/to_query'
7
+
8
+ module S3
9
+ class Client < Driver::Client
10
+ drive Storage
11
+
12
+ # Constructor
13
+ # @param [String] access_key_id AccessKeyId
14
+ # @param [String] secret_access_key SecretAccessKey
15
+ # @param [Hash] options Options
16
+ def initialize(access_key_id, secret_access_key, **options)
17
+ require 's3/client/exception'
18
+ require 'ostruct'
19
+
20
+ @api = API.new(access_key_id, secret_access_key, options)
21
+
22
+ self
23
+ end
24
+
25
+ attr_reader :api
26
+
27
+ require "forwardable"
28
+ extend Forwardable
29
+ def_delegators :@api, *%w(access_key_id secret_access_key endpoint).flat_map { |a| [a, a+?=] }.map(&:intern)
30
+ end
31
+ end
@@ -0,0 +1,258 @@
1
+ module S3
2
+ class Client
3
+ class API < Driver::API
4
+ drive Storage
5
+
6
+ autoload :RestParameter, 's3/client/api/rest_parameter'
7
+
8
+ def initialize(access_key_id, secret_access_key,
9
+ endpoint: S3::Settings.endpoint,
10
+ force_path_style: S3::Settings.force_path_style,
11
+ location: S3::Settings.location,
12
+ debug: S3::Settings.debug)
13
+
14
+ require 'time'
15
+ require 'base64'
16
+ require 'rexml/document'
17
+ require 'net/http'
18
+ require 'xmlsimple'
19
+ require 'ipaddr'
20
+ require 'httpclient'
21
+ require 'stringio'
22
+
23
+ @access_key_id = access_key_id
24
+ @secret_access_key = secret_access_key
25
+
26
+ unless [TrueClass, FalseClass].any? { |c| force_path_style.kind_of?(c) }
27
+ raise S3::Client::APIOptionInvalid.new("force_path_style is not boolean:#{force_path_style}")
28
+ end
29
+
30
+ unless [TrueClass, FalseClass].any? { |c| debug.kind_of?(c) }
31
+ raise S3::Client::APIOptionInvalid.new("debug is not boolean:#{debug}")
32
+ end
33
+
34
+ @endpoint = endpoint
35
+ @force_path_style = force_path_style
36
+ @location = location
37
+ @debug = debug
38
+
39
+ @http_client = HTTPClient.new
40
+ @http_client.connect_timeout = 300
41
+ @http_client.send_timeout = 300
42
+ @http_client.receive_timeout = 300
43
+ @http_client.debug_dev = STDERR if @debug
44
+ end
45
+
46
+ attr_accessor :access_key_id, :secret_access_key, :endpoint
47
+
48
+ def force_path_style?
49
+ @force_path_style
50
+ end
51
+
52
+ def execute_storage(rest_parameter, &block)
53
+ unless @access_key_id
54
+ raise S3::Client::ParameterInvalid.new("missing access_key_id")
55
+ end
56
+
57
+ unless @secret_access_key
58
+ raise S3::Client::ParameterInvalid.new("missing secret_access_key")
59
+ end
60
+
61
+ response = handle_api_failure(rest_parameter) do
62
+ rest_client(:storage, rest_parameter, &block)
63
+ end
64
+
65
+ if response.present?
66
+ data = if rest_parameter.raw_data?
67
+ response.body
68
+ else
69
+ REXML::Document.new(response.body)
70
+ end || ''
71
+
72
+ if data.present?
73
+ STDERR.print "\n\n" if @debug
74
+ end
75
+
76
+ data.instance_eval {
77
+ class << self
78
+ attr_accessor :headers
79
+ end
80
+ }
81
+ data.headers = response.header
82
+ return data.freeze
83
+ end
84
+ end
85
+
86
+ def download_signature(expire_at, bucket, output_object)
87
+ http_verb = "GET\n"
88
+ content_md5 = "\n"
89
+ content_type = "\n"
90
+ expire = "#{expire_at}\n"
91
+
92
+ string_to_sign = http_verb + content_md5 + content_type + expire +
93
+ canonicalized_resource(bucket, output_object)
94
+
95
+ digest = OpenSSL::HMAC::digest(OpenSSL::Digest::SHA1.new, @secret_access_key, string_to_sign)
96
+ Base64.encode64(digest).strip
97
+ end
98
+
99
+ private
100
+
101
+ def canonicalized_resource(bucket, object)
102
+ result = ''
103
+
104
+ unless @force_path_style
105
+ result = '/'
106
+ result += "#{bucket}"
107
+ end
108
+
109
+ File.join(result, object)
110
+ end
111
+
112
+ # API Error Handling
113
+ # @param [S3::Client::API::RestParameter] rest_parameter APIへの入力値
114
+ # @param [Proc] block リクエスト処理が入るブロック
115
+ def handle_api_failure(rest_parameter, &block)
116
+ response = nil
117
+
118
+ begin
119
+ response = block.call
120
+
121
+ #unless response.try(:status).to_s =~ /^(2\d\d|3\d\d)$/
122
+ unless response.try(:status).to_s =~ /^(2\d\d)$/
123
+ raise S3::Client::APIFailure
124
+ end
125
+
126
+ return response
127
+ rescue S3::Client::APIFailure
128
+ msg = "api_failure #{rest_parameter}"
129
+ api_failure = S3::Client::APIFailure.new(msg)
130
+ raise api_failure if response.blank?
131
+
132
+ xml_doc = REXML::Document.new(response.body)
133
+
134
+ if xml_doc && xml_doc.elements['Error/Code']
135
+ if xml_doc.elements['Error/Code']
136
+ api_failure.api_code = xml_doc.elements['Error/Code'].text
137
+ end
138
+ if xml_doc.elements['Error/Message']
139
+ api_failure.api_message = xml_doc.elements['Error/Message'].text
140
+ end
141
+ if xml_doc.elements['Error/Status']
142
+ api_failure.api_status = xml_doc.elements['Error/Status'].text.to_i
143
+ end
144
+ if xml_doc.elements['Error/RequestId']
145
+ api_failure.api_request_id = xml_doc.elements['Error/RequestId'].text
146
+ end
147
+ if xml_doc.elements['Error/Resource']
148
+ api_failure.api_resource = xml_doc.elements['Error/Resource'].text
149
+ end
150
+ else
151
+ api_failure.api_code = nil
152
+ api_failure.api_message = response.body
153
+ api_failure.api_status = response.try(:status)
154
+ api_failure.api_request_id = nil
155
+ api_failure.api_resource = response.http_header.request_uri
156
+ end
157
+
158
+ raise api_failure
159
+ end
160
+
161
+ response
162
+ end
163
+
164
+ def rest_client(kind, rest_parameter, &block)
165
+ url = rest_parameter.url(host_uri(kind), @force_path_style)
166
+
167
+ rest_parameter.headers.merge!({
168
+ Authorization: rest_parameter.authentication(@access_key_id, @secret_access_key, @force_path_style),
169
+ Date: rest_parameter.calc_date,
170
+ Host: host_name(kind, rest_parameter.bucket),
171
+ Accept: '*/*; q=0.5, application/xml',
172
+ 'Accept-Encoding' => 'gzip, deflate',
173
+ 'User-Agent' => "s3-client (#{S3::VERSION})"
174
+ })
175
+
176
+ parameters = rest_parameter.parameters
177
+
178
+ unless rest_parameter.headers['Content-Type']
179
+ if rest_parameter.content_type
180
+ rest_parameter.headers.merge!(
181
+ 'Content-Type' => rest_parameter.content_type
182
+ )
183
+ end
184
+ end
185
+
186
+ payload = if parameters.present? || rest_parameter.blank_body?
187
+ parameters
188
+ elsif block_given?
189
+ block.call
190
+ end
191
+
192
+ unless rest_parameter.headers['Content-Length']
193
+ rest_parameter.headers.merge!(
194
+ 'Content-Length' => payload ? payload.size.to_s : 0.to_s
195
+ )
196
+ end
197
+
198
+ STDERR.print "\n" if @debug
199
+
200
+ headers = rest_parameter.headers
201
+ case rest_parameter.method
202
+ when :get
203
+ @http_client.get(url, nil, headers)
204
+
205
+ when :post
206
+ @http_client.post(url, payload, headers)
207
+
208
+ when :put
209
+ @http_client.put(url, payload, headers)
210
+
211
+ when :delete
212
+ @http_client.delete(url, nil, headers)
213
+
214
+ end
215
+ end
216
+
217
+ def host_name(kind, bucket)
218
+ uri = host_uri(kind)
219
+ result = uri.host
220
+
221
+ if kind == :storage
222
+ return result if valid_ip?(result)
223
+
224
+ if !@force_path_style && bucket.present?
225
+ result = "#{bucket}.#{result}"
226
+ end
227
+ end
228
+
229
+ unless uri.port == 80 || uri.port == 443
230
+ result += ":#{uri.port}"
231
+ end
232
+
233
+ result
234
+ end
235
+
236
+ def valid_ip?(str)
237
+ begin
238
+ IPAddr.new(str)
239
+ true
240
+ rescue
241
+ false
242
+ end
243
+ end
244
+
245
+ def host_uri(kind)
246
+ host_url = case kind
247
+ when :storage
248
+ @endpoint
249
+ end
250
+
251
+ raise 'illegal kind' if host_url.blank?
252
+
253
+ URI.parse(host_url)
254
+ end
255
+
256
+ end
257
+ end
258
+ end