Class: Aliyun::OSS::Protocol

Inherits:
Object
  • Object
show all
Includes:
Common::Logging
Defined in:
lib/aliyun/oss/protocol.rb

Overview

Protocol implement the OSS Open API which is low-level. User should refer to Client for normal use.

Constant Summary collapse

STREAM_CHUNK_SIZE =
16 * 1024
CALLBACK_HEADER =
'x-oss-callback'

Constants included from Common::Logging

Common::Logging::MAX_NUM_LOG, Common::Logging::ROTATE_SIZE

Instance Method Summary collapse

Methods included from Common::Logging

#logger, set_log_file, set_log_level

Constructor Details

#initialize(config) ⇒ Protocol

Returns a new instance of Protocol.



22
23
24
25
# File 'lib/aliyun/oss/protocol.rb', line 22

def initialize(config)
  @config = config
  @http = HTTP.new(config)
end

Instance Method Details

#abort_multipart_upload(bucket_name, object_name, txn_id) ⇒ Object

Note:

All the parts are discarded after abort. For some parts being uploaded while the abort happens, they may not be discarded. Call abort_multipart_upload several times for this situation.

Abort a multipart uploading transaction

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • txn_id (String)

    the upload id



1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
# File 'lib/aliyun/oss/protocol.rb', line 1325

def abort_multipart_upload(bucket_name, object_name, txn_id)
  logger.debug("Begin abort multipart upload, txn id: #{txn_id}")

  sub_res = {'uploadId' => txn_id}

  @http.delete(
    {:bucket => bucket_name, :object => object_name, :sub_res => sub_res})

  logger.debug("Done abort multipart: #{txn_id}.")
end

#append_object(bucket_name, object_name, position, opts = {}) {|HTTP::StreamWriter| ... } ⇒ Integer

Note:
  1. Can not append to a “Normal Object”

  2. The position must equal to the object’s size before append

  3. The :content_type is only used when the object is created

