Merge pull request #116 from harshavardhana/pr_out_add_recursive_directory_upload_and_bucket_download_support_for_mc_cp_with_r_deprecate_mc_sync

This commit is contained in:
Harshavardhana
2015-03-13 03:01:02 -07:00
6 changed files with 262 additions and 194 deletions
+92 -59
View File
@@ -28,64 +28,74 @@ import (
// Different modes of cp operation
const (
first = iota // <Path> <S3Path> or <Path> <S3Bucket>
second // <S3Path> <Path> or <S3Path> .
third // <S3Path> <S3Path> or <S3Path> <S3Bucket>
fourth // <S3Bucket> <S3Bucket> - TODO
first = iota // <Object> <S3Object> or <Object> <S3Bucket>
second // <S3Object> <Object> or <S3Object> .
third // <S3Object> <S3Object> or <S3Object> <S3Bucket>
fourth // <Dir> <S3Bucket> or <S3Bucket> <Dir> or <Dir> <S3Uri>
invalid
)
func getMode(options *cmdOptions) int {
switch true {
// <Path> <S3Path> or <Path> <S3Bucket>
case options.source.bucket == "" && options.destination.bucket != "":
return first
// <S3Path> <Path> or <S3Path> .
case options.source.bucket != "" && options.destination.bucket == "":
return second
// <S3Path> <S3Path> or <S3Path> <S3Bucket>
case options.source.bucket != "" && options.destination.bucket != "" && options.source.key != "":
return third
// Get current mode of operation from available arguments and options
func getMode(recursive bool, args *cmdArgs) int {
switch recursive {
case false:
switch true {
// <Object> <S3Object> or <Object> <S3Bucket>
case args.source.bucket == "" && args.destination.bucket != "":
return first
// <S3Object> <Object> or <S3Object> .
case args.source.bucket != "" && args.source.key != "" && args.destination.bucket == "":
return second
// <S3Object> <S3Object> or <S3Object> <S3Bucket>
case args.source.bucket != "" && args.destination.bucket != "" && args.source.key != "":
return third
}
case true:
switch true {
// <Dir> <S3Bucket> or <S3Bucket> <Dir> or <Dir> <S3Uri>
case (args.source.bucket != "" && args.destination.key != "") || args.source.key != "":
return fourth
}
}
return invalid
}
// First mode <Path> <S3Path> or <Path> <S3Bucket>
func firstMode(s3c *s3.Client, options *cmdOptions) error {
if options.source.key == "" {
return fmt.Errorf("invalid")
// First mode <Object> <S3Object> or <Object> <S3Bucket>
func firstMode(s3c *s3.Client, args *cmdArgs) error {
if args.source.key == "" {
return fmt.Errorf("invalid args")
}
st, err := os.Stat(options.source.key)
st, err := os.Stat(args.source.key)
if os.IsNotExist(err) {
return err
}
if st.IsDir() {
fmt.Errorf("Is a directory")
return fmt.Errorf("omitting directory '%s'", st.Name())
}
size := st.Size()
source, err := os.Open(options.source.key)
source, err := os.Open(args.source.key)
defer source.Close()
if err != nil {
return err
}
// s3://<bucket> is specified without key
if options.destination.key == "" {
options.destination.key = options.source.key
if args.destination.key == "" {
args.destination.key = args.source.key
}
err = s3c.Put(options.destination.bucket, options.destination.key, size, source)
err = s3c.Put(args.destination.bucket, args.destination.key, size, source)
if err != nil {
return err
}
msg := fmt.Sprintf("%s uploaded -- to bucket:(s3://%s/%s)", options.source.key,
options.destination.bucket, options.destination.key)
msg := fmt.Sprintf("%s uploaded -- to bucket:(s3://%s/%s)", args.source.key,
args.destination.bucket, args.destination.key)
info(msg)
return nil
}
// Second mode <S3Path> <Path> or <S3Path> .
func secondMode(s3c *s3.Client, options *cmdOptions) error {
// Second mode <S3Object> <Object> or <S3Object> .
func secondMode(s3c *s3.Client, args *cmdArgs) error {
var objectReader io.ReadCloser
var objectSize, downloadedSize int64
var destination *os.File
@@ -93,32 +103,32 @@ func secondMode(s3c *s3.Client, options *cmdOptions) error {
var st os.FileInfo
// Send HEAD request to validate if file exists.
objectSize, _, err = s3c.Stat(options.source.bucket, options.source.key)
objectSize, _, err = s3c.Stat(args.source.bucket, args.source.key)
if err != nil {
return err
}
if options.destination.key == "." {
options.destination.key = options.source.key
if args.destination.key == "." {
args.destination.key = args.source.key
}
var bar *pb.ProgressBar
if !options.quiet {
if !args.quiet {
// get progress bar
bar = startBar(objectSize)
}
// Check if the object already exists
st, err = os.Stat(options.destination.key)
st, err = os.Stat(args.destination.key)
switch os.IsNotExist(err) {
case true:
// Create if it doesn't exist
destination, err = os.Create(options.destination.key)
destination, err = os.Create(args.destination.key)
defer destination.Close()
if err != nil {
return err
}
objectReader, _, err = s3c.Get(options.source.bucket, options.source.key)
objectReader, _, err = s3c.Get(args.source.bucket, args.source.key)
if err != nil {
return err
}
@@ -126,10 +136,10 @@ func secondMode(s3c *s3.Client, options *cmdOptions) error {
downloadedSize = st.Size()
// Verify if file is already downloaded
if downloadedSize == objectSize {
return fmt.Errorf("%s object has been already downloaded", options.destination.key)
return fmt.Errorf("%s object has been already downloaded", args.destination.key)
}
destination, err = os.OpenFile(options.destination.key, os.O_RDWR, 0600)
destination, err = os.OpenFile(args.destination.key, os.O_RDWR, 0600)
defer destination.Close()
if err != nil {
return err
@@ -141,19 +151,19 @@ func secondMode(s3c *s3.Client, options *cmdOptions) error {
}
remainingSize := objectSize - downloadedSize
objectReader, objectSize, err = s3c.GetPartial(options.source.bucket,
options.source.key, downloadedSize, remainingSize)
objectReader, objectSize, err = s3c.GetPartial(args.source.bucket,
args.source.key, downloadedSize, remainingSize)
if err != nil {
return err
}
if !options.quiet {
if !args.quiet {
bar.Set(int(downloadedSize))
}
}
writer := io.Writer(destination)
if !options.quiet {
if !args.quiet {
// Start the bar now
bar.Start()
// create multi writer to feed data
@@ -170,31 +180,31 @@ func secondMode(s3c *s3.Client, options *cmdOptions) error {
return nil
}
// <S3Path> <S3Path> or <S3Path> <S3Bucket>
func thirdMode(s3c *s3.Client, options *cmdOptions) error {
// <S3Object> <S3Object> or <S3Object> <S3Bucket>
func thirdMode(s3c *s3.Client, args *cmdArgs) error {
var objectReader io.ReadCloser
var objectSize int64
var err error
// Send HEAD request to validate if file exists.
objectSize, _, err = s3c.Stat(options.source.bucket, options.source.key)
objectSize, _, err = s3c.Stat(args.source.bucket, args.source.key)
if err != nil {
return err
}
if options.destination.key == "" {
options.destination.key = options.source.key
if args.destination.key == "" {
args.destination.key = args.source.key
}
// Check if the object already exists
_, _, err = s3c.Stat(options.destination.bucket, options.destination.key)
_, _, err = s3c.Stat(args.destination.bucket, args.destination.key)
switch os.IsNotExist(err) {
case true:
objectReader, _, err = s3c.Get(options.source.bucket, options.source.key)
objectReader, _, err = s3c.Get(args.source.bucket, args.source.key)
if err != nil {
return err
}
err = s3c.Put(options.destination.bucket, options.destination.key, objectSize, objectReader)
err = s3c.Put(args.destination.bucket, args.destination.key, objectSize, objectReader)
if err != nil {
return err
}
@@ -202,12 +212,30 @@ func thirdMode(s3c *s3.Client, options *cmdOptions) error {
return fmt.Errorf("Ranges not supported")
}
msg := fmt.Sprintf("s3://%s/%s uploaded -- to bucket:(s3://%s/%s)", options.source.bucket, options.source.key,
options.destination.bucket, options.destination.key)
msg := fmt.Sprintf("s3://%s/%s uploaded -- to bucket:(s3://%s/%s)", args.source.bucket, args.source.key,
args.destination.bucket, args.destination.key)
info(msg)
return nil
}
func fourthMode(s3c *s3.Client, args *cmdArgs) error {
if args.source.bucket == "" {
_, err := os.Stat(args.source.key)
if os.IsNotExist(err) {
return err
}
if args.destination.bucket == "" {
args.destination.bucket = args.source.key
}
} else {
_, err := os.Stat(args.destination.key)
if os.IsNotExist(err) {
os.MkdirAll(args.destination.key, 0755)
}
}
return doRecursiveCp(s3c, args)
}
func doFsCopy(c *cli.Context) {
s3c, err := getNewClient(c)
if err != nil {
@@ -218,29 +246,34 @@ func doFsCopy(c *cli.Context) {
fatal("Invalid number of args")
}
var cmdoptions *cmdOptions
cmdoptions, err = parseOptions(c)
var cmdargs *cmdArgs
cmdargs, err = parseArgs(c)
if err != nil {
fatal(err.Error())
}
switch getMode(cmdoptions) {
switch getMode(c.Bool("recursive"), cmdargs) {
case first:
err := firstMode(s3c, cmdoptions)
err := firstMode(s3c, cmdargs)
if err != nil {
fatal(err.Error())
}
case second:
err := secondMode(s3c, cmdoptions)
err := secondMode(s3c, cmdargs)
if err != nil {
fatal(err.Error())
}
case third:
err := thirdMode(s3c, cmdoptions)
err := thirdMode(s3c, cmdargs)
if err != nil {
fatal(err.Error())
}
case fourth:
err := fourthMode(s3c, cmdargs)
if err != nil {
fatal(err.Error())
}
default:
fatal("Invalid request")
fatal("invalid args")
}
}
+8 -8
View File
@@ -54,34 +54,34 @@ func doFsList(c *cli.Context) {
if err != nil {
fatal(err.Error())
}
cmdoptions, err := parseOptions(c)
args, err := parseArgs(c)
if err != nil {
fatal(err.Error())
}
switch true {
case cmdoptions.source.bucket == "": // List all buckets
case args.source.bucket == "": // List all buckets
buckets, err := s3c.ListBuckets()
if err != nil {
fatal(err.Error())
}
printBuckets(buckets)
case cmdoptions.source.key == "": // List objects in a bucket
items, _, err = s3c.ListObjects(cmdoptions.source.bucket, "", "", "", s3.MaxKeys)
case args.source.key == "": // List objects in a bucket
items, _, err = s3c.ListObjects(args.source.bucket, "", "", "", s3.MaxKeys)
if err != nil {
fatal(err.Error())
}
printObjects(items)
case cmdoptions.source.key != "": // List objects matching the key prefix
case args.source.key != "": // List objects matching the key prefix
var date time.Time
var size int64
size, date, err = s3c.Stat(cmdoptions.source.bucket, cmdoptions.source.key)
size, date, err = s3c.Stat(args.source.bucket, args.source.key)
switch err {
case nil: // List a single object. Exact key
printObject(date, size, cmdoptions.source.key)
printObject(date, size, args.source.key)
case os.ErrNotExist:
// List all objects matching the key prefix
items, _, err = s3c.ListObjects(cmdoptions.source.bucket, "", cmdoptions.source.key, "", s3.MaxKeys)
items, _, err = s3c.ListObjects(args.source.bucket, "", args.source.key, "", s3.MaxKeys)
if err != nil {
fatal(err.Error())
}
+7 -9
View File
@@ -25,6 +25,12 @@ var cp = cli.Command{
Usage: "",
Description: `Copies a local file or Object to another location locally or in S3.`,
Action: doFsCopy,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "recursive cp",
},
},
}
var ls = cli.Command{
@@ -41,13 +47,6 @@ var mb = cli.Command{
Action: doFsMb,
}
var sync = cli.Command{
Name: "sync",
Usage: "",
Description: "Syncs directories and S3 prefixes",
Action: doFsSync,
}
var configure = cli.Command{
Name: "config",
Usage: "Generate configuration \"" + getMcConfigFilename() + "\" file.",
@@ -85,7 +84,7 @@ type object struct {
key string
}
type cmdOptions struct {
type cmdArgs struct {
quiet bool
source object
destination object
@@ -95,7 +94,6 @@ var options = []cli.Command{
cp,
ls,
mb,
sync,
configure,
}
+139
View File
@@ -0,0 +1,139 @@
/*
* Mini 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 main
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/minio-io/mc/pkg/s3"
)
type walk struct {
s3 *s3.Client
args *cmdArgs
}
func (w *walk) putWalk(p string, i os.FileInfo, err error) error {
if i.IsDir() {
return nil
}
if !i.Mode().IsRegular() {
return nil
}
parts := strings.SplitN(p, "/", 2)
bucketname := w.args.destination.bucket
key := parts[1]
bodyFile, err := os.Open(p)
defer bodyFile.Close()
err = w.s3.Put(bucketname, key, i.Size(), bodyFile)
if err != nil {
return err
}
msg := fmt.Sprintf("%s uploaded -- to bucket:s3://%s/%s", key, bucketname, key)
info(msg)
return nil
}
func isValidBucketName(p string) error {
if path.IsAbs(p) {
return fmt.Errorf("directory bucketname cannot be absolute")
}
if strings.HasPrefix(p, "..") {
return fmt.Errorf("Relative directory references not supported")
}
if !s3.IsValidBucket(p) {
return errInvalidbucket
}
return nil
}
func isBucketExists(name string, v []*s3.Bucket) bool {
for _, b := range v {
if name == b.Name {
return true
}
}
return false
}
func doRecursiveCp(s3c *s3.Client, args *cmdArgs) error {
var err error
var st os.FileInfo
var buckets []*s3.Bucket
p := &walk{s3c, args}
switch true {
case args.source.bucket == "":
input := path.Clean(args.source.key)
if err := isValidBucketName(input); err != nil {
return err
}
st, err = os.Stat(input)
if os.IsNotExist(err) {
return err
}
if !st.IsDir() {
return fmt.Errorf("Should be a directory")
}
buckets, err = s3c.ListBuckets()
if !isBucketExists(args.destination.bucket, buckets) {
// Create bucketname, before uploading files
err = s3c.PutBucket(args.destination.bucket)
if err != nil {
return err
}
err = filepath.Walk(input, p.putWalk)
if err != nil {
return err
}
}
case args.destination.bucket == "":
items, _, err := s3c.ListObjects(args.source.bucket, "", "", "", s3.MaxKeys)
if err != nil {
fatal(err.Error())
}
root := args.destination.key
writeObjects := func(v []*s3.Item) error {
if len(v) > 0 {
// Items are already sorted
for _, b := range v {
args.source.key = b.Key
os.MkdirAll(path.Join(root, path.Dir(b.Key)), 0755)
args.destination.key = path.Join(root, b.Key)
err := secondMode(s3c, args)
if err != nil {
return err
}
}
}
return nil
}
err = writeObjects(items)
if err != nil {
fatal(err.Error())
}
}
return nil
}
-103
View File
@@ -1,103 +0,0 @@
/*
* Mini 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 main
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/codegangsta/cli"
"github.com/minio-io/mc/pkg/s3"
)
type walk struct {
s3 *s3.Client
}
func (w *walk) putWalk(p string, i os.FileInfo, err error) error {
if i.IsDir() {
return nil
}
if !i.Mode().IsRegular() {
return nil
}
parts := strings.SplitN(p, "/", 2)
bucketname := parts[0]
key := parts[1]
bodyFile, err := os.Open(p)
defer bodyFile.Close()
err = w.s3.Put(bucketname, key, i.Size(), bodyFile)
if err != nil {
return err
}
msg := fmt.Sprintf("%s uploaded -- to bucket:%s", key, bucketname)
info(msg)
return nil
}
func isValidBucketName(p string) {
if path.IsAbs(p) {
fatal("directory bucketname cannot be absolute")
}
if strings.HasPrefix(p, "..") {
fatal("Relative directory references not supported")
}
if !s3.IsValidBucket(p) {
fatal(errInvalidbucket.Error())
}
}
func doFsSync(c *cli.Context) {
var s3c *s3.Client
var err error
s3c, err = getNewClient(c)
if err != nil {
fatal(err.Error())
}
p := &walk{s3c}
switch len(c.Args()) {
case 1:
input := path.Clean(c.Args().Get(0))
isValidBucketName(input) // exit here if invalid
fl, err := os.Stat(input)
if os.IsNotExist(err) {
fatal(err.Error())
}
if !fl.IsDir() {
fatal("Should be a directory")
}
// Create bucketname, before uploading files
err = s3c.PutBucket(input)
if err != nil {
fatal(err.Error())
}
err = filepath.Walk(input, p.putWalk)
if err != nil {
fatal(err.Error())
}
default:
fatal("Requires a directory name <Directory>")
}
}
+16 -15
View File
@@ -96,12 +96,13 @@ func parseGlobalOptions(c *cli.Context) {
}
// Parse subcommand options
func parseOptions(c *cli.Context) (cmdopts *cmdOptions, err error) {
cmdopts = new(cmdOptions)
cmdopts.quiet = c.GlobalBool("quiet")
func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
args = new(cmdArgs)
args.quiet = c.GlobalBool("quiet")
switch len(c.Args()) {
case 0:
return cmdopts, nil
return args, nil
case 1:
if strings.HasPrefix(c.Args().Get(0), "s3://") {
uri, err := url.Parse(c.Args().Get(0))
@@ -111,8 +112,8 @@ func parseOptions(c *cli.Context) (cmdopts *cmdOptions, err error) {
if uri.Scheme != "s3" {
return nil, errInvalidScheme
}
cmdopts.source.bucket = uri.Host
cmdopts.source.key = strings.TrimPrefix(uri.Path, "/")
args.source.bucket = uri.Host
args.source.key = strings.TrimPrefix(uri.Path, "/")
} else {
return nil, errInvalidScheme
}
@@ -131,8 +132,8 @@ func parseOptions(c *cli.Context) (cmdopts *cmdOptions, err error) {
}
return nil, errInvalidScheme
}
cmdopts.source.bucket = uri.Host
cmdopts.source.key = strings.TrimPrefix(uri.Path, "/")
args.source.bucket = uri.Host
args.source.key = strings.TrimPrefix(uri.Path, "/")
case uri.Scheme == "":
if uri.Host != "" {
return nil, errInvalidScheme
@@ -143,8 +144,8 @@ func parseOptions(c *cli.Context) (cmdopts *cmdOptions, err error) {
if uri.Path == "." {
return nil, errFskey
}
cmdopts.source.bucket = uri.Host
cmdopts.source.key = strings.TrimPrefix(uri.Path, "/")
args.source.bucket = uri.Host
args.source.key = strings.TrimPrefix(uri.Path, "/")
case uri.Scheme != "s3":
return nil, errInvalidScheme
}
@@ -162,18 +163,18 @@ func parseOptions(c *cli.Context) (cmdopts *cmdOptions, err error) {
}
return nil, errInvalidScheme
}
cmdopts.destination.bucket = uri.Host
cmdopts.destination.key = strings.TrimPrefix(uri.Path, "/")
args.destination.bucket = uri.Host
args.destination.key = strings.TrimPrefix(uri.Path, "/")
case uri.Scheme == "":
if uri.Host != "" {
return nil, errInvalidScheme
}
if uri.Path == "." {
cmdopts.destination.key = cmdopts.source.key
args.destination.key = args.source.key
} else {
cmdopts.destination.key = strings.TrimPrefix(uri.Path, "/")
args.destination.key = strings.TrimPrefix(uri.Path, "/")
}
cmdopts.destination.bucket = uri.Host
args.destination.bucket = uri.Host
case uri.Scheme != "s3":
return nil, errInvalidScheme
}