Implement mc share upload and mc share download

This commit is contained in:
Krishna Srinivas
2015-10-08 13:20:29 -07:00
parent 7c251c314b
commit 7ec74a33ce
9 changed files with 348 additions and 62 deletions
+2 -1
View File
@@ -36,7 +36,8 @@ type Client interface {
SetBucketACL(acl string) *probe.Error
// Object operations
Share(expires time.Duration) (string, *probe.Error)
ShareDownload(expires time.Duration) (string, *probe.Error)
ShareUpload(bool, time.Duration, string) (map[string]string, *probe.Error)
GetObject(offset, length int64) (body io.ReadCloser, size int64, err *probe.Error)
PutObject(size int64, data io.Reader) *probe.Error
+6 -2
View File
@@ -145,8 +145,12 @@ func (f *fsClient) get() (io.ReadCloser, int64, *probe.Error) {
return body, content.Size, nil
}
func (f *fsClient) Share(expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(client.APINotImplemented{API: "Share", APIType: "filesystem"})
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(client.APINotImplemented{API: "ShareDownload", APIType: "filesystem"})
}
func (f *fsClient) ShareUpload(recursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
return nil, probe.NewError(client.APINotImplemented{API: "ShareUpload", APIType: "filesystem"})
}
// GetObject download an full or part object from bucket
+5 -1
View File
@@ -77,7 +77,7 @@ func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe
}
// Share - get a usable get object url to share
func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
if err != nil {
@@ -86,6 +86,10 @@ func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
return presignedURL, nil
}
func (f *s3Client) ShareUpload(recursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
return nil, probe.NewError(client.APINotImplemented{API: "Share", APIType: "filesystem"})
}
// PutObject - put object
func (c *s3Client) PutObject(size int64, data io.Reader) *probe.Error {
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
+18 -1
View File
@@ -77,7 +77,7 @@ func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe
}
// Share - get a usable get object url to share
func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
if err != nil {
@@ -86,6 +86,23 @@ func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
return presignedURL, nil
}
func (c *s3Client) ShareUpload(recursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
p := minio.NewPostPolicy()
p.SetExpires(time.Now().UTC().Add(expires))
if len(contentType) > 0 {
p.SetContentType(contentType)
}
p.SetBucket(bucket)
if recursive {
p.SetKeyStartsWith(object)
} else {
p.SetKey(object)
}
m, err := c.api.PresignedPostPolicy(p)
return m, probe.NewError(err)
}
// PutObject - put object
func (c *s3Client) PutObject(size int64, data io.Reader) *probe.Error {
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
+180 -52
View File
@@ -41,7 +41,8 @@ var shareCmd = cli.Command{
mc {{.Name}} - {{.Usage}}
USAGE:
mc {{.Name}} TARGET [DURATION]
mc {{.Name}} download TARGET [DURATION]
mc {{.Name}} upload TARGET [DURATION] [Content-Type]
DURATION = NN[h|m|s] [DEFAULT=168h]
@@ -65,28 +66,70 @@ EXAMPLES:
}
// ShareMessage is container for share command on success and failure messages
type ShareMessage struct {
type ShareMessageV1 struct {
Expiry time.Duration `json:"expiry"`
URL string `json:"url"`
Key string `json:"keyName"`
}
type ShareMessageV2 ShareMessageV1
type ShareMessageV3 struct {
Expiry time.Duration `json:"expiry"`
DownloadUrl string `json:"downloadUrl,omitempty"`
UploadInfo map[string]string `json:"uploadInfo,omitempty"`
Key string `json:"keyName"`
}
type ShareMessage ShareMessageV3
// String - regular colorized message
func (s ShareMessage) String() string {
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), s.URL, s.Key))
if len(s.DownloadUrl) > 0 {
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n DownloadUrl: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), s.DownloadUrl, s.Key))
} else {
var key string
URL := client.NewURL(s.Key)
postUrl := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator) + s.UploadInfo["bucket"] + " "
curlCommand := "curl " + postUrl
for k, v := range s.UploadInfo {
if k == "key" {
key = v
continue
}
curlCommand = curlCommand + fmt.Sprintf("-F %s=%s ", k, v)
}
curlCommand = curlCommand + fmt.Sprintf("-F key=%s ", key) + "-F file=@<LOCALFILEPATH> "
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n curl-command: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), curlCommand, s.Key))
}
}
// JSON json message for share command
func (s ShareMessage) JSON() string {
shareMessageBytes, err := json.Marshal(struct {
Expiry humanizedTime `json:"expiry"`
URL string `json:"url"`
Key string `json:"keyName"`
}{
Expiry: timeDurationToHumanizedTime(s.Expiry),
URL: s.URL,
Key: s.Key,
})
var shareMessageBytes []byte
var err error
if len(s.DownloadUrl) > 0 {
shareMessageBytes, err = json.Marshal(struct {
Expiry humanizedTime `json:"expiry"`
DownloadUrl string `json:"downloadUrl"`
Key string `json:"keyName"`
}{
Expiry: timeDurationToHumanizedTime(s.Expiry),
DownloadUrl: s.DownloadUrl,
Key: s.Key,
})
} else {
shareMessageBytes, err = json.Marshal(struct {
Expiry humanizedTime `json:"expiry"`
UploadInfo map[string]string `json:"uploadInfo"`
Key string `json:"keyName"`
}{
Expiry: timeDurationToHumanizedTime(s.Expiry),
UploadInfo: s.UploadInfo,
Key: s.Key,
})
}
fatalIf(probe.NewError(err), "Failed to marshal into JSON.")
// json encoding escapes ampersand into its unicode character which is not usable directly for share
@@ -98,13 +141,11 @@ func (s ShareMessage) JSON() string {
// migrateSharedURLs migrate to newest version sequentially
func migrateSharedURLs() {
migrateSharedURLsV1ToV2()
migrateSharedURLsV2ToV3()
}
func checkShareSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || ctx.Args().First() == "help" || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
}
if len(ctx.Args()) > 2 {
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
}
if ctx.Args().Get(0) == "list" {
@@ -142,7 +183,6 @@ func setSharePalette(style string) {
// mainShare - is a handler for mc share command
func mainShare(ctx *cli.Context) {
checkShareSyntax(ctx)
if !isSharedURLsDataDirExists() {
shareDir, err := getSharedURLsDataDir()
fatalIf(err.Trace(), "Unable to get shared URL data directory")
@@ -168,26 +208,46 @@ func mainShare(ctx *cli.Context) {
return
}
/// get first and last arguments
url := args.Get(0) // url to be shared
// default expiration is 7days
expires := time.Duration(604800) * time.Second
if len(args) == 2 {
if args.Get(0) == "upload" {
var expires time.Duration
var err error
expires, err = time.ParseDuration(args.Get(1))
fatalIf(probe.NewError(err), "Unable to parse time argument.")
url := args.Get(1)
if len(args.Get(2)) == 0 {
expires = time.Duration(604800) * time.Second
} else {
expires, err = time.ParseDuration(args.Get(2))
if err != nil {
fatalIf(probe.NewError(err), "Unable to parse time argument.")
}
}
contentType := args.Get(3)
targetURL := getAliasURL(url, config.Aliases)
e := doShareUploadURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires, contentType)
fatalIf(e.Trace(targetURL), "Unable to generate URL for sharing.")
return
} else if args.Get(0) == "download" {
/// get first and last arguments
url := args.Get(1) // url to be shared
// default expiration is 7days
expires := time.Duration(604800) * time.Second
if len(args) == 3 {
var err error
expires, err = time.ParseDuration(args.Get(2))
fatalIf(probe.NewError(err), "Unable to parse time argument.")
}
targetURL := getAliasURL(url, config.Aliases)
// if recursive strip off the "..."
err := doShareDownloadURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires)
fatalIf(err.Trace(targetURL), "Unable to generate URL for sharing.")
return
}
targetURL := getAliasURL(url, config.Aliases)
// if recursive strip off the "..."
err := doShareURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires)
fatalIf(err.Trace(targetURL), "Unable to generate URL for sharing.")
}
// doShareList list shared url's
func doShareList() *probe.Error {
sURLs, err := loadSharedURLsV2()
sURLs, err := loadSharedURLsV3()
if err != nil {
return err.Trace()
}
@@ -198,42 +258,105 @@ func doShareList() *probe.Error {
}
expiry := data.Message.Expiry - time.Since(data.Date)
if !globalJSONFlag {
var kind string
if len(data.Message.DownloadUrl) > 0 {
kind = "Download"
} else {
kind = "Upload"
}
msg := console.Colorize("Share", "Name: ")
msg += console.Colorize("URL", data.Message.Key+"\n")
msg += console.Colorize("URL", data.Message.Key+" ("+kind+")\n")
msg += console.Colorize("Share", "Expiry: ")
msg += console.Colorize("Expires", timeDurationToHumanizedTime(expiry))
msg += "\n"
console.Println(msg)
continue
}
shareListBytes, err := json.Marshal(struct {
Expiry humanizedTime `json:"expiry"`
URL string `json:"url"`
Key string `json:"keyName"`
}{
Expiry: timeDurationToHumanizedTime(expiry),
URL: data.Message.URL,
Key: data.Message.Key,
})
var shareMessageBytes []byte
var err error
s := data.Message
if len(s.DownloadUrl) > 0 {
shareMessageBytes, err = json.Marshal(struct {
Expiry humanizedTime `json:"expiry"`
DownloadUrl string `json:"downloadUrl"`
Key string `json:"keyName"`
}{
Expiry: timeDurationToHumanizedTime(s.Expiry),
DownloadUrl: s.DownloadUrl,
Key: s.Key,
})
} else {
shareMessageBytes, err = json.Marshal(struct {
Expiry humanizedTime `json:"expiry"`
UploadInfo map[string]string `json:"uploadInfo"`
Key string `json:"keyName"`
}{
Expiry: timeDurationToHumanizedTime(s.Expiry),
UploadInfo: s.UploadInfo,
Key: s.Key,
})
}
if err != nil {
return probe.NewError(err)
}
console.Println(string(shareListBytes))
console.Println(string(shareMessageBytes))
}
if err := saveSharedURLsV2(sURLs); err != nil {
if err := saveSharedURLsV3(sURLs); err != nil {
return err.Trace()
}
return nil
}
// doShareURL share files from target
func doShareURL(targetURL string, recursive bool, expires time.Duration) *probe.Error {
func doShareUploadURL(targetURL string, recursive bool, expires time.Duration, contentType string) *probe.Error {
shareDate := time.Now().UTC()
sURLs, err := loadSharedURLsV2()
sURLs, err := loadSharedURLsV3()
if err != nil {
return err.Trace()
}
clnt, err := url2Client(targetURL)
if err != nil {
return err.Trace()
}
m, err := clnt.ShareUpload(recursive, expires, contentType)
if err != nil {
return err.Trace()
}
Key := targetURL
if recursive {
Key = Key + recursiveSeparator
m["key"] = "<KEY>"
}
shareMessage := ShareMessage{
Expiry: expires,
UploadInfo: m,
Key: Key,
}
shareMessageV3 := ShareMessageV3{
Expiry: expires,
UploadInfo: m,
Key: Key,
}
sURLs.URLs = append(sURLs.URLs, struct {
Date time.Time
Message ShareMessageV3
}{
Date: shareDate,
Message: shareMessageV3,
})
Prints("%s\n", shareMessage)
saveSharedURLsV3(sURLs)
return nil
}
// doShareURL share files from target
func doShareDownloadURL(targetURL string, recursive bool, expires time.Duration) *probe.Error {
shareDate := time.Now().UTC()
sURLs, err := loadSharedURLsV3()
if err != nil {
return err.Trace()
}
var clnt client.Client
clnt, err = target2Client(targetURL)
if err != nil {
@@ -255,25 +378,30 @@ func doShareURL(targetURL string, recursive bool, expires time.Duration) *probe.
return err.Trace()
}
var sharedURL string
sharedURL, err = newClnt.Share(expires)
sharedURL, err = newClnt.ShareDownload(expires)
if err != nil {
return err.Trace()
}
shareMessage := ShareMessage{
Expiry: expires,
URL: sharedURL,
Key: newClnt.URL().String(),
Expiry: expires,
DownloadUrl: sharedURL,
Key: newClnt.URL().String(),
}
shareMessageV3 := ShareMessageV3{
Expiry: expires,
DownloadUrl: sharedURL,
Key: newClnt.URL().String(),
}
sURLs.URLs = append(sURLs.URLs, struct {
Date time.Time
Message ShareMessage
Message ShareMessageV3
}{
Date: shareDate,
Message: shareMessage,
Message: shareMessageV3,
})
Prints("%s\n", shareMessage)
}
saveSharedURLsV2(sURLs)
saveSharedURLsV3(sURLs)
return nil
}
+2 -2
View File
@@ -28,7 +28,7 @@ type sharedURLsV1 struct {
Version string
URLs map[string]struct {
Date time.Time
Message ShareMessage
Message ShareMessageV1
}
}
@@ -58,7 +58,7 @@ func newSharedURLsV1() *sharedURLsV1 {
Version: "1.0.0",
URLs: make(map[string]struct {
Date time.Time
Message ShareMessage
Message ShareMessageV1
}),
}
return s
+2 -2
View File
@@ -28,7 +28,7 @@ type sharedURLsV2 struct {
Version string
URLs []struct {
Date time.Time
Message ShareMessage
Message ShareMessageV2
}
}
@@ -68,7 +68,7 @@ func saveSharedURLsV2(s *sharedURLsV2) *probe.Error {
func newSharedURLsV2() *sharedURLsV2 {
var urls []struct {
Date time.Time
Message ShareMessage
Message ShareMessageV2
}
s := &sharedURLsV2{
Version: "1.1.0",
+78
View File
@@ -0,0 +1,78 @@
/*
* Minio Client (C) 2014, 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 (
"os"
"time"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
type sharedURLsV3 struct {
Version string
URLs []struct {
Date time.Time
Message ShareMessageV3
}
}
func loadSharedURLsV3() (*sharedURLsV3, *probe.Error) {
sharedURLsDataFile, err := getSharedURLsDataFile()
if err != nil {
return nil, err.Trace()
}
if _, err := os.Stat(sharedURLsDataFile); err != nil {
return nil, probe.NewError(err)
}
qs, err := quick.New(newSharedURLsV3())
if err != nil {
return nil, err.Trace()
}
err = qs.Load(sharedURLsDataFile)
if err != nil {
return nil, err.Trace(sharedURLsDataFile)
}
s := qs.Data().(*sharedURLsV3)
return s, nil
}
func saveSharedURLsV3(s *sharedURLsV3) *probe.Error {
qs, err := quick.New(s)
if err != nil {
return err.Trace()
}
sharedURLsDataFile, err := getSharedURLsDataFile()
if err != nil {
return err.Trace()
}
return qs.Save(sharedURLsDataFile).Trace(sharedURLsDataFile)
}
func newSharedURLsV3() *sharedURLsV3 {
var urls []struct {
Date time.Time
Message ShareMessageV3
}
s := &sharedURLsV3{
Version: "3",
URLs: urls,
}
return s
}
+55 -1
View File
@@ -20,8 +20,10 @@ import (
"encoding/json"
"os"
"path/filepath"
"time"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
func newSharedURLs() *sharedURLsV2 {
@@ -48,7 +50,18 @@ func migrateSharedURLsV1ToV2() {
sURLsV2 = newSharedURLsV2()
for key, value := range sURLsV1.URLs {
value.Message.Key = key
sURLsV2.URLs = append(sURLsV2.URLs, value)
entry := struct {
Date time.Time
Message ShareMessageV2
}{
Date: value.Date,
Message: ShareMessageV2{
Expiry: value.Message.Expiry,
URL: value.Message.URL,
Key: value.Message.Key,
},
}
sURLsV2.URLs = append(sURLsV2.URLs, entry)
}
err = saveSharedURLsV2(sURLsV2)
fatalIf(err.Trace(), "Unable to save new shared url version ‘1.1.0’.")
@@ -58,6 +71,47 @@ func migrateSharedURLsV1ToV2() {
}
}
func migrateSharedURLsV2ToV3() {
if !isSharedURLsDataFileExists() {
return
}
conffile, err := getSharedURLsDataFile()
if err != nil {
return
}
v3, err := quick.CheckVersion(conffile, "3")
if err != nil {
fatalIf(err.Trace(), "Unable to check version on share list file")
}
if v3 {
return
}
// try to load V2 if possible
sURLsV2, err := loadSharedURLsV2()
fatalIf(err.Trace(), "Unable to load shared url version ‘1.1.0’.")
if sURLsV2.Version != "1.1.0" {
fatalIf(errDummy().Trace(), "Invalid version loaded ‘"+sURLsV2.Version+"’.")
}
sURLsV3 := newSharedURLsV3()
for _, value := range sURLsV2.URLs {
entry := struct {
Date time.Time
Message ShareMessageV3
}{
Date: value.Date,
Message: ShareMessageV3{
Expiry: value.Message.Expiry,
DownloadUrl: value.Message.URL,
Key: value.Message.Key,
},
}
sURLsV3.URLs = append(sURLsV3.URLs, entry)
}
err = saveSharedURLsV3(sURLsV3)
fatalIf(err.Trace(), "Unable to save new shared url version ‘1.2.0’.")
}
func getSharedURLsDataDir() (string, *probe.Error) {
configDir, err := getMcConfigDir()
if err != nil {