Append to an object of a bucket. Create an “Appendable Object” if the object does not exist. A block is required to provide the appending data.

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • position (Integer)

    the position to append

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • :acl (String)

    specify the object’s ACL. See ACL

  • :content_type (String)

    the HTTP Content-Type for the file, if not specified client will try to determine the type itself and fall back to HTTP::DEFAULT_CONTENT_TYPE if it fails to do so

  • :metas (Hash<Symbol, String>)

    key-value pairs that serve as the object meta which will be stored together with the object

  • :headers (Hash)

    custom HTTP headers, case insensitive. Headers specified here will overwrite ‘:metas` and `:content_type`

Yields:

  • (HTTP::StreamWriter)

    a stream writer is yielded to the caller to which it can write chunks of data streamingly

Returns:

  • (Integer)

    next position to append



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
# File 'lib/aliyun/oss/protocol.rb', line 683

def append_object(bucket_name, object_name, position, opts = {}, &block)
  logger.debug("Begin append object, bucket: #{bucket_name}, object: "\
                "#{object_name}, position: #{position}, options: #{opts}")

  sub_res = {'append' => nil, 'position' => position}
  headers = {'content-type' => opts[:content_type]}
  headers['x-oss-object-acl'] = opts[:acl] if opts.key?(:acl)
  to_lower_case(opts[:metas] || {})
    .each { |k, v| headers["x-oss-meta-#{k.to_s}"] = v.to_s }

  headers.merge!(to_lower_case(opts[:headers])) if opts.key?(:headers)

  payload = HTTP::StreamWriter.new(
    @config.upload_crc_enable && !opts[:init_crc].nil?, opts[:init_crc], &block)

  r = @http.post(
    {:bucket => bucket_name, :object => object_name, :sub_res => sub_res},
    {:headers => headers, :body => payload})

  if @config.upload_crc_enable &&
    !r.headers[:x_oss_hash_crc64ecma].nil? &&
    !opts[:init_crc].nil?
    data_crc = payload.data_crc
    Aliyun::OSS::Util.crc_check(data_crc, r.headers[:x_oss_hash_crc64ecma], 'append')
  end

  logger.debug('Done append object')

  wrap(r.headers[:x_oss_next_append_position], &:to_i) || -1
end

#batch_delete_objects(bucket_name, object_names, opts = {}) ⇒ Array<String>

Batch delete objects

Parameters:

  • bucket_name (String)

    the bucket name

  • object_names (Enumerator<String>)

    the object names

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :quiet (Boolean)

    indicates whether the server should return the delete result of the objects

  • :encoding (String)

    the encoding type for object key in the response body, only KeyEncoding::URL is supported now

Returns:

  • (Array<String>)

    object names that have been successfully deleted or empty if :quiet is true



1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
# File 'lib/aliyun/oss/protocol.rb', line 1045

def batch_delete_objects(bucket_name, object_names, opts = {})
  logger.debug("Begin batch delete object, bucket: #{bucket_name}, "\
               "objects: #{object_names}, options: #{opts}")

  sub_res = {'delete' => nil}

  # It may have invisible chars in object key which will corrupt
  # libxml. So we're constructing xml body manually here.
  body = '<?xml version="1.0"?>'
  body << '<Delete>'
  body << '<Quiet>' << (opts[:quiet]? true : false).to_s << '</Quiet>'
  object_names.each { |k|
    body << '<Object><Key>' << CGI.escapeHTML(k) << '</Key></Object>'
  }
  body << '</Delete>'

  query = {}
  query['encoding-type'] = opts[:encoding] if opts[:encoding]

  r = @http.post(
       {:bucket => bucket_name, :sub_res => sub_res},
       {:query => query, :body => body})

  deleted = []
  unless opts[:quiet]
    doc = parse_xml(r.body)
    encoding = get_node_text(doc.root, 'EncodingType')
    doc.css("Deleted").map do |n|
      deleted << get_node_text(n, 'Key') { |x| decode_key(x, encoding) }
    end
  end

  logger.debug("Done delete object")

  deleted
end

#complete_multipart_upload(bucket_name, object_name, txn_id, parts, callback = nil) ⇒ Object

Complete a multipart uploading transaction

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • txn_id (String)

    the upload id

  • parts (Array<Multipart::Part>)

    all the parts in this transaction

  • callback (Callback) (defaults to: nil)

    the HTTP callback performed by OSS after this operation succeeds



1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
# File 'lib/aliyun/oss/protocol.rb', line 1284

def complete_multipart_upload(
      bucket_name, object_name, txn_id, parts, callback = nil)
  logger.debug("Begin complete multipart upload, "\
               "txn id: #{txn_id}, parts: #{parts.map(&:to_s)}")

  sub_res = {'uploadId' => txn_id}
  headers = {}
  headers[CALLBACK_HEADER] = callback.serialize if callback

  body = Nokogiri::XML::Builder.new do |xml|
    xml.CompleteMultipartUpload {
      parts.each do |p|
        xml.Part {
          xml.PartNumber p.number
          xml.ETag p.etag
        }
      end
    }
  end.to_xml

  r = @http.post(
    {:bucket => bucket_name, :object => object_name, :sub_res => sub_res},
    {:headers => headers, :body => body})

  if r.code == 203
    e = CallbackError.new(r)
    logger.error(e.to_s)
    raise e
  end

  logger.debug("Done complete multipart upload: #{txn_id}.")
end

#copy_object(bucket_name, src_object_name, dst_object_name, opts = {}) ⇒ Hash

Copy an object in the bucket. The source object and the dest object may be from different buckets of the same region.

Parameters:

  • bucket_name (String)

    the bucket name

  • src_object_name (String)

    the source object name

  • dst_object_name (String)

    the dest object name

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :src_bucket (String)

    specify the source object’s bucket. It MUST be in the same region as the dest bucket. It defaults to dest bucket if not specified.

  • :acl (String)

    specify the dest object’s ACL. See ACL

  • :meta_directive (String)

    specify what to do with the object’s meta: copy or replace. See MetaDirective

  • :content_type (String)

    the HTTP Content-Type for the file, if not specified client will try to determine the type itself and fall back to HTTP::DEFAULT_CONTENT_TYPE if it fails to do so

  • :metas (Hash<Symbol, String>)

    key-value pairs that serve as the object meta which will be stored together with the object

  • :condition (Hash)

    preconditions to get the object. See #get_object

Returns:

  • (Hash)

    the copy result

    • :etag [String] the etag of the dest object

    • :last_modified [Time] the last modification time of the dest object



985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
# File 'lib/aliyun/oss/protocol.rb', line 985

def copy_object(bucket_name, src_object_name, dst_object_name, opts = {})
  logger.debug("Begin copy object, bucket: #{bucket_name}, "\
               "source object: #{src_object_name}, dest object: "\
               "#{dst_object_name}, options: #{opts}")

  src_bucket = opts[:src_bucket] || bucket_name
  headers = {
    'x-oss-copy-source' =>
      @http.get_resource_path(src_bucket, src_object_name),
    'content-type' => opts[:content_type]
  }
  (opts[:metas] || {})
    .each { |k, v| headers["x-oss-meta-#{k.to_s}"] = v.to_s }

  {
    :acl => 'x-oss-object-acl',
    :meta_directive => 'x-oss-metadata-directive'
  }.each { |k, v| headers[v] = opts[k] if opts[k] }

  headers.merge!(get_copy_conditions(opts[:condition])) if opts[:condition]

  r = @http.put(
    {:bucket => bucket_name, :object => dst_object_name},
    {:headers => headers})

  doc = parse_xml(r.body)
  copy_result = {
    :last_modified => get_node_text(
      doc.root, 'LastModified') { |x| Time.parse(x) },
    :etag => get_node_text(doc.root, 'ETag')
  }.reject { |_, v| v.nil? }

  logger.debug("Done copy object")

  copy_result
end

#create_bucket(name, opts = {}) ⇒ Object

Create a bucket

Examples:

oss-cn-hangzhou

Parameters:

  • name (String)

    the bucket name

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :location (String)

    the region where the bucket is located



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/aliyun/oss/protocol.rb', line 98

def create_bucket(name, opts = {})
  logger.info("Begin create bucket, name: #{name}, opts: #{opts}")

  location = opts[:location]
  body = nil
  if location
    builder = Nokogiri::XML::Builder.new do |xml|
      xml.CreateBucketConfiguration {
        xml.LocationConstraint location
      }
    end
    body = builder.to_xml
  end

  @http.put({:bucket => name}, {:body => body})

  logger.info("Done create bucket")
end

#delete_bucket(name) ⇒ Object

Note:

it will fails if the bucket is not empty (it contains objects)

Delete a bucket

Parameters:

  • name (String)

    the bucket name



589
590
591
592
593
594
595
# File 'lib/aliyun/oss/protocol.rb', line 589

def delete_bucket(name)
  logger.info("Begin delete bucket: #{name}")

  @http.delete({:bucket => name})

  logger.info("Done delete bucket")
end

#delete_bucket_cors(name) ⇒ Object

Note:

this will delete all CORS rules of this bucket

Delete all bucket CORS rules

Parameters:

  • name (String)

    the bucket name



575
576
577
578
579
580
581
582
583
# File 'lib/aliyun/oss/protocol.rb', line 575

def delete_bucket_cors(name)
  logger.info("Begin delete bucket cors, bucket: #{name}")

  sub_res = {'cors' => nil}

  @http.delete({:bucket => name, :sub_res => sub_res})

  logger.info("Done delete bucket cors")
end

#delete_bucket_encryption(name) ⇒ Object

Delete bucket encryption settings, a.k.a. disable bucket encryption

Parameters:

  • name (String)

    the bucket name



305
306
307
308
309
310
311
312
# File 'lib/aliyun/oss/protocol.rb', line 305

def delete_bucket_encryption(name)
  logger.info("Begin delete bucket encryption, name: #{name}")

  sub_res = {'encryption' => nil}
  @http.delete({:bucket => name, :sub_res => sub_res})

  logger.info("Done delete bucket encryption")
end

#delete_bucket_lifecycle(name) ⇒ Object

Note:

this will delete all lifecycle rules

Delete all lifecycle rules on the bucket

Parameters:

  • name (String)

    the bucket name



500
501
502
503
504
505
506
507
# File 'lib/aliyun/oss/protocol.rb', line 500

def delete_bucket_lifecycle(name)
  logger.info("Begin delete bucket lifecycle, name: #{name}")

  sub_res = {'lifecycle' => nil}
  @http.delete({:bucket => name, :sub_res => sub_res})

  logger.info("Done delete bucket lifecycle")
end

#delete_bucket_logging(name) ⇒ Object

Delete bucket logging settings, a.k.a. disable bucket logging

Parameters:

  • name (String)

    the bucket name



206
207
208
209
210
211
212
213
# File 'lib/aliyun/oss/protocol.rb', line 206

def delete_bucket_logging(name)
  logger.info("Begin delete bucket logging, name: #{name}")

  sub_res = {'logging' => nil}
  @http.delete({:bucket => name, :sub_res => sub_res})

  logger.info("Done delete bucket logging")
end

#delete_bucket_website(name) ⇒ Object

Delete bucket website settings

Parameters:

  • name (String)

    the bucket name



369
370
371
372
373
374
375
376
# File 'lib/aliyun/oss/protocol.rb', line 369

def delete_bucket_website(name)
  logger.info("Begin delete bucket website, name: #{name}")

  sub_res = {'website' => nil}
  @http.delete({:bucket => name, :sub_res => sub_res})

  logger.info("Done delete bucket website")
end

#delete_object(bucket_name, object_name) ⇒ Object

Delete an object from the bucket

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name



1025
1026
1027
1028
1029
1030
1031
1032
# File 'lib/aliyun/oss/protocol.rb', line 1025

def delete_object(bucket_name, object_name)
  logger.debug("Begin delete object, bucket: #{bucket_name}, "\
               "object:  #{object_name}")

  @http.delete({:bucket => bucket_name, :object => object_name})

  logger.debug("Done delete object")
end

#download_crc_enableObject

Get the download crc status



1531
1532
1533
# File 'lib/aliyun/oss/protocol.rb', line 1531

def download_crc_enable
  @config.download_crc_enable
end

#get_access_key_idString

Get user’s access key id

Returns:

  • (String)

    the access key id



1506
1507
1508
# File 'lib/aliyun/oss/protocol.rb', line 1506

def get_access_key_id
  @config.access_key_id
end

#get_access_key_secretString

Get user’s access key secret

Returns:

  • (String)

    the access key secret



1512
1513
1514
# File 'lib/aliyun/oss/protocol.rb', line 1512

def get_access_key_secret
  @config.access_key_secret
end

#get_bucket_acl(name) ⇒ String

Get bucket acl

Parameters:

  • name (String)

    the bucket name

Returns:

  • (String)

    the acl of this bucket



136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/aliyun/oss/protocol.rb', line 136

def get_bucket_acl(name)
  logger.info("Begin get bucket acl, name: #{name}")

  sub_res = {'acl' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  doc = parse_xml(r.body)
  acl = get_node_text(doc.at_css("AccessControlList"), 'Grant')
  logger.info("Done get bucket acl")

  acl
end

#get_bucket_cors(name) ⇒ Array<OSS::CORSRule] the CORS rules

Get bucket CORS rules

Parameters:

  • name (String)

    the bucket name

Returns:

  • (Array<OSS::CORSRule] the CORS rules)

    Array<OSS::CORSRule] the CORS rules



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/aliyun/oss/protocol.rb', line 543

def get_bucket_cors(name)
  logger.info("Begin get bucket cors, bucket: #{name}")

  sub_res = {'cors' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  doc = parse_xml(r.body)
  rules = []

  doc.css("CORSRule").map do |n|
    allowed_origins = n.css("AllowedOrigin").map(&:text)
    allowed_methods = n.css("AllowedMethod").map(&:text)
    allowed_headers = n.css("AllowedHeader").map(&:text)
    expose_headers = n.css("ExposeHeader").map(&:text)
    max_age_seconds = get_node_text(n, 'MaxAgeSeconds', &:to_i)

    rules << CORSRule.new(
      :allowed_origins => allowed_origins,
      :allowed_methods => allowed_methods,
      :allowed_headers => allowed_headers,
      :expose_headers => expose_headers,
      :max_age_seconds => max_age_seconds)
  end

  logger.info("Done get bucket cors")

  rules
end

#get_bucket_encryption(name) ⇒ BucketEncryption

Get bucket encryption settings

Parameters:

  • name (String)

    the bucket name

Returns:



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/aliyun/oss/protocol.rb', line 284

def get_bucket_encryption(name)
  logger.info("Begin get bucket encryption, name: #{name}")

  sub_res = {'encryption' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  doc = parse_xml(r.body)

  encryption_node = doc.at_css("ApplyServerSideEncryptionByDefault")
  opts = {
    :sse_algorithm => get_node_text(encryption_node, 'SSEAlgorithm'),
    :kms_master_key_id => get_node_text(encryption_node, 'KMSMasterKeyID')
  }

  logger.info("Done get bucket encryption")

  BucketEncryption.new(opts)
end

#get_bucket_lifecycle(name) ⇒ Array<OSS::LifeCycleRule>

Get bucket lifecycle settings

Parameters:

  • name (String)

    the bucket name

Returns:



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/aliyun/oss/protocol.rb', line 470

def get_bucket_lifecycle(name)
  logger.info("Begin get bucket lifecycle, name: #{name}")

  sub_res = {'lifecycle' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  doc = parse_xml(r.body)
  rules = doc.css("Rule").map do |n|
    days = n.at_css("Expiration Days")
    date = n.at_css("Expiration Date")

    if (days && date) || (!days && !date)
      fail ClientError, "We can only have one of Date and Days for expiry."
    end

    LifeCycleRule.new(
      :id => get_node_text(n, 'ID'),
      :prefix => get_node_text(n, 'Prefix'),
      :enable => get_node_text(n, 'Status') { |x| x == 'Enabled' },
      :expiry => days ? days.text.to_i : Date.parse(date.text)
    )
  end
  logger.info("Done get bucket lifecycle")

  rules
end

#get_bucket_logging(name) ⇒ BucketLogging

Get bucket logging settings

Parameters:

  • name (String)

    the bucket name

Returns:



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/aliyun/oss/protocol.rb', line 183

def get_bucket_logging(name)
  logger.info("Begin get bucket logging, name: #{name}")

  sub_res = {'logging' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  doc = parse_xml(r.body)
  opts = {:enable => false}

  logging_node = doc.at_css("LoggingEnabled")
  opts.update(
    :target_bucket => get_node_text(logging_node, 'TargetBucket'),
    :target_prefix => get_node_text(logging_node, 'TargetPrefix')
  )
  opts[:enable] = true if opts[:target_bucket]

  logger.info("Done get bucket logging")

  BucketLogging.new(opts)
end

#get_bucket_referer(name) ⇒ BucketReferer

Get bucket referer

Parameters:

  • name (String)

    the bucket name

Returns:



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/aliyun/oss/protocol.rb', line 407

def get_bucket_referer(name)
  logger.info("Begin get bucket referer, name: #{name}")

  sub_res = {'referer' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  doc = parse_xml(r.body)
  opts = {
    :allow_empty =>
      get_node_text(doc.root, 'AllowEmptyReferer', &:to_bool),
    :whitelist => doc.css("RefererList Referer").map(&:text)
  }

  logger.info("Done get bucket referer")

  BucketReferer.new(opts)
end

#get_bucket_versioning(name) ⇒ BucketVersioning

Get bucket versioning settings

Parameters:

  • name (String)

    the bucket name

Returns:



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/aliyun/oss/protocol.rb', line 239

def get_bucket_versioning(name)
  logger.info("Begin get bucket versioning, name: #{name}")

  sub_res = {'versioning' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  doc = parse_xml(r.body)

  versioning_node = doc.at_css("VersioningConfiguration")
  opts = {
    :status => get_node_text(versioning_node, 'Status')
  }

  logger.info("Done get bucket versioning")

  BucketVersioning.new(opts)
end

#get_bucket_website(name) ⇒ BucketWebsite

Get bucket website settings

Parameters:

  • name (String)

    the bucket name

Returns:



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/aliyun/oss/protocol.rb', line 349

def get_bucket_website(name)
  logger.info("Begin get bucket website, name: #{name}")

  sub_res = {'website' => nil}
  r = @http.get({:bucket => name, :sub_res => sub_res})

  opts = {:enable => true}
  doc = parse_xml(r.body)
  opts.update(
    :index => get_node_text(doc.at_css('IndexDocument'), 'Suffix'),
    :error => get_node_text(doc.at_css('ErrorDocument'), 'Key')
  )

  logger.info("Done get bucket website")

  BucketWebsite.new(opts)
end

#get_object(bucket_name, object_name, opts = {}) {|String| ... } ⇒ OSS::Object

Note:

User can get the whole object or only part of it by specify the bytes range;

Note:

User can specify conditions to get the object like: if-modified-since, if-unmodified-since, if-match-etag, if-unmatch-etag. If the object to get fails to meet the conditions, it will not be returned;

Note:

User can indicate the server to rewrite the response headers such as content-type, content-encoding when get the object by specify the :rewrite options. The specified headers will be returned instead of the original property of the object.

Get an object from the bucket. A block is required to handle the object data chunks.

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :range (Array<Integer>)

    bytes range to get from the object, in the format: xx-yy

  • :condition (Hash)

    preconditions to get the object

    • :if_modified_since (Time) get the object if its modified time is later than specified

    • :if_unmodified_since (Time) get the object if its unmodified time if earlier than specified

    • :if_match_etag (String) get the object if its etag match specified

    • :if_unmatch_etag (String) get the object if its etag doesn’t match specified

  • :headers (Hash)

    custom HTTP headers, case insensitive. Headers specified here will overwrite ‘:condition` and `:range`

  • :rewrite (Hash)

    response headers to rewrite

    • :content_type (String) the Content-Type header

    • :content_language (String) the Content-Language header

    • :expires (Time) the Expires header

    • :cache_control (String) the Cache-Control header

    • :content_disposition (String) the Content-Disposition header

    • :content_encoding (String) the Content-Encoding header

