Migrate mc s3 client code to objecstorage-go library, now all requests from mc are signature v4 authenticated

This commit is contained in:
Harshavardhana
2015-05-13 19:05:31 -07:00
parent 9eb8314e41
commit cd93bfd251
52 changed files with 2493 additions and 1587 deletions
+4
View File
@@ -0,0 +1,4 @@
language: go
go:
- 1.4.2
sudo: false
@@ -0,0 +1,34 @@
### Setup your objectstorage-go Github Repository
Fork [objectstorage-go upstream](https://github.com/minio/objectstorage-go/fork) source repository to your own personal repository.
```sh
$ git clone https://github.com/$USER_ID/objectstorage-go
$ cd objectstorage-go
$ make
$ objectstorage-go --help
```
### Developer Guidelines
``objectstorage-go`` welcomes your contribution. To make the process as seamless as possible, we ask for the following:
* Go ahead and fork the project and make your changes. We encourage pull requests to discuss code changes.
- Fork it
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create new Pull Request
* If you have additional dependencies for ``objectstorage-go``, ``objectstorage-go`` manages its depedencies using [godep](https://github.com/tools/godep)
- Run `go get foo/bar`
- Edit your code to import foo/bar
- Run `make save` from top-level directory (or `godep restore && godep save ./...`).
* When you're ready to create a pull request, be sure to:
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
- Run `go fmt`
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
- Make sure `go test -race ./...` and `go build` completes.
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
- `objectstorage-go` project is strictly conformant with Golang style
- if you happen to observe offending code, please feel free to send a pull request
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+24
View File
@@ -0,0 +1,24 @@
# Minimal object storage library in Go
## Install
```go
# go get github.com/minio/objectstorage-go
```
## Documentation
[Objectstorage library in Go](http://godoc.org/github.com/minio/objectstorage-go)
## Join Community
* Community hangout on Gitter [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
* Ask questions on Quora [![Quora](http://upload.wikimedia.org/wikipedia/commons/thumb/5/57/Quora_logo.svg/55px-Quora_logo.svg.png)](http://www.quora.com/Minio)
## Roadmap
- Add v4 signature support
- Add s3 multi region support
## Contribute
[Contribute to minimal object storage library](./CONTRIBUTING.md)
+409
View File
@@ -0,0 +1,409 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage
import (
"errors"
"io"
"net/http"
"runtime"
"sort"
"strings"
"time"
)
// API - object storage API interface
type API interface {
// Bucket Read/Write/Stat operations
BucketAPI
// Object Read/Write/Stat operations
ObjectAPI
}
// BucketAPI - bucket specific Read/Write/Stat interface
type BucketAPI interface {
CreateBucket(bucket, acl, location string) error
SetBucketACL(bucket, acl string) error
StatBucket(bucket string) error
DeleteBucket(bucket string) error
ListObjects(bucket, prefix string, recursive bool) <-chan ObjectOnChannel
ListBuckets() <-chan BucketOnChannel
}
// ObjectAPI - object specific Read/Write/Stat interface
type ObjectAPI interface {
GetObject(bucket, object string, offset, length uint64) (io.ReadCloser, *ObjectMetadata, error)
CreateObject(bucket, object string, size uint64, data io.Reader) (string, error)
StatObject(bucket, object string) (*ObjectMetadata, error)
DeleteObject(bucket, object string) error
}
// BucketOnChannel - bucket metadata over read channel
type BucketOnChannel struct {
Data *BucketMetadata
Err error
}
// ObjectOnChannel - object metadata over read channel
type ObjectOnChannel struct {
Data *ObjectMetadata
Err error
}
// BucketMetadata container for bucket metadata
type BucketMetadata struct {
// The name of the bucket.
Name string
// Date the bucket was created.
CreationDate time.Time
}
// ObjectMetadata container for object metadata
type ObjectMetadata struct {
ETag string
Key string
LastModified time.Time
Size int64
Owner struct {
DisplayName string
ID string
}
// The class of storage used to store the object.
StorageClass string
}
// Regions s3 region map used by bucket location constraint
var Regions = map[string]string{
"us-gov-west-1": "https://s3-fips-us-gov-west-1.amazonaws.com",
"us-east-1": "https://s3.amazonaws.com",
"us-west-1": "https://s3-us-west-1.amazonaws.com",
"us-west-2": "https://s3-us-west-2.amazonaws.com",
"eu-west-1": "https://s3-eu-west-1.amazonaws.com",
"eu-central-1": "https://s3-eu-central-1.amazonaws.com",
"ap-southeast-1": "https://s3-ap-southeast-1.amazonaws.com",
"ap-southeast-2": "https://s3-ap-southeast-2.amazonaws.com",
"ap-northeast-1": "https://s3-ap-northeast-1.amazonaws.com",
"sa-east-1": "https://s3-sa-east-1.amazonaws.com",
"cn-north-1": "https://s3.cn-north-1.amazonaws.com.cn",
}
// getEndpoint fetches an endpoint based on region through the S3 Regions map
func getEndpoint(region string) string {
return Regions[region]
}
type api struct {
*lowLevelAPI
}
// Config - main configuration struct used by all to set endpoint, credentials, and other options for requests.
type Config struct {
// Standard options
AccessKeyID string
SecretAccessKey string
Region string
Endpoint string
// Advanced options
AcceptType string // specify this to get server response in non XML style if server supports it
UserAgent string // user override useful when objectstorage-go is used with in your application
Transport http.RoundTripper // custom transport usually for debugging, by default its nil
}
// MustGetEndpoint makes sure that a valid endpoint is provided all the time, even with false regions it will fall
// back to default, for no regions specified it chooses to default to "milkyway" and use endpoint as is
func (c *Config) MustGetEndpoint() string {
// for custom domains, there are no regions default to 'milkyway'
if strings.TrimSpace(c.Region) == "" && strings.TrimSpace(c.Endpoint) != "" {
c.Region = "milkyway"
return c.Endpoint
}
// if valid region provided override user provided endpoint
if endpoint := getEndpoint(strings.TrimSpace(c.Region)); endpoint != "" {
c.Endpoint = endpoint
return c.Endpoint
}
// fall back if region is set and not found, go through US-standard
c.Region = "us-east-1"
return getEndpoint(c.Region)
}
// Global constants
const (
LibraryName = "objectstorage-go/"
LibraryVersion = "0.1"
)
// New - instantiate a new minio api client
func New(config *Config) API {
// if not UserAgent provided set it to default
if strings.TrimSpace(config.UserAgent) == "" {
config.UserAgent = LibraryName + " (" + LibraryVersion + "; " + runtime.GOOS + "; " + runtime.GOARCH + ")"
}
return &api{&lowLevelAPI{config}}
}
/// Object operations
// GetObject retrieve object
//
// Additionally it also takes range arguments to download the specified range bytes of an object.
// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.
func (a *api) GetObject(bucket, object string, offset, length uint64) (io.ReadCloser, *ObjectMetadata, error) {
// get the the object
// NOTE : returned md5sum could be the md5sum of the partial object itself
// not the whole object depending on if offset range was requested or not
body, objectMetadata, err := a.getObject(bucket, object, offset, length)
if err != nil {
return nil, nil, err
}
return body, objectMetadata, nil
}
// completedParts is a wrapper to make parts sortable by their part number
// multi part completion requires list of multi parts to be sorted
type completedParts []*completePart
func (a completedParts) Len() int { return len(a) }
func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber }
// DefaultPartSize - default size per object after which PutObject becomes multipart
// one can change this value during a library import
var DefaultPartSize uint64 = 1024 * 1024 * 5
// CreateObject create an object in a bucket
//
// You must have WRITE permissions on a bucket to create an object
//
// This version of CreateObject automatically does multipart for more than 5MB worth of data
func (a *api) CreateObject(bucket, object string, size uint64, data io.Reader) (string, error) {
switch {
case size < DefaultPartSize:
// Single Part use case, use PutObject directly
for part := range MultiPart(data, DefaultPartSize) {
if part.Err != nil {
return "", part.Err
}
return "", a.putObject(bucket, object, part.Len, part.Data)
}
default:
initiateMultipartUploadResult, err := a.initiateMultipartUpload(bucket, object)
if err != nil {
return "", err
}
uploadID := initiateMultipartUploadResult.UploadID
completeMultipartUpload := new(completeMultipartUpload)
for part := range MultiPart(data, DefaultPartSize) {
if part.Err != nil {
return "", part.Err
}
completePart, err := a.uploadPart(bucket, object, uploadID, part.Num, part.Len, part.Data)
if err != nil {
return "", a.abortMultipartUpload(bucket, object, uploadID)
}
completeMultipartUpload.Part = append(completeMultipartUpload.Part, completePart)
}
sort.Sort(completedParts(completeMultipartUpload.Part))
completeMultipartUploadResult, err := a.completeMultipartUpload(bucket, object, uploadID, completeMultipartUpload)
if err != nil {
return "", a.abortMultipartUpload(bucket, object, uploadID)
}
return completeMultipartUploadResult.ETag, nil
}
return "", errors.New("Unexpected control flow")
}
// StatObject verify if object exists and you have permission to access it
func (a *api) StatObject(bucket, object string) (*ObjectMetadata, error) {
return a.headObject(bucket, object)
}
// DeleteObject remove the object from a bucket
func (a *api) DeleteObject(bucket, object string) error {
return a.deleteObject(bucket, object)
}
/// Bucket operations
// CreateBucket create a new bucket
//
// optional arguments are acl and location - by default all buckets are created
// with ``private`` acl and location set to US Standard if one wishes to set
// different ACLs and Location one can set them properly.
//
// ACL valid values
// ------------------
// private - owner gets full access [DEFAULT]
// public-read - owner gets full access, others get read access
// public-read-write - owner gets full access, others get full access too
// ------------------
//
// Location valid values
// ------------------
// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ]
// Default - US standard
func (a *api) CreateBucket(bucket, acl, location string) error {
return a.putBucket(bucket, acl, location)
}
// SetBucketACL set the permissions on an existing bucket using access control lists (ACL)
//
// Currently supported are:
// ------------------
// private - owner gets full access
// public-read - owner gets full access, others get read access
// public-read-write - owner gets full access, others get full access too
// ------------------
func (a *api) SetBucketACL(bucket, acl string) error {
return a.putBucketACL(bucket, acl)
}
// StatBucket verify if bucket exists and you have permission to access it
func (a *api) StatBucket(bucket string) error {
return a.headBucket(bucket)
}
// DeleteBucket deletes the bucket named in the URI
// NOTE: -
// All objects (including all object versions and delete markers)
// in the bucket must be deleted before successfully attempting this request
func (a *api) DeleteBucket(bucket string) error {
return a.deleteBucket(bucket)
}
// listObjectsInRoutine is an internal goroutine function called for listing objects
// This function feeds data into channel
func (a *api) listObjectsInRoutine(bucket, prefix string, recursive bool, ch chan ObjectOnChannel) {
defer close(ch)
switch {
case recursive == true:
listBucketResult, err := a.listObjects(bucket, 1000, "", prefix, "")
if err != nil {
ch <- ObjectOnChannel{
Data: nil,
Err: err,
}
return
}
for _, object := range listBucketResult.Contents {
ch <- ObjectOnChannel{
Data: object,
Err: nil,
}
}
for {
if !listBucketResult.IsTruncated {
break
}
listBucketResult, err = a.listObjects(bucket, 1000, listBucketResult.Marker, prefix, "")
if err != nil {
ch <- ObjectOnChannel{
Data: nil,
Err: err,
}
return
}
for _, object := range listBucketResult.Contents {
ch <- ObjectOnChannel{
Data: object,
Err: nil,
}
listBucketResult.Marker = object.Key
}
}
default:
listBucketResult, err := a.listObjects(bucket, 1000, "", prefix, "/")
if err != nil {
ch <- ObjectOnChannel{
Data: nil,
Err: err,
}
return
}
for _, object := range listBucketResult.Contents {
ch <- ObjectOnChannel{
Data: object,
Err: nil,
}
}
}
}
// ListObjects - (List Objects) - List some objects or all recursively
//
// ListObjects is a channel based API implemented to facilitate ease of usage of S3 API ListObjects()
// by automatically recursively traversing all objects on a given bucket if specified.
//
// Your input paramters are just bucket, prefix and recursive
//
// If you enable recursive as 'true' this function will return back all the objects in a given bucket
//
// eg:-
// api := objectstorage.New(....)
// for message := range api.ListObjects("mytestbucket", "starthere", true) {
// fmt.Println(message.Data)
// }
//
func (a *api) ListObjects(bucket string, prefix string, recursive bool) <-chan ObjectOnChannel {
ch := make(chan ObjectOnChannel)
go a.listObjectsInRoutine(bucket, prefix, recursive, ch)
return ch
}
// listBucketsInRoutine is an internal go routine function called for listing buckets
// This function feeds data into channel
func (a *api) listBucketsInRoutine(ch chan BucketOnChannel) {
defer close(ch)
listAllMyBucketListResults, err := a.listBuckets()
if err != nil {
ch <- BucketOnChannel{
Data: nil,
Err: err,
}
return
}
for _, bucket := range listAllMyBucketListResults.Buckets.Bucket {
ch <- BucketOnChannel{
Data: bucket,
Err: nil,
}
}
}
// ListBuckets list of all buckets owned by the authenticated sender of the request
//
// NOTE:
// This call requires explicit authentication, no anonymous
// requests are allowed for listing buckets
//
// eg:-
// api := objectstorage.New(....)
// for message := range api.ListBuckets() {
// fmt.Println(message.Data)
// }
//
func (a *api) ListBuckets() <-chan BucketOnChannel {
ch := make(chan BucketOnChannel)
go a.listBucketsInRoutine(ch)
return ch
}
+32
View File
@@ -0,0 +1,32 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage_test
import (
"net/http/httptest"
"testing"
)
func TestBucketOperations(t *testing.T) {
ts := httptest.NewServer(robotsTxtHandler)
defer ts.Close()
}
func TestObjectOperations(t *testing.T) {
ts := httptest.NewServer(robotsTxtHandler)
defer ts.Close()
}
@@ -0,0 +1,50 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"io"
"log"
"os"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "http://play.minio.io:9000"
config.AcceptType = ""
m := objectstorage.New(config)
reader, size, _, err := m.GetObject("testbucket", "testfile", 0, 0)
if err != nil {
log.Println(err)
}
localfile, err := os.Create("newfile")
if err != nil {
log.Println(err)
}
defer localfile.Close()
_, err = io.CopyN(localfile, reader, size)
if err != nil {
log.Println(err)
}
}
@@ -0,0 +1,40 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"log"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "http://play.minio.io:9000"
config.AcceptType = ""
m := objectstorage.New(config)
for message := range m.ListBuckets() {
if message.Err != nil {
log.Fatal(message.Err)
}
log.Println(message.Data)
}
}
@@ -0,0 +1,40 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"log"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "http://play.minio.io:9000"
config.AcceptType = ""
m := objectstorage.New(config)
for message := range m.ListObjects("public-bucket", "", true) {
if message.Err != nil {
log.Fatal(message.Err)
}
log.Println(message.Data)
}
}
@@ -0,0 +1,51 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"log"
"os"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "http://play.minio.io:9000"
config.AcceptType = ""
m := objectstorage.New(config)
object, err := os.Open("testfile")
if err != nil {
log.Fatalln(err)
}
objectInfo, err := object.Stat()
if err != nil {
object.Close()
log.Fatalln(err)
}
uploadID, err := m.CreateObject("testbucket", "testfile", uint64(objectInfo.Size()), object)
if err != nil {
object.Close()
log.Fatalln(err)
}
object.Close()
log.Println(uploadID)
}
Binary file not shown.
@@ -0,0 +1,50 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"io"
"log"
"os"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "https://s3.amazonaws.com"
config.AcceptType = ""
m := objectstorage.New(config)
reader, size, _, err := m.GetObject("testbucket", "testfile", 0, 0)
if err != nil {
log.Println(err)
}
localfile, err := os.Create("newfile")
if err != nil {
log.Println(err)
}
defer localfile.Close()
_, err = io.CopyN(localfile, reader, size)
if err != nil {
log.Println(err)
}
}
@@ -0,0 +1,40 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"log"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "https://s3.amazonaws.com"
config.AcceptType = ""
m := objectstorage.New(config)
for message := range m.ListBuckets() {
if message.Err != nil {
log.Fatal(message.Err)
}
log.Println(message.Data)
}
}
@@ -0,0 +1,40 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"log"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "https://s3.amazonaws.com"
config.AcceptType = ""
m := objectstorage.New(config)
for message := range m.ListObjects("public-bucket", "", true) {
if message.Err != nil {
log.Fatal(message.Err)
}
log.Println(message.Data)
}
}
@@ -0,0 +1,51 @@
// +build ignore
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"log"
"os"
"github.com/minio/objectstorage-go"
)
func main() {
config := new(objectstorage.Config)
config.AccessKeyID = ""
config.SecretAccessKey = ""
config.Endpoint = "https://s3.amazonaws.com"
config.AcceptType = ""
m := objectstorage.New(config)
object, err := os.Open("testfile")
if err != nil {
log.Fatalln(err)
}
objectInfo, err := object.Stat()
if err != nil {
object.Close()
log.Fatalln(err)
}
uploadID, err := m.CreateObject("testbucket", "testfile", uint64(objectInfo.Size()), object)
if err != nil {
object.Close()
log.Fatalln(err)
}
object.Close()
log.Println(uploadID)
}
Binary file not shown.
@@ -0,0 +1,513 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage
import (
"bytes"
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type lowLevelAPI struct {
config *Config
}
// putBucketRequest wrapper creates a new PutBucket request
func (a *lowLevelAPI) putBucketRequest(bucket, acl, location string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "PUT",
HTTPPath: "/" + bucket,
}
var createBucketConfigBuffer *bytes.Reader
// If location is set use it and create proper bucket configuration
switch {
case location != "":
createBucketConfig := new(createBucketConfiguration)
createBucketConfig.Location = location
createBucketConfigBytes, err := xml.Marshal(createBucketConfig)
if err != nil {
return nil, err
}
createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes)
}
var r *request
var err error
switch {
case createBucketConfigBuffer == nil:
r, err = newRequest(op, a.config, nil)
if err != nil {
return nil, err
}
default:
r, err = newRequest(op, a.config, createBucketConfigBuffer)
if err != nil {
return nil, err
}
r.req.ContentLength = int64(createBucketConfigBuffer.Len())
}
// by default bucket is private
switch {
case acl != "":
r.Set("x-amz-acl", acl)
default:
r.Set("x-amz-acl", "private")
}
return r, nil
}
/// Bucket Write Operations
// putBucket create a new bucket
//
// Requires valid AWS Access Key ID to authenticate requests
// Anonymous requests are never allowed to create buckets
//
// optional arguments are acl and location - by default all buckets are created
// with ``private`` acl and location set to US Standard if one wishes to set
// different ACLs and Location one can set them properly.
//
// ACL valid values
// ------------------
// private - owner gets full access [DEFAULT]
// public-read - owner gets full access, others get read access
// public-read-write - owner gets full access, others get full access too
// ------------------
//
// Location valid values
// ------------------
// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ]
// Default - US standard
func (a *lowLevelAPI) putBucket(bucket, acl, location string) error {
req, err := a.putBucketRequest(bucket, acl, location)
if err != nil {
return err
}
resp, err := req.Do()
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return responseToError(resp)
}
}
return resp.Body.Close()
}
// putBucketRequestACL wrapper creates a new putBucketACL request
func (a *lowLevelAPI) putBucketRequestACL(bucket, acl string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "PUT",
HTTPPath: "/" + bucket + "?acl",
}
req, err := newRequest(op, a.config, nil)
if err != nil {
return nil, err
}
req.Set("x-amz-acl", acl)
return req, nil
}
// putBucketACL set the permissions on an existing bucket using access control lists (ACL)
func (a *lowLevelAPI) putBucketACL(bucket, acl string) error {
req, err := a.putBucketRequestACL(bucket, acl)
if err != nil {
return err
}
resp, err := req.Do()
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return responseToError(resp)
}
}
return resp.Body.Close()
}
// getBucketLocationRequest wrapper creates a new getBucketLocation request
func (a *lowLevelAPI) getBucketLocationRequest(bucket string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "GET",
HTTPPath: "/" + bucket + "?location",
}
req, err := newRequest(op, a.config, nil)
if err != nil {
return nil, err
}
return req, nil
}
// getBucketLocation uses location subresource to return a bucket's region
func (a *lowLevelAPI) getBucketLocation(bucket string) (string, error) {
req, err := a.getBucketLocationRequest(bucket)
if err != nil {
return "", err
}
resp, err := req.Do()
if err != nil {
return "", err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return "", responseToError(resp)
}
}
var locationConstraint string
decoder := xml.NewDecoder(resp.Body)
err = decoder.Decode(&locationConstraint)
if err != nil {
return "", err
}
return locationConstraint, resp.Body.Close()
}
// listObjectsRequest wrapper creates a new ListObjects request
func (a *lowLevelAPI) listObjectsRequest(bucket string, maxkeys int, marker, prefix, delimiter string) (*request, error) {
// resourceQuery - get resources properly escaped and lined up before using them in http request
resourceQuery := func() string {
switch {
case marker != "":
marker = fmt.Sprintf("&marker=%s", url.QueryEscape(marker))
case prefix != "":
prefix = fmt.Sprintf("&prefix=%s", url.QueryEscape(prefix))
case delimiter != "":
delimiter = fmt.Sprintf("&delimiter=%s", url.QueryEscape(delimiter))
}
return fmt.Sprintf("?max-keys=%d", maxkeys) + marker + prefix + delimiter
}
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "GET",
HTTPPath: "/" + bucket + resourceQuery(),
}
r, err := newRequest(op, a.config, nil)
if err != nil {
return nil, err
}
return r, nil
}
/// Bucket Read Operations
// listObjects - (List Objects) - List some or all (up to 1000) of the objects in a bucket.
//
// You can use the request parameters as selection criteria to return a subset of the objects in a bucket.
// request paramters :-
// ---------
// ?marker - Specifies the key to start with when listing objects in a bucket.
// ?delimiter - A delimiter is a character you use to group keys.
// ?prefix - Limits the response to keys that begin with the specified prefix.
// ?max-keys - Sets the maximum number of keys returned in the response body.
func (a *lowLevelAPI) listObjects(bucket string, maxkeys int, marker, prefix, delimiter string) (*listBucketResult, error) {
req, err := a.listObjectsRequest(bucket, maxkeys, marker, prefix, delimiter)
if err != nil {
return nil, err
}
resp, err := req.Do()
if err != nil {
return nil, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return nil, responseToError(resp)
}
}
listBucketResult := new(listBucketResult)
decoder := xml.NewDecoder(resp.Body)
err = decoder.Decode(listBucketResult)
if err != nil {
return nil, err
}
// close body while returning, along with any error
return listBucketResult, resp.Body.Close()
}
func (a *lowLevelAPI) headBucketRequest(bucket string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "HEAD",
HTTPPath: "/" + bucket,
}
return newRequest(op, a.config, nil)
}
// headBucket - useful to determine if a bucket exists and you have permission to access it.
func (a *lowLevelAPI) headBucket(bucket string) error {
req, err := a.headBucketRequest(bucket)
if err != nil {
return err
}
resp, err := req.Do()
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
// Head has no response body, handle it
return fmt.Errorf("%s", resp.Status)
}
}
return resp.Body.Close()
}
// deleteBucketRequest wrapper creates a new DeleteBucket request
func (a *lowLevelAPI) deleteBucketRequest(bucket string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "DELETE",
HTTPPath: "/" + bucket,
}
return newRequest(op, a.config, nil)
}
// deleteBucket - deletes the bucket named in the URI
// NOTE: -
// All objects (including all object versions and delete markers)
// in the bucket must be deleted before successfully attempting this request
func (a *lowLevelAPI) deleteBucket(bucket string) error {
req, err := a.deleteBucketRequest(bucket)
if err != nil {
return err
}
resp, err := req.Do()
if err != nil {
return err
}
return resp.Body.Close()
}
/// Object Read/Write/Stat Operations
// putObjectRequest wrapper creates a new PutObject request
func (a *lowLevelAPI) putObjectRequest(bucket, object string, size int64, body io.ReadSeeker) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "PUT",
HTTPPath: "/" + bucket + "/" + object,
}
md5SumBytes, err := sumMD5Reader(body, size)
if err != nil {
return nil, err
}
r, err := newRequest(op, a.config, body)
if err != nil {
return nil, err
}
// set Content-MD5 as base64 encoded md5
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
r.req.ContentLength = size
return r, nil
}
// putObject - add an object to a bucket
//
// You must have WRITE permissions on a bucket to add an object to it.
func (a *lowLevelAPI) putObject(bucket, object string, size int64, body io.ReadSeeker) error {
req, err := a.putObjectRequest(bucket, object, size, body)
if err != nil {
return err
}
resp, err := req.Do()
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return responseToError(resp)
}
}
return resp.Body.Close()
}
// getObjectRequest wrapper creates a new GetObject request
func (a *lowLevelAPI) getObjectRequest(bucket, object string, offset, length uint64) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "GET",
HTTPPath: "/" + bucket + "/" + object,
}
r, err := newRequest(op, a.config, nil)
if err != nil {
return nil, err
}
// TODO - fix this to support full - http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
switch {
case length > 0:
r.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
default:
r.Set("Range", fmt.Sprintf("bytes=%d-", offset))
}
return r, nil
}
// getObject - retrieve object from Object Storage
//
// Additionally it also takes range arguments to download the specified range bytes of an object.
// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.
func (a *lowLevelAPI) getObject(bucket, object string, offset, length uint64) (io.ReadCloser, *ObjectMetadata, error) {
req, err := a.getObjectRequest(bucket, object, offset, length)
if err != nil {
return nil, nil, err
}
resp, err := req.Do()
if err != nil {
return nil, nil, err
}
if resp != nil {
switch resp.StatusCode {
case http.StatusOK:
case http.StatusPartialContent:
default:
return nil, nil, responseToError(resp)
}
}
md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
if md5sum == "" {
return nil, nil, errors.New("missing ETag")
}
date, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
if err != nil {
return nil, nil, err
}
objectmetadata := new(ObjectMetadata)
objectmetadata.ETag = md5sum
objectmetadata.Key = object
objectmetadata.Size = resp.ContentLength
objectmetadata.LastModified = date
// do not close body here, caller will close
return resp.Body, objectmetadata, nil
}
// headObjectRequest wrapper creates a new HeadObject request
func (a *lowLevelAPI) headObjectRequest(bucket, object string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "HEAD",
HTTPPath: "/" + bucket + "/" + object,
}
return newRequest(op, a.config, nil)
}
// headObject - retrieves metadata from an object without returning the object itself
func (a *lowLevelAPI) headObject(bucket, object string) (*ObjectMetadata, error) {
req, err := a.headObjectRequest(bucket, object)
if err != nil {
return nil, err
}
resp, err := req.Do()
if err != nil {
return nil, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return nil, responseToError(resp)
}
}
md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
if md5sum == "" {
return nil, errors.New("missing ETag")
}
size, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
if err != nil {
return nil, err
}
date, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
if err != nil {
return nil, err
}
objectmetadata := new(ObjectMetadata)
objectmetadata.ETag = md5sum
objectmetadata.Key = object
objectmetadata.Size = size
objectmetadata.LastModified = date
return objectmetadata, nil
}
// deleteObjectRequest wrapper creates a new DeleteObject request
func (a *lowLevelAPI) deleteObjectRequest(bucket, object string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "DELETE",
HTTPPath: "/" + bucket + "/" + object,
}
return newRequest(op, a.config, nil)
}
// deleteObject removes the object
func (a *lowLevelAPI) deleteObject(bucket, object string) error {
req, err := a.deleteObjectRequest(bucket, object)
if err != nil {
return err
}
resp, err := req.Do()
if err != nil {
return err
}
return resp.Body.Close()
}
/// Service Operations
// listBucketRequest wrapper creates a new ListBuckets request
func (a *lowLevelAPI) listBucketsRequest() (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "GET",
HTTPPath: "/",
}
return newRequest(op, a.config, nil)
}
// listBuckets list of all buckets owned by the authenticated sender of the request
func (a *lowLevelAPI) listBuckets() (*listAllMyBucketsResult, error) {
req, err := a.listBucketsRequest()
if err != nil {
return nil, err
}
resp, err := req.Do()
if err != nil {
return nil, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return nil, responseToError(resp)
}
}
listAllMyBucketsResult := new(listAllMyBucketsResult)
decoder := xml.NewDecoder(resp.Body)
err = decoder.Decode(listAllMyBucketsResult)
if err != nil {
return nil, err
}
return listAllMyBucketsResult, resp.Body.Close()
}
@@ -0,0 +1,77 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"io"
)
// sum256Reader calculate sha256 sum for an input reader
func sum256Reader(reader io.ReadSeeker) ([]byte, error) {
h := sha256.New()
var err error
start, _ := reader.Seek(0, 1)
defer reader.Seek(start, 0)
for err == nil {
length := 0
byteBuffer := make([]byte, 1024*1024)
length, err = reader.Read(byteBuffer)
byteBuffer = byteBuffer[0:length]
h.Write(byteBuffer)
}
if err != io.EOF {
return nil, err
}
return h.Sum(nil), nil
}
// sum256 calculate sha256 sum for an input byte array
func sum256(data []byte) []byte {
hash := sha256.New()
hash.Write(data)
return hash.Sum(nil)
}
// sumHMAC calculate hmac between two input byte array
func sumHMAC(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key)
hash.Write(data)
return hash.Sum(nil)
}
// sumMD5Reader calculate md5 for an input reader of a given size
func sumMD5Reader(body io.ReadSeeker, size int64) ([]byte, error) {
hasher := md5.New()
_, err := io.CopyN(hasher, body, size)
if err != nil {
return nil, err
}
// seek back
_, err = body.Seek(0, 0)
if err != nil {
return nil, err
}
// encode the md5 checksum in base64
return hasher.Sum(nil), nil
}
@@ -0,0 +1,132 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage
import "time"
// listAllMyBucketsResult container for ListBucets response
type listAllMyBucketsResult struct {
// Container for one or more buckets.
Buckets struct {
Bucket []*BucketMetadata
}
Owner owner
}
// owner container for bucket owner information
type owner struct {
DisplayName string
ID string
}
// commonPrefix container for prefix response in ListObjects
type commonPrefix struct {
Prefix string
}
// listBucketResult container for ListObjects response
type listBucketResult struct {
CommonPrefixes []*commonPrefix // A response can contain CommonPrefixes only if you specify a delimiter
Contents []*ObjectMetadata // Metadata about each object returned
Delimiter string
// Encoding type used to encode object keys in the response.
EncodingType string
// A flag that indicates whether or not ListObjects returned all of the results
// that satisfied the search criteria.
IsTruncated bool
Marker string
MaxKeys int64
Name string
// When response is truncated (the IsTruncated element value in the response
// is true), you can use the key name in this field as marker in the subsequent
// request to get next set of objects. Object storage lists objects in alphabetical
// order Note: This element is returned only if you have delimiter request parameter
// specified. If response does not include the NextMaker and it is truncated,
// you can use the value of the last Key in the response as the marker in the
// subsequent request to get the next set of object keys.
NextMarker string
Prefix string
}
// initiator container for who initiated multipart upload
type initiator struct {
ID string
DisplayName string
}
// part container for particular part of an object
type part struct {
PartNumber int
LastModified time.Time `type:"timestamp" timestampFormat:"iso8601"`
ETag string
Size int64
}
// listObjectPartsResult container for ListObjectParts response
type listObjectPartsResult struct {
Bucket string
Key string
UploadID string `xml:"UploadId"`
Initiator initiator
Owner owner
StorageClass string
PartNumberMarker int
NextPartNumberMarker int
MaxParts int
// Indicates whether the returned list of parts is truncated.
IsTruncated bool
Part []*part
EncodingType string
}
// initiateMultipartUploadResult container for InitiateMultiPartUpload response
type initiateMultipartUploadResult struct {
Bucket string
Key string
UploadID string `xml:"UploadId"`
}
// completeMultipartUploadResult containe for completed multipart upload response
type completeMultipartUploadResult struct {
Location string
Bucket string
Key string
ETag string
}
// completePart sub container lists individual part numbers and their md5sum, part of CompleteMultipartUpload
type completePart struct {
PartNumber int
ETag string
}
// completeMultipartUpload container for completing multipart upload
type completeMultipartUpload struct {
Part []*completePart
}
// createBucketConfiguration container for bucket configuration
type createBucketConfiguration struct {
Location string `xml:"LocationConstraint"`
}
@@ -0,0 +1,58 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage
import (
"encoding/xml"
"net/http"
)
/* **** SAMPLE ERROR RESPONSE ****
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<Resource>/mybucket/myphoto.jpg</Resource>
<RequestId>F19772218238A85A</RequestId>
<HostId>GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD</HostId>
</Error>
*/
// errorResponse is the type returned by some API operations.
type errorResponse struct {
Code string
Message string
Resource string
RequestID string
HostID string
}
// responseToError returns a new encoded ErrorResponse structure
func responseToError(res *http.Response) error {
var respError errorResponse
decoder := xml.NewDecoder(res.Body)
err := decoder.Decode(&respError)
if err != nil {
return err
}
return respError
}
// Error formats HTTP error string
func (e errorResponse) Error() string {
return e.Message
}
@@ -0,0 +1,202 @@
package objectstorage
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/xml"
"fmt"
"io"
"net/http"
"strconv"
)
// initiateMultipartRequest wrapper creates a new InitiateMultiPart request
func (a *lowLevelAPI) initiateMultipartRequest(bucket, object string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "POST",
HTTPPath: "/" + bucket + "/" + object + "?uploads",
}
return newRequest(op, a.config, nil)
}
// initiateMultipartUpload initiates a multipart upload and returns an upload ID
func (a *lowLevelAPI) initiateMultipartUpload(bucket, object string) (*initiateMultipartUploadResult, error) {
req, err := a.initiateMultipartRequest(bucket, object)
if err != nil {
return nil, err
}
resp, err := req.Do()
if err != nil {
return nil, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return nil, responseToError(resp)
}
}
initiateMultipartUploadResult := new(initiateMultipartUploadResult)
decoder := xml.NewDecoder(resp.Body)
err = decoder.Decode(initiateMultipartUploadResult)
if err != nil {
return nil, err
}
return initiateMultipartUploadResult, resp.Body.Close()
}
// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request
func (a *lowLevelAPI) completeMultipartUploadRequest(bucket, object, uploadID string, complete *completeMultipartUpload) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "POST",
HTTPPath: "/" + bucket + "/" + object + "?uploadId=" + uploadID,
}
completeMultipartUploadBytes, err := xml.Marshal(complete)
if err != nil {
return nil, err
}
completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)
r, err := newRequest(op, a.config, completeMultipartUploadBuffer)
if err != nil {
return nil, err
}
r.req.ContentLength = int64(completeMultipartUploadBuffer.Len())
return r, nil
}
// completeMultipartUpload completes a multipart upload by assembling previously uploaded parts.
func (a *lowLevelAPI) completeMultipartUpload(bucket, object, uploadID string, c *completeMultipartUpload) (*completeMultipartUploadResult, error) {
req, err := a.completeMultipartUploadRequest(bucket, object, uploadID, c)
if err != nil {
return nil, err
}
resp, err := req.Do()
if err != nil {
return nil, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return nil, responseToError(resp)
}
}
completeMultipartUploadResult := new(completeMultipartUploadResult)
decoder := xml.NewDecoder(resp.Body)
err = decoder.Decode(completeMultipartUploadResult)
if err != nil {
return nil, err
}
return completeMultipartUploadResult, resp.Body.Close()
}
// abortMultipartUploadRequest wrapper creates a new AbortMultipartUpload request
func (a *lowLevelAPI) abortMultipartUploadRequest(bucket, object, uploadID string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "DELETE",
HTTPPath: "/" + bucket + "/" + object + "?uploadId=" + uploadID,
}
return newRequest(op, a.config, nil)
}
// abortMultipartUpload aborts a multipart upload for the given uploadID, all parts are deleted
func (a *lowLevelAPI) abortMultipartUpload(bucket, object, uploadID string) error {
req, err := a.abortMultipartUploadRequest(bucket, object, uploadID)
if err != nil {
return err
}
resp, err := req.Do()
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode != http.StatusNoContent {
// Abort has no response body, handle it
return fmt.Errorf("%s", resp.Status)
}
}
return resp.Body.Close()
}
// listObjectPartsRequest wrapper creates a new ListObjectParts request
func (a *lowLevelAPI) listObjectPartsRequest(bucket, object, uploadID string) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "GET",
HTTPPath: "/" + bucket + "/" + object + "?uploadId=" + uploadID,
}
return newRequest(op, a.config, nil)
}
// listObjectParts lists the parts that have been uploaded for a specific multipart upload.
func (a *lowLevelAPI) listObjectParts(bucket, object, uploadID string) (*listObjectPartsResult, error) {
req, err := a.listObjectPartsRequest(bucket, object, uploadID)
if err != nil {
return nil, err
}
resp, err := req.Do()
if err != nil {
return nil, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return nil, responseToError(resp)
}
}
listObjectPartsResult := new(listObjectPartsResult)
decoder := xml.NewDecoder(resp.Body)
err = decoder.Decode(listObjectPartsResult)
if err != nil {
return nil, err
}
return listObjectPartsResult, resp.Body.Close()
}
// uploadPartRequest wrapper creates a new UploadPart request
func (a *lowLevelAPI) uploadPartRequest(bucket, object, uploadID string, partNumber int, size int64, body io.ReadSeeker) (*request, error) {
op := &operation{
HTTPServer: a.config.MustGetEndpoint(),
HTTPMethod: "PUT",
HTTPPath: "/" + bucket + "/" + object + "?partNumber=" + strconv.Itoa(partNumber) + "&uploadId=" + uploadID,
}
md5SumBytes, err := sumMD5Reader(body, size)
if err != nil {
return nil, err
}
r, err := newRequest(op, a.config, body)
if err != nil {
return nil, err
}
// set Content-MD5 as base64 encoded md5
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
r.req.ContentLength = size
return r, nil
}
// uploadPart uploads a part in a multipart upload.
func (a *lowLevelAPI) uploadPart(bucket, object, uploadID string, partNumber int, size int64, body io.ReadSeeker) (*completePart, error) {
req, err := a.uploadPartRequest(bucket, object, uploadID, partNumber, size, body)
if err != nil {
return nil, err
}
// get hex encoding for md5sum in base64
md5SumBytes, err := base64.StdEncoding.DecodeString(req.Get("Content-MD5"))
if err != nil {
return nil, err
}
completePart := new(completePart)
completePart.PartNumber = partNumber
completePart.ETag = "\"" + hex.EncodeToString(md5SumBytes) + "\""
// initiate the request
resp, err := req.Do()
if err != nil {
return nil, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return nil, responseToError(resp)
}
}
return completePart, resp.Body.Close()
}
@@ -0,0 +1,237 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage
import (
"bytes"
"encoding/hex"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
// operation - rest operation
type operation struct {
HTTPServer string
HTTPMethod string
HTTPPath string
}
// request - a http request
type request struct {
req *http.Request
config *Config
body io.ReadSeeker
}
const (
authHeaderPrefix = "AWS4-HMAC-SHA256"
iso8601Format = "20060102T150405Z"
yyyymmdd = "20060102"
)
var ignoredHeaders = map[string]bool{
"Authorization": true,
"Content-Type": true,
"Content-Length": true,
"User-Agent": true,
}
// newRequest - instantiate a new request
func newRequest(op *operation, config *Config, body io.ReadSeeker) (*request, error) {
// if no method default to POST
method := op.HTTPMethod
if method == "" {
method = "POST"
}
// parse URL for the combination of HTTPServer + HTTPPath
u, err := url.Parse(op.HTTPServer + op.HTTPPath)
if err != nil {
return nil, err
}
// get a new HTTP request, for the requested method
req, err := http.NewRequest(method, u.String(), nil)
if err != nil {
return nil, err
}
// set UserAgent
req.Header.Set("User-Agent", config.UserAgent)
// set Accept header for response encoding style, if available
if config.AcceptType != "" {
req.Header.Set("Accept", config.AcceptType)
}
// add body
switch {
case body == nil:
req.Body = nil
default:
req.Body = ioutil.NopCloser(body)
}
// save for subsequent use
r := new(request)
r.config = config
r.req = req
r.body = body
return r, nil
}
// Do - start the request
func (r *request) Do() (resp *http.Response, err error) {
if r.config.AccessKeyID != "" && r.config.SecretAccessKey != "" {
r.SignV4()
}
client := &http.Client{}
if r.config.Transport != nil {
client.Transport = r.config.Transport
}
return client.Do(r.req)
}
// Set - set additional headers if any
func (r *request) Set(key, value string) {
r.req.Header.Set(key, value)
}
// Get - get header values
func (r *request) Get(key string) string {
return r.req.Header.Get(key)
}
// SignV4 the request before Do() (version 4.0)
func (r *request) SignV4() {
t := time.Now().UTC()
// Add date if not present
if date := r.Get("Date"); date == "" {
r.Set("X-Amz-Date", t.Format(iso8601Format))
}
hash := func() string {
switch {
case r.body == nil:
return hex.EncodeToString(sum256([]byte{}))
default:
sum256Bytes, _ := sum256Reader(r.body)
return hex.EncodeToString(sum256Bytes)
}
}
bodyDigest := hash()
r.req.Header.Add("X-Amz-Content-Sha256", bodyDigest)
canonicalHeaders := func() string {
var headers []string
vals := make(map[string][]string)
for k, vv := range r.req.Header {
if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
continue // ignored header
}
headers = append(headers, strings.ToLower(k))
vals[strings.ToLower(k)] = vv
}
headers = append(headers, "host")
sort.Strings(headers)
var buf bytes.Buffer
for _, k := range headers {
buf.WriteString(k)
buf.WriteByte(':')
switch {
case k == "host":
buf.WriteString(r.req.URL.Host)
fallthrough
default:
for idx, v := range vals[k] {
if idx > 0 {
buf.WriteByte(',')
}
buf.WriteString(v)
}
buf.WriteByte('\n')
}
}
return buf.String()
}
signedHeaders := func() string {
var headers []string
for k := range r.req.Header {
if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
continue // ignored header
}
headers = append(headers, strings.ToLower(k))
}
headers = append(headers, "host")
sort.Strings(headers)
return strings.Join(headers, ";")
}
canonicalRequest := func() string {
r.req.URL.RawQuery = strings.Replace(r.req.URL.Query().Encode(), "+", "%20", -1)
canonicalRequest := strings.Join([]string{
r.req.Method,
r.req.URL.Path,
r.req.URL.RawQuery,
canonicalHeaders(),
signedHeaders(),
bodyDigest,
}, "\n")
return canonicalRequest
}
scope := strings.Join([]string{
t.Format(yyyymmdd),
r.config.Region,
"s3",
"aws4_request",
}, "/")
stringToSign := func() string {
stringToSign := authHeaderPrefix + "\n" + t.Format(iso8601Format) + "\n"
stringToSign = stringToSign + scope + "\n"
stringToSign = stringToSign + hex.EncodeToString(sum256([]byte(canonicalRequest())))
return stringToSign
}
signingKey := func() []byte {
secret := r.config.SecretAccessKey
date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
region := sumHMAC(date, []byte(r.config.Region))
service := sumHMAC(region, []byte("s3"))
signingKey := sumHMAC(service, []byte("aws4_request"))
return signingKey
}
signature := func() string {
return hex.EncodeToString(sumHMAC(signingKey(), []byte(stringToSign())))
}
parts := []string{authHeaderPrefix + " Credential=" + r.config.AccessKeyID + "/" + scope,
"SignedHeaders=" + signedHeaders(), "Signature=" + signature(),
}
auth := strings.Join(parts, ", ")
r.Set("Authorization", auth)
}
@@ -0,0 +1,53 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage_test
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
var robotsTxtHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Last-Modified", "sometime")
fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
})
func TestNewRequest(t *testing.T) {
}
func TestResponseToError(t *testing.T) {
}
func TestCommonFunctions(t *testing.T) {
}
func TestLowLevelBucketOperations(t *testing.T) {
ts := httptest.NewServer(robotsTxtHandler)
defer ts.Close()
}
func TestLowLevelObjectOperations(t *testing.T) {
ts := httptest.NewServer(robotsTxtHandler)
defer ts.Close()
}
func TestLowLevelMultiPartOperations(t *testing.T) {
ts := httptest.NewServer(robotsTxtHandler)
defer ts.Close()
}
+97
View File
@@ -0,0 +1,97 @@
/*
* Minimal object storage library (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectstorage
import (
"bytes"
"io"
)
// Part - message structure for results from the MultiPart
type Part struct {
Data io.ReadSeeker
Err error
Len int64
Num int // part number
}
// MultiPart reads from io.Reader, partitions the data into chunks of given chunksize, and sends
// each chunk as io.ReadSeeker to the caller over a channel
//
// This method runs until an EOF or error occurs. If an error occurs,
// the method sends the error over the channel and returns.
// Before returning, the channel is always closed.
func MultiPart(reader io.Reader, chunkSize uint64) <-chan Part {
ch := make(chan Part)
go multiPartInRoutine(reader, chunkSize, ch)
return ch
}
func multiPartInRoutine(reader io.Reader, chunkSize uint64, ch chan Part) {
defer close(ch)
part := make([]byte, chunkSize)
n, err := io.ReadFull(reader, part)
if err == io.EOF || err == io.ErrUnexpectedEOF { // short read, only single part return
ch <- Part{
Data: bytes.NewReader(part[0:n]),
Err: nil,
Len: int64(n),
Num: 1,
}
return
}
// catastrophic error send error and return
if err != nil {
ch <- Part{
Data: nil,
Err: err,
Num: 0,
}
return
}
// send the first part
var num = 1
ch <- Part{
Data: bytes.NewReader(part),
Err: nil,
Len: int64(n),
Num: num,
}
for err == nil {
var n int
part := make([]byte, chunkSize)
n, err = io.ReadFull(reader, part)
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF { // catastrophic error
ch <- Part{
Data: nil,
Err: err,
Num: 0,
}
return
}
}
num++
ch <- Part{
Data: bytes.NewReader(part[0:n]),
Err: nil,
Len: int64(n),
Num: num,
}
}
}