Get rid of client interface and move s3 back into a struct

This commit is contained in:
Harshavardhana
2015-04-08 16:06:25 -07:00
parent 3af592d342
commit 4a2facfa7b
19 changed files with 74 additions and 114 deletions
+2 -3
View File
@@ -26,8 +26,7 @@ import (
"github.com/cheggaaa/pb"
"github.com/minio-io/iodine"
"github.com/minio-io/mc/pkg/client"
"github.com/minio-io/mc/pkg/client/s3"
"github.com/minio-io/mc/pkg/s3"
)
// StartBar -- instantiate a progressbar
@@ -156,7 +155,7 @@ func getTraceTransport() s3.RoundTripTrace {
}
// NewClient - get new client
func getNewClient(debug bool, urlStr string) (clnt client.Client, err error) {
func getNewClient(debug bool, urlStr string) (clnt *s3.Client, err error) {
config, err := getMcConfig()
if err != nil {
return nil, iodine.New(err, nil)
+4 -4
View File
@@ -23,7 +23,7 @@ import (
"github.com/cheggaaa/pb"
"github.com/minio-io/cli"
"github.com/minio-io/iodine"
"github.com/minio-io/mc/pkg/client"
"github.com/minio-io/mc/pkg/s3"
"github.com/minio-io/minio/pkg/utils/log"
)
@@ -32,7 +32,7 @@ const (
)
// printBuckets lists buckets and its meta-dat
func printBuckets(v []*client.Bucket) {
func printBuckets(v []*s3.Bucket) {
for _, b := range v {
msg := fmt.Sprintf("%23s %13s %s", b.CreationDate.Local().Format(printDate), "", b.Name)
info(msg)
@@ -40,7 +40,7 @@ func printBuckets(v []*client.Bucket) {
}
// printObjects prints a meta-data of a list of objects
func printObjects(v []*client.Item) {
func printObjects(v []*s3.Item) {
if len(v) > 0 {
// Items are already sorted
for _, b := range v {
@@ -57,7 +57,7 @@ func printObject(date time.Time, v int64, key string) {
// doListCmd lists objects inside a bucket
func doListCmd(ctx *cli.Context) {
var items []*client.Item
var items []*s3.Item
urlStr, err := parseURL(ctx.Args().First())
if err != nil {
+1 -1
View File
@@ -19,7 +19,7 @@ package main
import (
"github.com/minio-io/cli"
"github.com/minio-io/iodine"
"github.com/minio-io/mc/pkg/client/s3"
"github.com/minio-io/mc/pkg/s3"
"github.com/minio-io/minio/pkg/utils/log"
)
-55
View File
@@ -1,55 +0,0 @@
/*
* Minimalist Object Storage, (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 client
import (
"io"
"time"
)
// Client - client interface
type Client interface {
// Bucket operations
PutBucket(bucket string) error
StatBucket(bucket string) error
ListBuckets() ([]*Bucket, error)
ListObjects(bucket, keyPrefix string) (items []*Item, err error)
// Object operations
Get(bucket, object string) (body io.ReadCloser, size int64, md5 string, err error)
GetPartial(bucket, key string, offset, length int64) (body io.ReadCloser, size int64, md5 string, err error)
Put(bucket, object, md5 string, size int64, body io.Reader) error
StatObject(bucket, object string) (size int64, date time.Time, err error)
}
// Bucket - carries s3 bucket reply header
type Bucket struct {
Name string
CreationDate time.Time // 2006-02-03T16:45:09.000Z
}
// Item - object item list
type Item struct {
Key string
LastModified time.Time
Size int64
}
// Prefix - common prefix
type Prefix struct {
Prefix string
}
+7 -7
View File
@@ -56,7 +56,7 @@ import (
"encoding/base64"
)
func (a *s3Client) loadKeys(cert string, key string) (*TLSConfig, error) {
func (a *Client) loadKeys(cert string, key string) (*TLSConfig, error) {
certBlock, err := ioutil.ReadFile(cert)
if err != nil {
return nil, err
@@ -71,7 +71,7 @@ func (a *s3Client) loadKeys(cert string, key string) (*TLSConfig, error) {
return t, nil
}
func (a *s3Client) getTLSTransport() (*http.Transport, error) {
func (a *Client) getTLSTransport() (*http.Transport, error) {
if a.CertPEM == "" || a.KeyPEM == "" {
return &http.Transport{
Dial: (&net.Dialer{
@@ -103,7 +103,7 @@ func (a *s3Client) getTLSTransport() (*http.Transport, error) {
return transport, nil
}
func (a *s3Client) signRequest(req *http.Request, host string) {
func (a *Client) signRequest(req *http.Request, host string) {
if date := req.Header.Get("Date"); date == "" {
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
@@ -137,7 +137,7 @@ func firstNonEmptyString(strs ...string) string {
// Date + "\n" +
// CanonicalizedAmzHeaders +
// CanonicalizedResource;
func (a *s3Client) stringToSign(req *http.Request, host string) string {
func (a *Client) stringToSign(req *http.Request, host string) string {
buf := new(bytes.Buffer)
buf.WriteString(req.Method)
buf.WriteByte('\n')
@@ -166,7 +166,7 @@ func hasPrefixCaseInsensitive(s, pfx string) bool {
return shead == pfx || shead == strings.ToLower(pfx)
}
func (a *s3Client) writeCanonicalizedAmzHeaders(buf *bytes.Buffer, req *http.Request) {
func (a *Client) writeCanonicalizedAmzHeaders(buf *bytes.Buffer, req *http.Request) {
var amzHeaders []string
vals := make(map[string][]string)
for k, vv := range req.Header {
@@ -228,7 +228,7 @@ var subResList = []string{
// CanonicalizedResource = [ "/" + Bucket ] +
// <HTTP-Request-URI, from the protocol name up to the query string> +
// [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"];
func (a *s3Client) writeCanonicalizedResource(buf *bytes.Buffer, req *http.Request, host string) {
func (a *Client) writeCanonicalizedResource(buf *bytes.Buffer, req *http.Request, host string) {
bucket := a.bucketFromHost(req, host)
if bucket != "" {
buf.WriteByte('/')
@@ -262,7 +262,7 @@ func hasDotSuffix(s string, suffix string) bool {
return len(s) >= len(suffix)+1 && strings.HasSuffix(s, suffix) && s[len(s)-len(suffix)-1] == '.'
}
func (a *s3Client) bucketFromHost(req *http.Request, host string) string {
func (a *Client) bucketFromHost(req *http.Request, host string) string {
reqHost := req.Host
if reqHost == "" {
host = req.URL.Host
@@ -60,7 +60,7 @@ func req(s string) *http.Request {
}
func TestStringToSign(t *testing.T) {
var a s3Client
var a Client
tests := []reqAndExpected{
{`GET /photos/puppy.jpg HTTP/1.1
Host: johnsmith.s3.amazonaws.com
@@ -119,7 +119,7 @@ Content-Length: 5913339
}
func TestBucketFromHostname(t *testing.T) {
var a s3Client
var a Client
tests := []reqAndExpected{
{"GET / HTTP/1.0\n\n", "", ""},
{"GET / HTTP/1.0\nHost: s3.amazonaws.com\n\n", "", "s3.amazonaws.com"},
@@ -139,7 +139,7 @@ func TestsignRequest(t *testing.T) {
r := req("GET /foo HTTP/1.1\n\n")
auth := &Auth{AccessKeyID: "key", SecretAccessKey: "secretkey"}
url, _ := url.Parse("localhost:9000")
cl := &s3Client{
cl := &Client{
&Meta{
Auth: auth,
Transport: http.DefaultTransport,
+8 -7
View File
@@ -47,11 +47,10 @@ import (
"net/http"
"github.com/minio-io/iodine"
"github.com/minio-io/mc/pkg/client"
)
// bySize implements sort.Interface for []Item based on the Size field.
type bySize []*client.Item
type bySize []*Item
func (a bySize) Len() int { return len(a) }
func (a bySize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
@@ -60,7 +59,7 @@ func (a bySize) Less(i, j int) bool { return a[i].Size < a[j].Size }
/// Bucket API operations
// ListBuckets - Get list of buckets
func (c *s3Client) ListBuckets() ([]*client.Bucket, error) {
func (c *Client) ListBuckets() ([]*Bucket, error) {
u := fmt.Sprintf("%s://%s/", c.Scheme, c.Host)
req := newReq(u)
c.signRequest(req, c.Host)
@@ -79,7 +78,7 @@ func (c *s3Client) ListBuckets() ([]*client.Bucket, error) {
}
// PutBucket - create new bucket
func (c *s3Client) PutBucket(bucket string) error {
func (c *Client) PutBucket(bucket string) error {
if !IsValidBucketName(bucket) || strings.Contains(bucket, ".") {
return errors.New("invalid bucket")
}
@@ -100,7 +99,8 @@ func (c *s3Client) PutBucket(bucket string) error {
return nil
}
func (c *s3Client) StatBucket(bucket string) error {
// StatBucket - check if bucket can be accessed
func (c *Client) StatBucket(bucket string) error {
if bucket == "" {
return iodine.New(errors.New("invalid argument"), nil)
}
@@ -127,11 +127,12 @@ func (c *s3Client) StatBucket(bucket string) error {
}
}
func (c *s3Client) ListObjects(bucket, objectPrefix string) (items []*client.Item, err error) {
// ListObjects - list objects
func (c *Client) ListObjects(bucket, objectPrefix string) (items []*Item, err error) {
size, date, err := c.StatObject(bucket, objectPrefix)
switch err {
case nil: // List a single object. Exact key
items = append(items, &client.Item{Key: objectPrefix, LastModified: date, Size: size})
items = append(items, &Item{Key: objectPrefix, LastModified: date, Size: size})
return items, nil
default:
// List all objects matching the key prefix
@@ -12,13 +12,23 @@ import (
"time"
"github.com/minio-io/iodine"
"github.com/minio-io/mc/pkg/client"
)
type listBucketResults struct {
Contents []*Item
IsTruncated bool
MaxKeys int
Name string // bucket name
Marker string
Delimiter string
Prefix string
CommonPrefixes []*Prefix
}
// Try the enumerate 5 times, since Amazon likes to close
// https connections a lot, and Go sucks at dealing with it:
// https://code.google.com/p/go/issues/detail?id=3514
func (c *s3Client) retryRequest(urlReq string) (listBucketResults, error) {
func (c *Client) retryRequest(urlReq string) (listBucketResults, error) {
const maxTries = 5
bres := listBucketResults{}
for try := 1; try <= maxTries; try++ {
@@ -54,7 +64,7 @@ func (c *s3Client) retryRequest(urlReq string) (listBucketResults, error) {
}
// get items out of content and provide marker for future request
func (c *s3Client) getItems(s, m string, contents []*client.Item) (items []*client.Item, marker string, err error) {
func (c *Client) getItems(s, m string, contents []*Item) (items []*Item, marker string, err error) {
for _, it := range contents {
if it.Key == m && it.Key != s {
// Skip first dup on pages 2 and higher.
@@ -74,7 +84,7 @@ func (c *s3Client) getItems(s, m string, contents []*client.Item) (items []*clie
// provided bucket. Keys before startAt will be skipped. (This is the S3
// 'marker' value). If the length of the returned items is equal to
// maxKeys, there is no indication whether or not the returned list is truncated.
func (c *s3Client) queryObjects(bucket string, startAt, prefix, delimiter string, maxKeys int) (items []*client.Item, prefixes []*client.Prefix, err error) {
func (c *Client) queryObjects(bucket string, startAt, prefix, delimiter string, maxKeys int) (items []*Item, prefixes []*Prefix, err error) {
var urlReq string
var buffer bytes.Buffer
+27 -20
View File
@@ -47,21 +47,27 @@ import (
"net/url"
"regexp"
"strings"
"time"
"encoding/xml"
"github.com/minio-io/mc/pkg/client"
)
type listBucketResults struct {
Contents []*client.Item
IsTruncated bool
MaxKeys int
Name string // bucket name
Marker string
Delimiter string
Prefix string
CommonPrefixes []*client.Prefix
// Bucket - carries s3 bucket reply header
type Bucket struct {
Name string
CreationDate time.Time // 2006-02-03T16:45:09.000Z
}
// Item - object item list
type Item struct {
Key string
LastModified time.Time
Size int64
}
// Prefix - common prefix
type Prefix struct {
Prefix string
}
// Meta holds Amazon S3 client credentials and flags.
@@ -85,7 +91,8 @@ type TLSConfig struct {
KeyPEMBlock []byte
}
type s3Client struct {
// Client -
type Client struct {
*Meta
// Supports URL in following formats
@@ -94,13 +101,13 @@ type s3Client struct {
*url.URL
}
// GetNewClient returns an initialized s3Client structure.
func GetNewClient(auth *Auth, urlStr string, transport http.RoundTripper) client.Client {
// GetNewClient returns an initialized Client structure.
func GetNewClient(auth *Auth, urlStr string, transport http.RoundTripper) *Client {
u, err := url.Parse(urlStr)
if err != nil {
return nil
}
s3c := &s3Client{
s3c := &Client{
&Meta{
Auth: auth,
Transport: GetNewTraceTransport(s3Verify{}, transport),
@@ -112,7 +119,7 @@ func GetNewClient(auth *Auth, urlStr string, transport http.RoundTripper) client
// bucketURL constructs a URL (with a trailing slash) for a given
// bucket. URL is appropriately encoded based on the host's object
// storage implementation.
func (c *s3Client) bucketURL(bucket string) string {
func (c *Client) bucketURL(bucket string) string {
var url string
// TODO: Bucket names can contain ".". This second check should be removed.
// when minio server supports buckets with "."
@@ -133,7 +140,7 @@ func (c *s3Client) bucketURL(bucket string) string {
}
// keyURL constructs a URL using bucket and object key
func (c *s3Client) keyURL(bucket, key string) string {
func (c *Client) keyURL(bucket, key string) string {
url := c.bucketURL(bucket)
if strings.Contains(c.Host, "localhost") || strings.Contains(c.Host, "127.0.0.1") {
return url + "/" + key
@@ -152,14 +159,14 @@ func newReq(url string) *http.Request {
// caller handle errors gracefully.
panic(fmt.Sprintf("s3 client; invalid URL: %v", err))
}
req.Header.Set("User-Agent", "Minio s3Client")
req.Header.Set("User-Agent", "Minio Client")
return req
}
func listAllMyBuckets(r io.Reader) ([]*client.Bucket, error) {
func listAllMyBuckets(r io.Reader) ([]*Bucket, error) {
type allMyBuckets struct {
Buckets struct {
Bucket []*client.Bucket
Bucket []*Bucket
}
}
var res allMyBuckets
@@ -43,8 +43,6 @@ import (
"strings"
"testing"
"time"
"github.com/minio-io/mc/pkg/client"
)
// Date format
@@ -52,7 +50,7 @@ const (
iso8601Format = "2006-01-02T15:04:05.000Z"
)
var tc *s3Client
var tc *Client
func TestParseBuckets(t *testing.T) {
res := "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Owner><ID>ownerIDField</ID><DisplayName>bobDisplayName</DisplayName></Owner><Buckets><Bucket><Name>bucketOne</Name><CreationDate>2006-06-21T07:04:31.000Z</CreationDate></Bucket><Bucket><Name>bucketTwo</Name><CreationDate>2006-06-21T07:04:32.000Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>"
@@ -66,11 +64,11 @@ func TestParseBuckets(t *testing.T) {
t1, _ := time.Parse(iso8601Format, "2006-06-21T07:04:31.000Z")
t2, _ := time.Parse(iso8601Format, "2006-06-21T07:04:32.000Z")
want := []*client.Bucket{
want := []*Bucket{
{Name: "bucketOne", CreationDate: t1},
{Name: "bucketTwo", CreationDate: t2},
}
dump := func(v []*client.Bucket) {
dump := func(v []*Bucket) {
for i, b := range v {
t.Logf("Bucket #%d: %#v", i, b)
}
+5 -5
View File
@@ -58,7 +58,7 @@ import (
/// Object API operations
// Put - upload new object to bucket
func (c *s3Client) Put(bucket, key, md5HexString string, size int64, contents io.Reader) error {
func (c *Client) Put(bucket, key, md5HexString string, size int64, contents io.Reader) error {
req := newReq(c.keyURL(bucket, key))
req.Method = "PUT"
req.ContentLength = size
@@ -83,8 +83,8 @@ func (c *s3Client) Put(bucket, key, md5HexString string, size int64, contents io
return nil
}
// Stat - returns 0, "", os.ErrNotExist if not on S3
func (c *s3Client) StatObject(bucket, key string) (size int64, date time.Time, reterr error) {
// StatObject - returns 0, "", os.ErrNotExist if not available
func (c *Client) StatObject(bucket, key string) (size int64, date time.Time, reterr error) {
if bucket == "" || key == "" {
return 0, date, iodine.New(os.ErrNotExist, nil)
}
@@ -120,7 +120,7 @@ func (c *s3Client) StatObject(bucket, key string) (size int64, date time.Time, r
}
// Get - download a requested object from a given bucket
func (c *s3Client) Get(bucket, key string) (body io.ReadCloser, size int64, md5 string, err error) {
func (c *Client) Get(bucket, key string) (body io.ReadCloser, size int64, md5 string, err error) {
req := newReq(c.keyURL(bucket, key))
c.signRequest(req, c.Host)
res, err := c.Transport.RoundTrip(req)
@@ -137,7 +137,7 @@ func (c *s3Client) Get(bucket, key string) (body io.ReadCloser, size int64, md5
// GetPartial fetches part of the s3 key object in bucket.
// If length is negative, the rest of the object is returned.
func (c *s3Client) GetPartial(bucket, key string, offset, length int64) (body io.ReadCloser, size int64, md5 string, err error) {
func (c *Client) GetPartial(bucket, key string, offset, length int64) (body io.ReadCloser, size int64, md5 string, err error) {
if offset < 0 {
return nil, 0, "", iodine.New(errors.New("invalid negative offset"), nil)
}