Yields:

  • (String)

    it gives the data chunks of the object to the block

Returns:



850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/aliyun/oss/protocol.rb', line 850

def get_object(bucket_name, object_name, opts = {}, &block)
  logger.debug("Begin get object, bucket: #{bucket_name}, "\
               "object: #{object_name}")

  range = opts[:range]
  conditions = opts[:condition]
  rewrites = opts[:rewrite]

  headers = {}
  headers['range'] = get_bytes_range(range) if range
  headers.merge!(get_conditions(conditions)) if conditions
  headers.merge!(to_lower_case(opts[:headers])) if opts.key?(:headers)

  sub_res = {}
  if rewrites
    [ :content_type,
      :content_language,
      :cache_control,
      :content_disposition,
      :content_encoding
    ].each do |k|
      key = "response-#{k.to_s.sub('_', '-')}"
      sub_res[key] = rewrites[k] if rewrites.key?(k)
    end
    sub_res["response-expires"] =
      rewrites[:expires].httpdate if rewrites.key?(:expires)
  end

  data_crc = opts[:init_crc].nil? ? 0 : opts[:init_crc]
  r = @http.get(
    {:bucket => bucket_name, :object => object_name,
     :sub_res => sub_res},
    {:headers => headers}
  ) do |chunk|
    if block_given?
      # crc enable and no range and oss server support crc
      data_crc = Aliyun::OSS::Util.crc(chunk, data_crc) if @config.download_crc_enable && range.nil?
      yield chunk
    end
  end

  if @config.download_crc_enable && range.nil? && !r.headers[:x_oss_hash_crc64ecma].nil?
    Aliyun::OSS::Util.crc_check(data_crc, r.headers[:x_oss_hash_crc64ecma], 'get')
  end

  h = r.headers
  metas = {}
  meta_prefix = 'x_oss_meta_'
  h.select { |k, _| k.to_s.start_with?(meta_prefix) }
    .each { |k, v| metas[k.to_s.sub(meta_prefix, '')] = v.to_s }

  obj = Object.new(
    :key => object_name,
    :type => h[:x_oss_object_type],
    :size => wrap(h[:content_length], &:to_i),
    :etag => h[:etag],
    :metas => metas,
    :last_modified => wrap(h[:last_modified]) { |x| Time.parse(x) },
    :headers => h)

  logger.debug("Done get object")

  obj
