Merge pull request #178 from harshavardhana/pr_out_add_gocyclo_and_fix_all_its_complaints_use_15_as_cyclomatic_threshold
This commit is contained in:
@@ -14,8 +14,9 @@ getdeps: checkdeps checkgopath
|
||||
@go get github.com/tools/godep && echo "Installed godep"
|
||||
@go get github.com/golang/lint/golint && echo "Installed golint"
|
||||
@go get golang.org/x/tools/cmd/vet && echo "Installed vet"
|
||||
@go get github.com/fzipp/gocyclo && echo "Installed gocyclo"
|
||||
|
||||
verifiers: getdeps vet fmt lint
|
||||
verifiers: getdeps vet fmt lint cyclo
|
||||
|
||||
vet:
|
||||
@echo "Running $@"
|
||||
@@ -28,6 +29,10 @@ lint:
|
||||
@echo "Running $@"
|
||||
@test -z "$$(golint ./... | grep -v Godeps/_workspace/src/ | tee /dev/stderr)"
|
||||
|
||||
cyclo:
|
||||
@echo "Running $@"
|
||||
@test -z "$$(gocyclo -over 15 . | grep -v Godeps/_workspace/src/ | tee /dev/stderr)"
|
||||
|
||||
build-all: getdeps verifiers
|
||||
@echo "Building Libraries"
|
||||
@godep go generate ./...
|
||||
|
||||
+15
-11
@@ -76,25 +76,29 @@ func isBucketExist(bucketName string, v []*client.Bucket) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func sourceValidate(input string) error {
|
||||
if s3.IsValidBucketName(input) {
|
||||
return fmt.Errorf("Invalid input bucket name [%s]", input)
|
||||
}
|
||||
st, err := os.Stat(input)
|
||||
if os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
if !st.IsDir() {
|
||||
return errors.New("Should be a directory")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// doRecursiveCP recursively copies objects from source to destination
|
||||
func doRecursiveCP(c *cli.Context, args *cmdArgs) error {
|
||||
var err error
|
||||
var st os.FileInfo
|
||||
var buckets []*client.Bucket
|
||||
|
||||
switch true {
|
||||
case args.source.bucket == "":
|
||||
input := path.Clean(args.source.key)
|
||||
if s3.IsValidBucketName(input) {
|
||||
return fmt.Errorf("Invalid input bucket name [%s]", input)
|
||||
}
|
||||
st, err = os.Stat(input)
|
||||
if os.IsNotExist(err) {
|
||||
if err := sourceValidate(input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !st.IsDir() {
|
||||
return errors.New("Should be a directory")
|
||||
}
|
||||
s3c, err := getNewClient(c.GlobalBool("debug"), args.destination.url.String())
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -55,12 +55,37 @@ func printObject(date time.Time, v int64, key string) {
|
||||
info(msg)
|
||||
}
|
||||
|
||||
// listObjectPrefix prints matching key prefix
|
||||
func listObjectPrefix(s3c client.Client, bucketName, objectName string, maxkeys int) {
|
||||
var date time.Time
|
||||
var size int64
|
||||
var err error
|
||||
|
||||
size, date, err = s3c.Stat(bucketName, objectName)
|
||||
var items []*client.Item
|
||||
switch err {
|
||||
case nil: // List a single object. Exact key
|
||||
printObject(date, size, objectName)
|
||||
case os.ErrNotExist:
|
||||
// List all objects matching the key prefix
|
||||
items, _, err = s3c.ListObjects(bucketName, "", objectName, "", maxkeys)
|
||||
if err != nil {
|
||||
fatal(err.Error())
|
||||
}
|
||||
if len(items) > 0 {
|
||||
printObjects(items)
|
||||
} else {
|
||||
fatal(os.ErrNotExist.Error())
|
||||
}
|
||||
default: // Error
|
||||
fatal(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// doListCmd lists objects inside a bucket
|
||||
func doListCmd(c *cli.Context) {
|
||||
var items []*client.Item
|
||||
|
||||
// quiet := c.GlobalBool("quiet")
|
||||
|
||||
urlStr, err := parseURL(c)
|
||||
if err != nil {
|
||||
fatal(err.Error())
|
||||
@@ -94,27 +119,7 @@ func doListCmd(c *cli.Context) {
|
||||
}
|
||||
printObjects(items)
|
||||
case objectName != "": // List objects matching the key prefix
|
||||
var date time.Time
|
||||
var size int64
|
||||
|
||||
size, date, err = s3c.Stat(bucketName, objectName)
|
||||
switch err {
|
||||
case nil: // List a single object. Exact key
|
||||
printObject(date, size, objectName)
|
||||
case os.ErrNotExist:
|
||||
// List all objects matching the key prefix
|
||||
items, _, err = s3c.ListObjects(bucketName, "", objectName, "", s3.MaxKeys)
|
||||
if err != nil {
|
||||
fatal(err.Error())
|
||||
}
|
||||
if len(items) > 0 {
|
||||
printObjects(items)
|
||||
} else {
|
||||
fatal(os.ErrNotExist.Error())
|
||||
}
|
||||
default: // Error
|
||||
fatal(err.Error())
|
||||
}
|
||||
listObjectPrefix(s3c, bucketName, objectName, s3.MaxKeys)
|
||||
default:
|
||||
fatal(err.Error())
|
||||
}
|
||||
|
||||
@@ -78,35 +78,120 @@ func getNewClient(debug bool, url string) (cl client.Client, err error) {
|
||||
return cl, nil
|
||||
}
|
||||
|
||||
func parseDestinationArgs(urlParsed *url.URL, destination, source object) (object, error) {
|
||||
switch true {
|
||||
case urlParsed.Scheme == "http" || urlParsed.Scheme == "https":
|
||||
if urlParsed.Host == "" {
|
||||
if urlParsed.Path == "" {
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
destination.host = urlParsed.Host
|
||||
destination.scheme = urlParsed.Scheme
|
||||
destination.url = urlParsed
|
||||
urlSplits := strings.Split(urlParsed.Path, "/")
|
||||
if len(urlSplits) > 1 {
|
||||
destination.bucket = urlSplits[1]
|
||||
destination.key = path.Join(urlSplits[2:]...)
|
||||
}
|
||||
case urlParsed.Scheme == "":
|
||||
if urlParsed.Host != "" {
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
if urlParsed.Path == "." {
|
||||
destination.key = source.key
|
||||
} else {
|
||||
destination.key = strings.TrimPrefix(urlParsed.Path, "/")
|
||||
}
|
||||
destination.bucket = urlParsed.Host
|
||||
case urlParsed.Scheme != "http" && urlParsed.Scheme != "https":
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
return destination, nil
|
||||
}
|
||||
|
||||
func parseSourceArgs(urlParsed *url.URL, firstArg string, source object) (object, error) {
|
||||
switch true {
|
||||
case urlParsed.Scheme == "http" || urlParsed.Scheme == "https":
|
||||
if urlParsed.Host == "" {
|
||||
if urlParsed.Path == "" {
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
source.scheme = urlParsed.Scheme
|
||||
source.host = urlParsed.Host
|
||||
source.url = urlParsed
|
||||
urlSplits := strings.Split(urlParsed.Path, "/")
|
||||
if len(urlSplits) > 1 {
|
||||
source.bucket = urlSplits[1]
|
||||
source.key = path.Join(urlSplits[2:]...)
|
||||
}
|
||||
case urlParsed.Scheme == "":
|
||||
if urlParsed.Host != "" {
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
if urlParsed.Path != firstArg {
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
if urlParsed.Path == "." {
|
||||
return object{}, errFskey
|
||||
}
|
||||
source.key = strings.TrimPrefix(urlParsed.Path, "/")
|
||||
case urlParsed.Scheme != "http" && urlParsed.Scheme != "https":
|
||||
return object{}, errInvalidScheme
|
||||
}
|
||||
return source, nil
|
||||
}
|
||||
|
||||
func parseSingleArg(urlParsed *url.URL, source object) (object, error) {
|
||||
source.scheme = urlParsed.Scheme
|
||||
source.url = urlParsed
|
||||
if urlParsed.Scheme != "" {
|
||||
if urlParsed.Host == "" {
|
||||
return object{}, errHostname
|
||||
}
|
||||
}
|
||||
source.host = urlParsed.Host
|
||||
urlSplits := strings.Split(urlParsed.Path, "/")
|
||||
if len(urlSplits) > 1 {
|
||||
source.bucket = urlSplits[1]
|
||||
source.key = path.Join(urlSplits[2:]...)
|
||||
}
|
||||
return source, nil
|
||||
}
|
||||
|
||||
func urlAliasExpander(arg string) (*url.URL, error) {
|
||||
urlString, err := aliasExpand(arg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
urlParsed, err := url.Parse(urlString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return urlParsed, nil
|
||||
}
|
||||
|
||||
// Parse subcommand options
|
||||
func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
|
||||
args = new(cmdArgs)
|
||||
args.quiet = c.GlobalBool("quiet")
|
||||
|
||||
switch len(c.Args()) {
|
||||
case 1: // only one URL
|
||||
urlString, err := aliasExpand(c.Args().First())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(urlString, "http") {
|
||||
urlParsed, err := url.Parse(urlString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args.source.scheme = urlParsed.Scheme
|
||||
args.source.url = urlParsed
|
||||
if urlParsed.Scheme != "" {
|
||||
if urlParsed.Host == "" {
|
||||
return nil, errHostname
|
||||
}
|
||||
}
|
||||
args.source.host = urlParsed.Host
|
||||
urlSplits := strings.Split(urlParsed.Path, "/")
|
||||
if len(urlSplits) > 1 {
|
||||
args.source.bucket = urlSplits[1]
|
||||
args.source.key = path.Join(urlSplits[2:]...)
|
||||
args.source, err = parseSingleArg(urlParsed, args.source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
return nil, errInvalidScheme
|
||||
@@ -114,85 +199,24 @@ func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
|
||||
case 2: // one URL and one path||URL
|
||||
switch true {
|
||||
case c.Args().First() != "":
|
||||
urlString, err := aliasExpand(c.Args().First())
|
||||
urlParsed, err := urlAliasExpander(c.Args().First())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
urlParsed, err := url.Parse(urlString)
|
||||
args.source, err = parseSourceArgs(urlParsed, c.Args().First(), args.source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch true {
|
||||
case urlParsed.Scheme == "http" || urlParsed.Scheme == "https":
|
||||
if urlParsed.Host == "" {
|
||||
if urlParsed.Path == "" {
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
args.source.scheme = urlParsed.Scheme
|
||||
args.source.host = urlParsed.Host
|
||||
args.source.url = urlParsed
|
||||
urlSplits := strings.Split(urlParsed.Path, "/")
|
||||
if len(urlSplits) > 1 {
|
||||
args.source.bucket = urlSplits[1]
|
||||
args.source.key = path.Join(urlSplits[2:]...)
|
||||
}
|
||||
case urlParsed.Scheme == "":
|
||||
if urlParsed.Host != "" {
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
if urlParsed.Path != c.Args().First() {
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
if urlParsed.Path == "." {
|
||||
return nil, errFskey
|
||||
}
|
||||
args.source.key = strings.TrimPrefix(urlParsed.Path, "/")
|
||||
case urlParsed.Scheme != "http" && urlParsed.Scheme != "https":
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
fallthrough
|
||||
case c.Args().Get(1) != "":
|
||||
urlString, err := aliasExpand(c.Args().Get(1))
|
||||
urlParsed, err := urlAliasExpander(c.Args().Get(1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
urlParsed, err := url.Parse(urlString)
|
||||
args.destination, err = parseDestinationArgs(urlParsed, args.destination, args.source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch true {
|
||||
case urlParsed.Scheme == "http" || urlParsed.Scheme == "https":
|
||||
if urlParsed.Host == "" {
|
||||
if urlParsed.Path == "" {
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
args.destination.host = urlParsed.Host
|
||||
args.destination.scheme = urlParsed.Scheme
|
||||
args.destination.url = urlParsed
|
||||
urlSplits := strings.Split(urlParsed.Path, "/")
|
||||
if len(urlSplits) > 1 {
|
||||
args.destination.bucket = urlSplits[1]
|
||||
args.destination.key = path.Join(urlSplits[2:]...)
|
||||
}
|
||||
case urlParsed.Scheme == "":
|
||||
if urlParsed.Host != "" {
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
if urlParsed.Path == "." {
|
||||
args.destination.key = args.source.key
|
||||
} else {
|
||||
args.destination.key = strings.TrimPrefix(urlParsed.Path, "/")
|
||||
}
|
||||
args.destination.bucket = urlParsed.Host
|
||||
case urlParsed.Scheme != "http" && urlParsed.Scheme != "https":
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
}
|
||||
default:
|
||||
return nil, errInvalidScheme
|
||||
|
||||
+44
-35
@@ -11,9 +11,50 @@ import (
|
||||
"github.com/minio-io/mc/pkg/client/donut"
|
||||
)
|
||||
|
||||
var d = donut.GetNewClient("testdir")
|
||||
|
||||
func upload(urlArg1, urlArg2 *url.URL) {
|
||||
st, stErr := os.Stat(urlArg1.Path)
|
||||
if os.IsNotExist(stErr) {
|
||||
panic(stErr)
|
||||
}
|
||||
if st.IsDir() {
|
||||
panic("is a directory")
|
||||
}
|
||||
reader, err := os.OpenFile(urlArg1.Path, 2, os.ModeAppend)
|
||||
defer reader.Close()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if urlArg2.Scheme == "donut" {
|
||||
err := d.Put(urlArg2.Host, strings.TrimPrefix(urlArg2.Path, "/"), st.Size(), reader)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func download(urlArg1, urlArg2 *url.URL) {
|
||||
writer, err := os.Create(urlArg2.Path)
|
||||
defer writer.Close()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if urlArg1.Scheme == "donut" {
|
||||
reader, size, err := d.Get(urlArg1.Host, strings.TrimPrefix(urlArg1.Path, "/"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_, err = io.CopyN(writer, reader, size)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
reader.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func doDonutCPCmd(c *cli.Context) {
|
||||
os.MkdirAll("testdir", 0755)
|
||||
d := donut.GetNewClient("testdir")
|
||||
switch len(c.Args()) {
|
||||
case 2:
|
||||
urlArg1, errArg1 := url.Parse(c.Args().Get(0))
|
||||
@@ -26,41 +67,9 @@ func doDonutCPCmd(c *cli.Context) {
|
||||
}
|
||||
switch true {
|
||||
case urlArg1.Scheme != "" && urlArg2.Scheme == "":
|
||||
writer, err := os.Create(urlArg2.Path)
|
||||
defer writer.Close()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if urlArg1.Scheme == "donut" {
|
||||
reader, size, err := d.Get(urlArg1.Host, strings.TrimPrefix(urlArg1.Path, "/"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_, err = io.CopyN(writer, reader, size)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
reader.Close()
|
||||
}
|
||||
download(urlArg1, urlArg2)
|
||||
case urlArg1.Scheme == "" && urlArg2.Scheme != "":
|
||||
st, stErr := os.Stat(urlArg1.Path)
|
||||
if os.IsNotExist(stErr) {
|
||||
panic(stErr)
|
||||
}
|
||||
if st.IsDir() {
|
||||
panic("is a directory")
|
||||
}
|
||||
reader, err := os.OpenFile(urlArg1.Path, 2, os.ModeAppend)
|
||||
defer reader.Close()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if urlArg2.Scheme == "donut" {
|
||||
err := d.Put(urlArg2.Host, strings.TrimPrefix(urlArg2.Path, "/"), st.Size(), reader)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
upload(urlArg1, urlArg2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+77
-55
@@ -104,6 +104,69 @@ func (c *s3Client) PutBucket(bucket string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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) retry(urlReq string) (listBucketResults, error) {
|
||||
const maxTries = 5
|
||||
bres := listBucketResults{}
|
||||
for try := 1; try <= maxTries; try++ {
|
||||
time.Sleep(time.Duration(try-1) * 100 * time.Millisecond)
|
||||
req := newReq(urlReq)
|
||||
c.signRequest(req, c.Host)
|
||||
res, err := c.Transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
if try < maxTries {
|
||||
continue
|
||||
}
|
||||
return listBucketResults{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return listBucketResults{}, NewError(res)
|
||||
}
|
||||
|
||||
var logbuf bytes.Buffer
|
||||
err = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(&bres)
|
||||
if err != nil {
|
||||
fmt.Printf("Error parsing s3 XML response: %v for %q\n", err, logbuf.Bytes())
|
||||
if try < maxTries-1 {
|
||||
fmt.Printf("Reconnecting...\n")
|
||||
continue
|
||||
}
|
||||
return listBucketResults{}, err
|
||||
}
|
||||
break
|
||||
}
|
||||
return bres, nil
|
||||
}
|
||||
|
||||
func (c *s3Client) getItems(s, m string, contents []*client.Item) (items []*client.Item, marker string, err error) {
|
||||
for _, it := range contents {
|
||||
if it.Key == m && it.Key != s {
|
||||
// Skip first dup on pages 2 and higher.
|
||||
continue
|
||||
}
|
||||
if it.Key < s {
|
||||
msg := fmt.Sprintf("Unexpected response from Amazon: item key %q but wanted greater than %q", it.Key, s)
|
||||
return nil, m, errors.New(msg)
|
||||
}
|
||||
items = append(items, it)
|
||||
marker = it.Key
|
||||
}
|
||||
return items, marker, nil
|
||||
}
|
||||
|
||||
func (c *s3Client) getPrefixes(commonPrefixes []*client.Prefix) (prefixes []*client.Prefix, err error) {
|
||||
for _, pre := range commonPrefixes {
|
||||
if pre.Prefix != "" {
|
||||
prefixes = append(prefixes, pre)
|
||||
}
|
||||
}
|
||||
return prefixes, nil
|
||||
}
|
||||
|
||||
// ListObjects returns 0 to maxKeys (inclusive) items from the
|
||||
// provided bucket. Keys before startAt will be skipped. (This is the S3
|
||||
// 'marker' value). If the length of the returned items is equal to
|
||||
@@ -136,63 +199,22 @@ func (c *s3Client) ListObjects(bucket string, startAt, prefix, delimiter string,
|
||||
}
|
||||
|
||||
urlReq = buffer.String()
|
||||
// Try the enumerate three 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
|
||||
const maxTries = 5
|
||||
for try := 1; try <= maxTries; try++ {
|
||||
time.Sleep(time.Duration(try-1) * 100 * time.Millisecond)
|
||||
req := newReq(urlReq)
|
||||
c.signRequest(req, c.Host)
|
||||
res, err := c.Transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
if try < maxTries {
|
||||
continue
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, nil, NewError(res)
|
||||
}
|
||||
|
||||
bres = listBucketResults{}
|
||||
var logbuf bytes.Buffer
|
||||
err = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(&bres)
|
||||
if err != nil {
|
||||
fmt.Printf("Error parsing s3 XML response: %v for %q", err, logbuf.Bytes())
|
||||
} else if bres.MaxKeys != fetchN || bres.Name != bucket || bres.Marker != marker {
|
||||
msg := fmt.Sprintf("Unexpected parse from server: %#v from: %s", bres, logbuf.Bytes())
|
||||
err = errors.New(msg)
|
||||
fmt.Print(err)
|
||||
}
|
||||
if err != nil {
|
||||
if try < maxTries-1 {
|
||||
continue
|
||||
}
|
||||
fmt.Print(err)
|
||||
return nil, nil, err
|
||||
}
|
||||
break
|
||||
bres, err = c.retry(urlReq)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, it := range bres.Contents {
|
||||
if it.Key == marker && it.Key != startAt {
|
||||
// Skip first dup on pages 2 and higher.
|
||||
continue
|
||||
}
|
||||
if it.Key < startAt {
|
||||
msg := fmt.Sprintf("Unexpected response from Amazon: item key %q but wanted greater than %q", it.Key, startAt)
|
||||
return nil, nil, errors.New(msg)
|
||||
}
|
||||
items = append(items, it)
|
||||
marker = it.Key
|
||||
if bres.MaxKeys != fetchN || bres.Name != bucket || bres.Marker != marker {
|
||||
msg := fmt.Sprintf("Unexpected parse from server: %#v", bres)
|
||||
err = errors.New(msg)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
for _, pre := range bres.CommonPrefixes {
|
||||
if pre.Prefix != "" {
|
||||
prefixes = append(prefixes, pre)
|
||||
}
|
||||
items, marker, err = c.getItems(startAt, marker, bres.Contents)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
prefixes, err = c.getPrefixes(bres.CommonPrefixes)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if !bres.IsTruncated {
|
||||
|
||||
@@ -23,8 +23,8 @@ import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Integer to Int conversion
|
||||
func int2CInt(srcErrList []int) *C.int32_t {
|
||||
// intSlice2CIntArray converts Go int slice to C int array
|
||||
func intSlice2CIntArray(srcErrList []int) *C.int32_t {
|
||||
var sizeErrInt = int(unsafe.Sizeof(srcErrList[0]))
|
||||
switch sizeInt {
|
||||
case sizeErrInt:
|
||||
|
||||
@@ -27,11 +27,16 @@ import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Decode decodes 2 tuple data containing (k + m) chunks back into its original form.
|
||||
// Additionally original block length should also be provided as input.
|
||||
// Decode decodes erasure coded blocks of data into its original
|
||||
// form. Erasure coded data contains K data blocks and M parity
|
||||
// blocks. Decode can withstand data loss up to any M number of blocks.
|
||||
//
|
||||
// Decoded data is exactly similar in length and content as the original data.
|
||||
func (e *Encoder) Decode(chunks [][]byte, length int) ([]byte, error) {
|
||||
// "encodedDataBlocks" is an array of K data blocks and M parity
|
||||
// blocks. Data blocks are position and order dependent. Missing blocks
|
||||
// are set to "nil". There must be at least "K" number of data|parity
|
||||
// blocks.
|
||||
// "dataLen" is the length of original source data
|
||||
func (e *Encoder) Decode(encodedDataBlocks [][]byte, dataLen int) (decodedData []byte, err error) {
|
||||
var decodeMatrix *C.uint8_t
|
||||
var decodeTbls *C.uint8_t
|
||||
var decodeIndex *C.uint32_t
|
||||
@@ -40,66 +45,73 @@ func (e *Encoder) Decode(chunks [][]byte, length int) ([]byte, error) {
|
||||
k := int(e.params.K)
|
||||
m := int(e.params.M)
|
||||
n := k + m
|
||||
if len(chunks) != n {
|
||||
msg := fmt.Sprintf("chunks length must be %d", n)
|
||||
return nil, errors.New(msg)
|
||||
// We need the data and parity blocks preserved in the same order. Missing blocks are set to nil.
|
||||
if len(encodedDataBlocks) != n {
|
||||
return nil, errors.New(fmt.Sprintf("Encoded data blocks slice must of length [%d]", n))
|
||||
}
|
||||
chunkLen := GetEncodedBlockLen(length, uint8(k))
|
||||
|
||||
errorIndex := make([]int, n+1)
|
||||
var errCount int
|
||||
// Length of a single encoded block
|
||||
encodedBlockLen := GetEncodedBlockLen(dataLen, uint8(k))
|
||||
|
||||
for i := range chunks {
|
||||
// Check of chunks are really null
|
||||
if chunks[i] == nil || len(chunks[i]) == 0 {
|
||||
errorIndex[errCount] = i
|
||||
errCount++
|
||||
// Keep track of errors per block.
|
||||
missingEncodedBlocks := make([]int, n+1)
|
||||
var missingEncodedBlocksCount int = 0
|
||||
|
||||
// Check for the missing encoded blocks
|
||||
for i := range encodedDataBlocks {
|
||||
if encodedDataBlocks[i] == nil || len(encodedDataBlocks[i]) == 0 {
|
||||
missingEncodedBlocks[missingEncodedBlocksCount] = i
|
||||
missingEncodedBlocksCount++
|
||||
}
|
||||
}
|
||||
errorIndex[errCount] = -1
|
||||
errCount++
|
||||
missingEncodedBlocks[missingEncodedBlocksCount] = -1
|
||||
missingEncodedBlocksCount++
|
||||
|
||||
// Too many missing chunks, cannot be more than parity `m`
|
||||
if errCount-1 > int(n-k) {
|
||||
return nil, errors.New("too many erasures requested, can't decode")
|
||||
// Cannot reconstruct original data. Need at least M number of data or parity blocks.
|
||||
if missingEncodedBlocksCount-1 > m {
|
||||
return nil, fmt.Errorf("Cannot reconstruct original data. Need at least [%d] data or parity blocks", m)
|
||||
}
|
||||
|
||||
errorIndexPtr := int2CInt(errorIndex[:errCount])
|
||||
// Convert from Go int slice to C int array
|
||||
missingEncodedBlocksC := intSlice2CIntArray(missingEncodedBlocks[:missingEncodedBlocksCount])
|
||||
|
||||
for i := range chunks {
|
||||
if chunks[i] == nil || len(chunks[i]) == 0 {
|
||||
chunks[i] = make([]byte, chunkLen)
|
||||
// Allocate buffer for the missing blocks
|
||||
for i := range encodedDataBlocks {
|
||||
if encodedDataBlocks[i] == nil || len(encodedDataBlocks[i]) == 0 {
|
||||
encodedDataBlocks[i] = make([]byte, encodedBlockLen)
|
||||
}
|
||||
}
|
||||
|
||||
C.minio_init_decoder(errorIndexPtr, C.int(k), C.int(n), C.int(errCount-1),
|
||||
// Initialzie decoder
|
||||
C.minio_init_decoder(missingEncodedBlocksC, C.int(k), C.int(n), C.int(missingEncodedBlocksCount-1),
|
||||
e.encodeMatrix, &decodeMatrix, &decodeTbls, &decodeIndex)
|
||||
|
||||
// Make a slice of pointers to encoded blocks. Necessary to bridge to the C world.
|
||||
pointers := make([]*byte, n)
|
||||
for i := range chunks {
|
||||
pointers[i] = &chunks[i][0]
|
||||
for i := range encodedDataBlocks {
|
||||
pointers[i] = &encodedDataBlocks[i][0]
|
||||
}
|
||||
|
||||
data := (**C.uint8_t)(unsafe.Pointer(&pointers[0]))
|
||||
|
||||
ret := C.minio_get_source_target(C.int(errCount-1), C.int(k), C.int(m), errorIndexPtr,
|
||||
decodeIndex, data, &source, &target)
|
||||
|
||||
// Get pointers to source "data" and target "parity" blocks from the output byte array.
|
||||
ret := C.minio_get_source_target(C.int(missingEncodedBlocksCount-1), C.int(k), C.int(m), missingEncodedBlocksC,
|
||||
decodeIndex, (**C.uint8_t)(unsafe.Pointer(&pointers[0])), &source, &target)
|
||||
if int(ret) == -1 {
|
||||
return nil, errors.New("Decoding source target failed")
|
||||
return nil, errors.New("Unable to decode data")
|
||||
}
|
||||
|
||||
C.ec_encode_data(C.int(chunkLen), C.int(k), C.int(errCount-1), decodeTbls,
|
||||
// Decode data
|
||||
C.ec_encode_data(C.int(encodedBlockLen), C.int(k), C.int(missingEncodedBlocksCount-1), decodeTbls,
|
||||
source, target)
|
||||
|
||||
recoveredOutput := make([]byte, 0, chunkLen*int(k))
|
||||
// Allocate buffer to output buffer
|
||||
decodedData = make([]byte, 0, encodedBlockLen*int(k))
|
||||
for i := 0; i < int(k); i++ {
|
||||
recoveredOutput = append(recoveredOutput, chunks[i]...)
|
||||
decodedData = append(decodedData, encodedDataBlocks[i]...)
|
||||
}
|
||||
|
||||
// TODO cache this if necessary
|
||||
e.decodeMatrix = decodeMatrix
|
||||
e.decodeTbls = decodeTbls
|
||||
|
||||
return recoveredOutput[:length], nil
|
||||
return decodedData[:dataLen], nil
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ func (e *Encoder) Encode(inputData []byte) (encodedBlocks [][]byte, err error) {
|
||||
}
|
||||
|
||||
// Extend inputData buffer to accommodate coded parity blocks
|
||||
if true { // create a temporary scope to trigger garbage collect
|
||||
{ // Local Scope
|
||||
encodedParityBlocksLen := encodedBlockLen * m
|
||||
parityBlocks := make([]byte, encodedParityBlocksLen)
|
||||
inputData = append(inputData, parityBlocks...)
|
||||
|
||||
+39
-23
@@ -86,31 +86,13 @@ func (p *Partition) getPartitionAttrs(part string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// getDiskAttrs - populates all the disk related attributes
|
||||
func (d *Disk) getDiskAttrs(disk string) error {
|
||||
var diskAttrsList []string
|
||||
var diskQueueAttrs []string
|
||||
aggrAttrMap := make(map[string][]byte)
|
||||
|
||||
sysfsBlockDev := path.Join(SysfsBlock, disk)
|
||||
sysfsBlockDevQueue := path.Join(sysfsBlockDev, "/queue")
|
||||
|
||||
scsiFiles, err := ioutil.ReadDir(sysfsBlockDev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
scsiQueueFiles, err := ioutil.ReadDir(sysfsBlockDevQueue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Disk) getDiskAttrList(scsiFiles []os.FileInfo, disk string) (diskAttrsList []string, err error) {
|
||||
for _, sf := range scsiFiles {
|
||||
if sf.IsDir() {
|
||||
if strings.Contains(sf.Name(), disk) {
|
||||
var p = Partition{}
|
||||
if err := p.getPartitionAttrs(sf.Name()); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
d.Partitions = append(d.Partitions, p)
|
||||
}
|
||||
@@ -126,7 +108,10 @@ func (d *Disk) getDiskAttrs(disk string) error {
|
||||
}
|
||||
diskAttrsList = append(diskAttrsList, sf.Name())
|
||||
}
|
||||
return diskAttrsList, nil
|
||||
}
|
||||
|
||||
func (d *Disk) getDiskQueueAttrsList(scsiQueueFiles []os.FileInfo) (diskQueueAttrsList []string, err error) {
|
||||
for _, sf := range scsiQueueFiles {
|
||||
if sf.IsDir() {
|
||||
continue
|
||||
@@ -139,19 +124,50 @@ func (d *Disk) getDiskAttrs(disk string) error {
|
||||
if sf.Mode().Perm() == 128 {
|
||||
continue
|
||||
}
|
||||
diskQueueAttrs = append(diskQueueAttrs, sf.Name())
|
||||
diskQueueAttrsList = append(diskQueueAttrsList, sf.Name())
|
||||
}
|
||||
return diskQueueAttrsList, nil
|
||||
}
|
||||
|
||||
// getDiskAttrs - populates all the disk related attributes
|
||||
func (d *Disk) getDiskAttrs(disk string) error {
|
||||
var diskAttrsList []string
|
||||
var diskQueueAttrsList []string
|
||||
aggrAttrMap := make(map[string][]byte)
|
||||
|
||||
sysfsBlockDev := path.Join(SysfsBlock, disk)
|
||||
sysfsBlockDevQueue := path.Join(sysfsBlockDev, "/queue")
|
||||
|
||||
scsiFiles, err := ioutil.ReadDir(sysfsBlockDev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
scsiQueueFiles, err := ioutil.ReadDir(sysfsBlockDevQueue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
diskAttrsList, err = d.getDiskAttrList(scsiFiles, disk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
diskQueueAttrsList, err = d.getDiskQueueAttrsList(scsiQueueFiles)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(diskAttrsList) == 0 {
|
||||
return NoDiskAttributesFound{}
|
||||
}
|
||||
|
||||
if len(diskQueueAttrs) == 0 {
|
||||
if len(diskQueueAttrsList) == 0 {
|
||||
return NoDiskQueueAttributesFound{}
|
||||
}
|
||||
|
||||
diskAttrMap := getattrs(sysfsBlockDev, diskAttrsList)
|
||||
diskQueueAttrMap := getattrs(sysfsBlockDevQueue, diskQueueAttrs)
|
||||
diskQueueAttrMap := getattrs(sysfsBlockDevQueue, diskQueueAttrsList)
|
||||
|
||||
for k, v := range diskAttrMap {
|
||||
aggrAttrMap[k] = v
|
||||
|
||||
@@ -2,6 +2,7 @@ package donut
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/minio-io/iodine"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -12,7 +13,7 @@ type donutBucket struct {
|
||||
}
|
||||
|
||||
// GetNodes - get list of associated nodes for a given bucket
|
||||
func (b donutBucket) GetNodes() ([]string, error) {
|
||||
func (b donutBucket) GetNodes() ([]string, *iodine.Error) {
|
||||
var nodes []string
|
||||
for _, node := range b.nodes {
|
||||
nodes = append(nodes, node)
|
||||
@@ -20,17 +21,17 @@ func (b donutBucket) GetNodes() ([]string, error) {
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (b donutBucket) AddNode(nodeID, bucketID string) error {
|
||||
func (b donutBucket) AddNode(nodeID, bucketID string) *iodine.Error {
|
||||
tokens := strings.Split(bucketID, ":")
|
||||
if len(tokens) != 3 {
|
||||
return errors.New("Bucket ID malformed: " + bucketID)
|
||||
return iodine.New(errors.New("Bucket ID malformed: "+bucketID), map[string]string{"nodeID": nodeID, "bucketID": bucketID})
|
||||
}
|
||||
// bucketName := tokens[0]
|
||||
// aggregate := tokens[1]
|
||||
// aggregate := "0"
|
||||
part, err := strconv.Atoi(tokens[2])
|
||||
if err != nil {
|
||||
return errors.New("Part malformed: " + tokens[2])
|
||||
return iodine.New(errors.New("Part malformed: "+tokens[2]), map[string]string{"nodeID": nodeID, "bucketID": bucketID})
|
||||
}
|
||||
b.nodes[part] = nodeID
|
||||
return nil
|
||||
|
||||
@@ -67,9 +67,6 @@ func erasureReader(readers []io.ReadCloser, donutMetadata map[string]string, wri
|
||||
summer := md5.New()
|
||||
params, _ := erasure.ParseEncoderParams(uint8(k), uint8(m), technique)
|
||||
encoder := erasure.NewEncoder(params)
|
||||
for _, reader := range readers {
|
||||
defer reader.Close()
|
||||
}
|
||||
for i := 0; i < totalChunks; i++ {
|
||||
curBlockSize := totalLeft
|
||||
if blockSize < totalLeft {
|
||||
@@ -77,9 +74,9 @@ func erasureReader(readers []io.ReadCloser, donutMetadata map[string]string, wri
|
||||
}
|
||||
|
||||
curChunkSize := erasure.GetEncodedBlockLen(curBlockSize, uint8(k))
|
||||
|
||||
encodedBytes := make([][]byte, 16)
|
||||
for i, reader := range readers {
|
||||
defer reader.Close()
|
||||
var bytesBuffer bytes.Buffer
|
||||
_, err := io.CopyN(&bytesBuffer, reader, int64(curChunkSize))
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package donut
|
||||
|
||||
import (
|
||||
"github.com/minio-io/iodine"
|
||||
"io"
|
||||
)
|
||||
|
||||
@@ -18,8 +19,8 @@ type Donut interface {
|
||||
|
||||
// Bucket interface
|
||||
type Bucket interface {
|
||||
GetNodes() ([]string, error)
|
||||
AddNode(nodeID, bucketID string) error
|
||||
GetNodes() ([]string, *iodine.Error)
|
||||
AddNode(nodeID, bucketID string) *iodine.Error
|
||||
}
|
||||
|
||||
// Node interface
|
||||
|
||||
Reference in New Issue
Block a user