end

#get_object_acl(bucket_name, object_name) ⇒ Object

Get object acl

return

the object’s acl. See ACL

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name



1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
# File 'lib/aliyun/oss/protocol.rb', line 1104

def get_object_acl(bucket_name, object_name)
  logger.debug("Begin get object acl, bucket: #{bucket_name}, "\
               "object: #{object_name}")

  sub_res = {'acl' => nil}
  r = @http.get(
    {bucket: bucket_name, object: object_name, sub_res: sub_res})

  doc = parse_xml(r.body)
  acl = get_node_text(doc.at_css("AccessControlList"), 'Grant')

  logger.debug("Done get object acl")

  acl
end

#get_object_cors(bucket_name, object_name, origin, method, headers = []) ⇒ CORSRule

Note:

this is usually used by browser to make a “preflight”

Get object CORS rule

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • origin (String)

    the Origin of the reqeust

  • method (String)

    the method to request access: Access-Control-Request-Method

  • headers (Array<String>) (defaults to: [])

    the headers to request access: Access-Control-Request-Headers

Returns:

  • (CORSRule)

    the CORS rule of the object



1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/aliyun/oss/protocol.rb', line 1130

def get_object_cors(bucket_name, object_name, origin, method, headers = [])
  logger.debug("Begin get object cors, bucket: #{bucket_name}, object: "\
               "#{object_name}, origin: #{origin}, method: #{method}, "\
               "headers: #{headers.join(',')}")

  h = {
    'origin' => origin,
    'access-control-request-method' => method,
    'access-control-request-headers' => headers.join(',')
  }

  r = @http.options(
    {:bucket => bucket_name, :object => object_name},
    {:headers => h})

  logger.debug("Done get object cors")

  CORSRule.new(
    :allowed_origins => r.headers[:access_control_allow_origin],
    :allowed_methods => r.headers[:access_control_allow_methods],
    :allowed_headers => r.headers[:access_control_allow_headers],
    :expose_headers => r.headers[:access_control_expose_headers],
    :max_age_seconds => r.headers[:access_control_max_age]
  )
end

#get_object_meta(bucket_name, object_name, opts = {}) ⇒ OSS::Object

Note:

User can specify conditions to get the object like: if-modified-since, if-unmodified-since, if-match-etag, if-unmatch-etag. If the object to get fails to meet the conditions, it will not be returned.

Get the object meta rather than the whole object.

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :condition (Hash)

    preconditions to get the object meta. The same as #get_object

Returns:



927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
# File 'lib/aliyun/oss/protocol.rb', line 927

def get_object_meta(bucket_name, object_name, opts = {})
  logger.debug("Begin get object meta, bucket: #{bucket_name}, "\
               "object: #{object_name}, options: #{opts}")

  headers = {}
  headers.merge!(get_conditions(opts[:condition])) if opts[:condition]

  r = @http.head(
    {:bucket => bucket_name, :object => object_name},
    {:headers => headers})

  h = r.headers
  metas = {}
  meta_prefix = 'x_oss_meta_'
  h.select { |k, _| k.to_s.start_with?(meta_prefix) }
    .each { |k, v| metas[k.to_s.sub(meta_prefix, '')] = v.to_s }

  obj = Object.new(
    :key => object_name,
    :type => h[:x_oss_object_type],
    :size => wrap(h[:content_length], &:to_i),
    :etag => h[:etag],
    :metas => metas,
    :last_modified => wrap(h[:last_modified]) { |x| Time.parse(x) },
    :headers => h)

  logger.debug("Done get object meta")

  obj
end

#get_request_url(bucket, object = nil) ⇒ String

Get bucket/object url

Parameters:

  • bucket (String)

    the bucket name

  • object (String) (defaults to: nil)

    the bucket name

Returns:

  • (String)

    url for the bucket/object



1492
1493
1494
# File 'lib/aliyun/oss/protocol.rb', line 1492

def get_request_url(bucket, object = nil)
  @http.get_request_url(bucket, object)
end

#get_resource_path(bucket, object = nil) ⇒ String

Get bucket/object resource path

Parameters:

  • bucket (String)

    the bucket name

  • object (String) (defaults to: nil)

    the bucket name

Returns:

  • (String)

    resource path for the bucket/object



1500
1501
1502
# File 'lib/aliyun/oss/protocol.rb', line 1500

def get_resource_path(bucket, object = nil)
  @http.get_resource_path(bucket, object)
end

#get_sts_tokenString

Get user’s STS token

Returns:



1518
1519
1520
# File 'lib/aliyun/oss/protocol.rb', line 1518

def get_sts_token
  @config.sts_token
end

#initiate_multipart_upload(bucket_name, object_name, opts = {}) ⇒ String

Initiate a a multipart uploading transaction

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :content_type (String)

    the HTTP Content-Type for the file, if not specified client will try to determine the type itself and fall back to HTTP::DEFAULT_CONTENT_TYPE if it fails to do so

  • :metas (Hash<Symbol, String>)

    key-value pairs that serve as the object meta which will be stored together with the object

  • :headers (Hash)

    custom HTTP headers, case insensitive. Headers specified here will overwrite ‘:metas` and `:content_type`

Returns:



1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'lib/aliyun/oss/protocol.rb', line 1175

def initiate_multipart_upload(bucket_name, object_name, opts = {})
  logger.info("Begin initiate multipart upload, bucket: "\
              "#{bucket_name}, object: #{object_name}, options: #{opts}")

  sub_res = {'uploads' => nil}
  headers = {'content-type' => opts[:content_type]}
  to_lower_case(opts[:metas] || {})
    .each { |k, v| headers["x-oss-meta-#{k.to_s}"] = v.to_s }

  headers.merge!(to_lower_case(opts[:headers])) if opts.key?(:headers)

  r = @http.post(
    {:bucket => bucket_name, :object => object_name,
     :sub_res => sub_res},
    {:headers => headers})

  doc = parse_xml(r.body)
  txn_id = get_node_text(doc.root, 'UploadId')

  logger.info("Done initiate multipart upload: #{txn_id}.")

  txn_id
end

#list_buckets(opts = {}) ⇒ Array<Bucket>, Hash

List all the buckets.

Parameters:

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :prefix (String)

    return only those buckets prefixed with it if specified

  • :marker (String)

    return buckets after where it indicates (exclusively). All buckets are sorted by name alphabetically

  • :limit (Integer)

    return only the first N buckets if specified

Returns:

  • (Array<Bucket>, Hash)

    the returned buckets and a hash including the next tokens, which includes:

    • :prefix [String] the prefix used

    • :delimiter [String] the delimiter used

    • :marker [String] the marker used

    • :limit [Integer] the limit used

    • :next_marker [String] marker to continue list buckets

    • :truncated [Boolean] whether there are more buckets to be returned



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/aliyun/oss/protocol.rb', line 45

def list_buckets(opts = {})
  logger.info("Begin list buckets, options: #{opts}")

  params = {
    'prefix' => opts[:prefix],
    'marker' => opts[:marker],
    'max-keys' => opts[:limit]
  }.reject { |_, v| v.nil? }

  r = @http.get( {}, {:query => params})
  doc = parse_xml(r.body)

  buckets = doc.css("Buckets Bucket").map do |node|
    Bucket.new(
      {
        :name => get_node_text(node, "Name"),
        :location => get_node_text(node, "Location"),
        :creation_time =>
          get_node_text(node, "CreationDate") { |t| Time.parse(t) }
      }, self
    )
  end

  more = {
    :prefix => 'Prefix',
    :limit => 'MaxKeys',
    :marker => 'Marker',
    :next_marker => 'NextMarker',
    :truncated => 'IsTruncated'
  }.reduce({}) { |h, (k, v)|
    value = get_node_text(doc.root, v)
    value.nil?? h : h.merge(k => value)
  }

  update_if_exists(
    more, {
      :limit => ->(x) { x.to_i },
      :truncated => ->(x) { x.to_bool }
    }
  )

  logger.info("Done list buckets, buckets: #{buckets}, more: #{more}")

  [buckets, more]
end

#list_multipart_uploads(bucket_name, opts = {}) ⇒ Array<Multipart::Transaction>, Hash

Get a list of all the on-going multipart uploading transactions. That is: thoses started and not aborted.

Parameters:

  • bucket_name (String)

    the bucket name

  • opts (Hash) (defaults to: {})

    options:

Options Hash (opts):

  • :id_marker (String)

    return only thoese transactions with txn id after :id_marker

  • :key_marker (String)

    the object key marker for a multipart upload transaction.

    1. if :id_marker is not set, return only those transactions with object key after :key_marker;

    2. if :id_marker is set, return only thoese transactions with object key equals :key_marker and txn id after :id_marker

  • :prefix (String)

    the prefix of the object key for a multipart upload transaction. if set only return those transactions with the object key prefixed with it

  • :encoding (String)

    the encoding of object key in the response body. Only KeyEncoding::URL is supported now.

Returns:

  • (Array<Multipart::Transaction>, Hash)

    the returned transactions and a hash including next tokens, which includes:

    • :prefix [String] the prefix used

    • :limit [Integer] the limit used

    • :id_marker [String] the upload id marker used

    • :next_id_marker [String] upload id marker to continue list multipart transactions

    • :key_marker [String] the object key marker used

    • :next_key_marker [String] object key marker to continue list multipart transactions

    • :truncated [Boolean] whether there are more transactions to be returned

    • :encoding [String] the object key encoding used



1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
# File 'lib/aliyun/oss/protocol.rb', line 1369

def list_multipart_uploads(bucket_name, opts = {})
  logger.debug("Begin list multipart uploads, "\
               "bucket: #{bucket_name}, opts: #{opts}")

  sub_res = {'uploads' => nil}
  params = {
    'prefix' => opts[:prefix],
    'upload-id-marker' => opts[:id_marker],
    'key-marker' => opts[:key_marker],
    'max-uploads' => opts[:limit],
    'encoding-type' => opts[:encoding]
  }.reject { |_, v| v.nil? }

  r = @http.get(
    {:bucket => bucket_name, :sub_res => sub_res},
    {:query => params})

  doc = parse_xml(r.body)
  encoding = get_node_text(doc.root, 'EncodingType')
  txns = doc.css("Upload").map do |node|
    Multipart::Transaction.new(
      :id => get_node_text(node, "UploadId"),
      :object => get_node_text(node, "Key") { |x| decode_key(x, encoding) },
      :bucket => bucket_name,
      :creation_time =>
        get_node_text(node, "Initiated") { |t| Time.parse(t) }
    )
  end || []

  more = {
    :prefix => 'Prefix',
    :limit => 'MaxUploads',
    :id_marker => 'UploadIdMarker',
    :next_id_marker => 'NextUploadIdMarker',
    :key_marker => 'KeyMarker',
    :next_key_marker => 'NextKeyMarker',
    :truncated => 'IsTruncated',
    :encoding => 'EncodingType'
  }.reduce({}) { |h, (k, v)|
    value = get_node_text(doc.root, v)
    value.nil?? h : h.merge(k => value)
  }

  update_if_exists(
    more, {
      :limit => ->(x) { x.to_i },
      :truncated => ->(x) { x.to_bool },
      :key_marker => ->(x) { decode_key(x, encoding) },
      :next_key_marker => ->(x) { decode_key(x, encoding) }
    }
  )

  logger.debug("Done list multipart transactions")

  [txns, more]
end

#list_objects(bucket_name, opts = {}) ⇒ Array<Objects>, Hash

List objects in a bucket.

Examples:

Assume we have the following objects:
   /foo/bar/obj1
   /foo/bar/obj2
   ...
   /foo/bar/obj9999999
   /foo/xxx/
use 'foo/' as the prefix, '/' as the delimiter, the common
prefixes we get are: '/foo/bar/', '/foo/xxx/'. They are
coincidentally the sub-directories under '/foo/'. Using
delimiter we avoid list all the objects whose number may be
large.

Parameters:

  • bucket_name (String)

    the bucket name

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :prefix (String)

    return only those buckets prefixed with it if specified

  • :marker (String)

    return buckets after where it indicates (exclusively). All buckets are sorted by name alphabetically

  • :limit (Integer)

    return only the first N buckets if specified

  • :delimiter (String)

    the delimiter to get common prefixes of all objects

  • :encoding (String)

    the encoding of object key in the response body. Only KeyEncoding::URL is supported now.

Returns:

  • (Array<Objects>, Hash)

    the returned object and a hash including the next tokens, which includes:

    • :common_prefixes [String] the common prefixes returned

    • :prefix [String] the prefix used

    • :delimiter [String] the delimiter used

    • :marker [String] the marker used

    • :limit [Integer] the limit used

    • :next_marker [String] marker to continue list objects

    • :truncated [Boolean] whether there are more objects to be returned



751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
# File 'lib/aliyun/oss/protocol.rb', line 751

def list_objects(bucket_name, opts = {})
  logger.debug("Begin list object, bucket: #{bucket_name}, options: #{opts}")

  params = {
    'prefix' => opts[:prefix],
    'delimiter' => opts[:delimiter],
    'marker' => opts[:marker],
    'max-keys' => opts[:limit],
    'encoding-type' => opts[:encoding]
  }.reject { |_, v| v.nil? }

  r = @http.get({:bucket => bucket_name}, {:query => params})

  doc = parse_xml(r.body)
  encoding = get_node_text(doc.root, 'EncodingType')
  objects = doc.css("Contents").map do |node|
    Object.new(
      :key => get_node_text(node, "Key") { |x| decode_key(x, encoding) },
      :type => get_node_text(node, "Type"),
      :size => get_node_text(node, "Size", &:to_i),
      :etag => get_node_text(node, "ETag"),
      :last_modified =>
        get_node_text(node, "LastModified") { |x| Time.parse(x) }
    )
  end || []

  more = {
    :prefix => 'Prefix',
    :delimiter => 'Delimiter',
    :limit => 'MaxKeys',
    :marker => 'Marker',
    :next_marker => 'NextMarker',
    :truncated => 'IsTruncated',
    :encoding => 'EncodingType'
  }.reduce({}) { |h, (k, v)|
    value = get_node_text(doc.root, v)
    value.nil?? h : h.merge(k => value)
  }

  update_if_exists(
    more, {
      :limit => ->(x) { x.to_i },
      :truncated => ->(x) { x.to_bool },
      :delimiter => ->(x) { decode_key(x, encoding) },
      :marker => ->(x) { decode_key(x, encoding) },
      :next_marker => ->(x) { decode_key(x, encoding) }
    }
  )

  common_prefixes = []
  doc.css("CommonPrefixes Prefix").map do |node|
    common_prefixes << decode_key(node.text, encoding)
  end
  more[:common_prefixes] = common_prefixes unless common_prefixes.empty?

  logger.debug("Done list object. objects: #{objects}, more: #{more}")

  [objects, more]
end

#list_parts(bucket_name, object_name, txn_id, opts = {}) ⇒ Array<Multipart::Part>, Hash

Get a list of parts that are successfully uploaded in a transaction.

Parameters:

  • txn_id (String)

    the upload id

  • opts (Hash) (defaults to: {})

    options:

Options Hash (opts):

  • :marker (Integer)

    the part number marker after which to return parts

  • :limit (Integer)

    max number parts to return

Returns:

  • (Array<Multipart::Part>, Hash)

    the returned parts and a hash including next tokens, which includes:

    • :marker [Integer] the marker used

    • :limit [Integer] the limit used

    • :next_marker [Integer] marker to continue list parts

    • :truncated [Boolean] whether there are more parts to be returned



1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
# File 'lib/aliyun/oss/protocol.rb', line 1440

def list_parts(bucket_name, object_name, txn_id, opts = {})
  logger.debug("Begin list parts, bucket: #{bucket_name}, object: "\
               "#{object_name}, txn id: #{txn_id}, options: #{opts}")

  sub_res = {'uploadId' => txn_id}
  params = {
    'part-number-marker' => opts[:marker],
    'max-parts' => opts[:limit],
    'encoding-type' => opts[:encoding]
  }.reject { |_, v| v.nil? }

  r = @http.get(
    {:bucket => bucket_name, :object => object_name, :sub_res => sub_res},
    {:query => params})

  doc = parse_xml(r.body)
  parts = doc.css("Part").map do |node|
    Multipart::Part.new(
      :number => get_node_text(node, 'PartNumber', &:to_i),
      :etag => get_node_text(node, 'ETag'),
      :size => get_node_text(node, 'Size', &:to_i),
      :last_modified =>
        get_node_text(node, 'LastModified') { |x| Time.parse(x) })
  end || []

  more = {
    :limit => 'MaxParts',
    :marker => 'PartNumberMarker',
    :next_marker => 'NextPartNumberMarker',
    :truncated => 'IsTruncated',
    :encoding => 'EncodingType'
  }.reduce({}) { |h, (k, v)|
    value = get_node_text(doc.root, v)
    value.nil?? h : h.merge(k => value)
  }

  update_if_exists(
    more, {
      :limit => ->(x) { x.to_i },
      :truncated => ->(x) { x.to_bool }
    }
  )

  logger.debug("Done list parts, parts: #{parts}, more: #{more}")

  [parts, more]
end

#put_bucket_acl(name, acl) ⇒ Object

Put bucket acl

Parameters:

  • name (String)

    the bucket name

  • acl (String)

    the bucket acl

See Also:



121
122
123
124
125
126
127
128
129
130
131
# File 'lib/aliyun/oss/protocol.rb', line 121

def put_bucket_acl(name, acl)
  logger.info("Begin put bucket acl, name: #{name}, acl: #{acl}")

  sub_res = {'acl' => nil}
  headers = {'x-oss-acl' => acl}
  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:headers => headers, :body => nil})

  logger.info("Done put bucket acl")
end

#put_bucket_encryption(name, encryption) ⇒ Object

Put bucket encryption settings

Parameters:



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/aliyun/oss/protocol.rb', line 260

def put_bucket_encryption(name, encryption)
  logger.info("Begin put bucket encryption, "\
              "name: #{name}, encryption: #{encryption}")

  sub_res = {'encryption' => nil}
  body = Nokogiri::XML::Builder.new do |xml|
    xml.ServerSideEncryptionRule {
      xml.ApplyServerSideEncryptionByDefault {
        xml.SSEAlgorithm encryption.sse_algorithm
        xml.KMSMasterKeyID encryption.kms_master_key_id if encryption.kms_master_key_id
      }
    }
  end.to_xml

  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:body => body})

  logger.info("Done put bucket encryption")
end

#put_bucket_lifecycle(name, rules) ⇒ Object

Put bucket lifecycle settings

Parameters:

See Also:



430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/aliyun/oss/protocol.rb', line 430

def put_bucket_lifecycle(name, rules)
  logger.info("Begin put bucket lifecycle, name: #{name}, rules: "\
               "#{rules.map { |r| r.to_s }}")

  sub_res = {'lifecycle' => nil}
  body = Nokogiri::XML::Builder.new do |xml|
    xml.LifecycleConfiguration {
      rules.each do |r|
        xml.Rule {
          xml.ID r.id if r.id
          xml.Status r.enabled? ? 'Enabled' : 'Disabled'

          xml.Prefix r.prefix
          xml.Expiration {
            if r.expiry.is_a?(Date)
              xml.Date Time.utc(
                         r.expiry.year, r.expiry.month, r.expiry.day)
                        .iso8601.sub('Z', '.000Z')
            elsif r.expiry.is_a?(Integer)
              xml.Days r.expiry
            else
              fail ClientError, "Expiry must be a Date or Integer."
            end
          }
        }
      end
    }
  end.to_xml

  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:body => body})

  logger.info("Done put bucket lifecycle")
end

#put_bucket_logging(name, logging) ⇒ Object

Put bucket logging settings

Parameters:



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/aliyun/oss/protocol.rb', line 152

def put_bucket_logging(name, logging)
  logger.info("Begin put bucket logging, "\
              "name: #{name}, logging: #{logging}")

  if logging.enabled? && !logging.target_bucket
    fail ClientError,
         "Must specify target bucket when enabling bucket logging."
  end

  sub_res = {'logging' => nil}
  body = Nokogiri::XML::Builder.new do |xml|
    xml.BucketLoggingStatus {
      if logging.enabled?
        xml.LoggingEnabled {
          xml.TargetBucket logging.target_bucket
          xml.TargetPrefix logging.target_prefix if logging.target_prefix
        }
      end
    }
  end.to_xml

  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:body => body})

  logger.info("Done put bucket logging")
end

#put_bucket_referer(name, referer) ⇒ Object

Put bucket referer

Parameters:



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/aliyun/oss/protocol.rb', line 381

def put_bucket_referer(name, referer)
  logger.info("Begin put bucket referer, "\
              "name: #{name}, referer: #{referer}")

  sub_res = {'referer' => nil}
  body = Nokogiri::XML::Builder.new do |xml|
    xml.RefererConfiguration {
      xml.AllowEmptyReferer referer.allow_empty?
      xml.RefererList {
        (referer.whitelist or []).each do |r|
          xml.Referer r
        end
      }
    }
  end.to_xml

  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:body => body})

  logger.info("Done put bucket referer")
end

#put_bucket_versioning(name, versioning) ⇒ Object

Put bucket versioning settings

Parameters:



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/aliyun/oss/protocol.rb', line 218

def put_bucket_versioning(name, versioning)
  logger.info("Begin put bucket versioning, "\
              "name: #{name}, versioning: #{versioning}")

  sub_res = {'versioning' => nil}
  body = Nokogiri::XML::Builder.new do |xml|
    xml.VersioningConfiguration {
      xml.Status versioning.status
    }
  end.to_xml

  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:body => body})

  logger.info("Done put bucket versioning")
end

#put_bucket_website(name, website) ⇒ Object

Put bucket website settings

Parameters:



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/aliyun/oss/protocol.rb', line 317

def put_bucket_website(name, website)
  logger.info("Begin put bucket website, "\
              "name: #{name}, website: #{website}")

  unless website.index
    fail ClientError, "Must specify index to put bucket website."
  end

  sub_res = {'website' => nil}
  body = Nokogiri::XML::Builder.new do |xml|
    xml.WebsiteConfiguration {
      xml.IndexDocument {
        xml.Suffix website.index
      }
      if website.error
        xml.ErrorDocument {
          xml.Key website.error
        }
      end
    }
  end.to_xml

  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:body => body})

  logger.info("Done put bucket website")
end

#put_object(bucket_name, object_name, opts = {}) {|HTTP::StreamWriter| ... } ⇒ Object

Put an object to the specified bucket, a block is required to provide the object data.

Examples:

chunk = get_chunk
put_object('bucket', 'object') { |sw| sw.write(chunk) }

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • :acl (String)

    specify the object’s ACL. See ACL

  • :content_type (String)

    the HTTP Content-Type for the file, if not specified client will try to determine the type itself and fall back to HTTP::DEFAULT_CONTENT_TYPE if it fails to do so

  • :metas (Hash<Symbol, String>)

    key-value pairs that serve as the object meta which will be stored together with the object

  • :callback (Callback)

    the HTTP callback performed by OSS after ‘put_object` succeeds

  • :headers (Hash)

    custom HTTP headers, case insensitive. Headers specified here will overwrite ‘:metas` and `:content_type`

Yields:

  • (HTTP::StreamWriter)

    a stream writer is yielded to the caller to which it can write chunks of data streamingly



622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'lib/aliyun/oss/protocol.rb', line 622

def put_object(bucket_name, object_name, opts = {}, &block)
  logger.debug("Begin put object, bucket: #{bucket_name}, object: "\
               "#{object_name}, options: #{opts}")

  headers = {'content-type' => opts[:content_type]}
  headers['x-oss-object-acl'] = opts[:acl] if opts.key?(:acl)
  to_lower_case(opts[:metas] || {})
    .each { |k, v| headers["x-oss-meta-#{k.to_s}"] = v.to_s }

  headers.merge!(to_lower_case(opts[:headers])) if opts.key?(:headers)

  if opts.key?(:callback)
    headers[CALLBACK_HEADER] = opts[:callback].serialize
  end

  payload = HTTP::StreamWriter.new(@config.upload_crc_enable, opts[:init_crc], &block)
  r = @http.put(
    {:bucket => bucket_name, :object => object_name},
    {:headers => headers, :body => payload})

  if r.code == 203
    e = CallbackError.new(r)
    logger.error(e.to_s)
    raise e
  end

  if @config.upload_crc_enable && !r.headers[:x_oss_hash_crc64ecma].nil?
    data_crc = payload.data_crc
    Aliyun::OSS::Util.crc_check(data_crc, r.headers[:x_oss_hash_crc64ecma], 'put')
  end

  logger.debug('Done put object')
end

#put_object_acl(bucket_name, object_name, acl) ⇒ Object

Put object acl

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • acl (String)

    the object’s ACL. See ACL



1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
# File 'lib/aliyun/oss/protocol.rb', line 1086

def put_object_acl(bucket_name, object_name, acl)
  logger.debug("Begin update object acl, bucket: #{bucket_name}, "\
               "object: #{object_name}, acl: #{acl}")

  sub_res = {'acl' => nil}
  headers = {'x-oss-object-acl' => acl}

  @http.put(
    {:bucket => bucket_name, :object => object_name, :sub_res => sub_res},
    {:headers => headers})

  logger.debug("Done update object acl")
end

#set_bucket_cors(name, rules) ⇒ Object

Set bucket CORS(Cross-Origin Resource Sharing) rules

Parameters:

  • name (String)

    the bucket name

  • rules (Array<OSS::CORSRule] the CORS rules)

    ules [Array<OSS::CORSRule] the CORS rules

See Also:



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/aliyun/oss/protocol.rb', line 514

def set_bucket_cors(name, rules)
  logger.info("Begin set bucket cors, bucket: #{name}, rules: "\
               "#{rules.map { |r| r.to_s }.join(';')}")

  sub_res = {'cors' => nil}
  body = Nokogiri::XML::Builder.new do |xml|
    xml.CORSConfiguration {
      rules.each do |r|
        xml.CORSRule {
          r.allowed_origins.each { |x| xml.AllowedOrigin x }
          r.allowed_methods.each { |x| xml.AllowedMethod x }
          r.allowed_headers.each { |x| xml.AllowedHeader x }
          r.expose_headers.each { |x| xml.ExposeHeader x }
          xml.MaxAgeSeconds r.max_age_seconds if r.max_age_seconds
        }
      end
    }
  end.to_xml

  @http.put(
    {:bucket => name, :sub_res => sub_res},
    {:body => body})

  logger.info("Done delete bucket lifecycle")
end

#sign(string_to_sign) ⇒ String

Sign a string using the stored access key secret

Parameters:

  • string_to_sign (String)

    the string to sign

Returns:



1525
1526
1527
# File 'lib/aliyun/oss/protocol.rb', line 1525

def sign(string_to_sign)
  Util.sign(@config.access_key_secret, string_to_sign)
end

#upload_crc_enableObject

Get the upload crc status



1537
1538
1539
# File 'lib/aliyun/oss/protocol.rb', line 1537

def upload_crc_enable
  @config.upload_crc_enable
end

#upload_part(bucket_name, object_name, txn_id, part_no) {|HTTP::StreamWriter| ... } ⇒ Object

Upload a part in a multipart uploading transaction.

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • txn_id (String)

    the upload id

  • part_no (Integer)

    the part number

Yields:

  • (HTTP::StreamWriter)

    a stream writer is yielded to the caller to which it can write chunks of data streamingly



1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
# File 'lib/aliyun/oss/protocol.rb', line 1207

def upload_part(bucket_name, object_name, txn_id, part_no, &block)
  logger.debug("Begin upload part, bucket: #{bucket_name}, object: "\
               "#{object_name}, txn id: #{txn_id}, part No: #{part_no}")

  sub_res = {'partNumber' => part_no, 'uploadId' => txn_id}

  payload = HTTP::StreamWriter.new(@config.upload_crc_enable, &block)
  r = @http.put(
    {:bucket => bucket_name, :object => object_name, :sub_res => sub_res},
    {:body => payload})

  if @config.upload_crc_enable && !r.headers[:x_oss_hash_crc64ecma].nil?
    data_crc = payload.data_crc
    Aliyun::OSS::Util.crc_check(data_crc, r.headers[:x_oss_hash_crc64ecma], 'put')
  end

  logger.debug("Done upload part")

  Multipart::Part.new(:number => part_no, :etag => r.headers[:etag])
end

#upload_part_by_copy(bucket_name, object_name, txn_id, part_no, source_object, opts = {}) ⇒ Object

Upload a part in a multipart uploading transaction by copying from an existent object as the part’s content. It may copy only part of the object by specifying the bytes range to read.

Parameters:

  • bucket_name (String)

    the bucket name

  • object_name (String)

    the object name

  • txn_id (String)

    the upload id

  • part_no (Integer)

    the part number

  • source_object (String)

    the source object name to copy from

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :src_bucket (String)

    specify the source object’s bucket. It MUST be in the same region as the dest bucket. It defaults to dest bucket if not specified.

  • :range (Array<Integer>)

    the bytes range to copy, int the format: [begin(inclusive), end(exclusive)]

  • :condition (Hash)

    preconditions to copy the object. See #get_object



1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
# File 'lib/aliyun/oss/protocol.rb', line 1244

def upload_part_by_copy(
      bucket_name, object_name, txn_id, part_no, source_object, opts = {})
  logger.debug("Begin upload part by copy, bucket: #{bucket_name}, "\
               "object: #{object_name}, source object: #{source_object}"\
               "txn id: #{txn_id}, part No: #{part_no}, options: #{opts}")

  range = opts[:range]
  conditions = opts[:condition]

  if range && (!range.is_a?(Array) || range.size != 2)
    fail ClientError, "Range must be an array containing 2 Integers."
  end

  src_bucket = opts[:src_bucket] || bucket_name
  headers = {
    'x-oss-copy-source' =>
      @http.get_resource_path(src_bucket, source_object)
  }
  headers['range'] = get_bytes_range(range) if range
  headers.merge!(get_copy_conditions(conditions)) if conditions

  sub_res = {'partNumber' => part_no, 'uploadId' => txn_id}

  r = @http.put(
    {:bucket => bucket_name, :object => object_name, :sub_res => sub_res},
    {:headers => headers})

  logger.debug("Done upload part by copy: #{source_object}.")

  Multipart::Part.new(:number => part_no, :etag => r.headers[:etag])
end