Add od command (#4180)

This commit is contained in:
Taran Pelkey
2022-08-22 22:02:23 -07:00
committed by GitHub
parent 488b277e36
commit 68a36788aa
7 changed files with 621 additions and 0 deletions
+1
View File
@@ -445,6 +445,7 @@ var completeCmds = map[string]complete.Predictor{
"/update": nil,
"/ready": nil,
"/ping": nil,
"/od": nil,
}
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
+118
View File
@@ -391,6 +391,116 @@ func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, progre
return f.put(ctx, reader, size, progress, opts)
}
func (f *fsClient) putN(ctx context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (int64, *probe.Error) {
// ContentType is not handled on purpose.
// For filesystem this is a redundant information.
// Extract dir name.
objectDir, objectName := filepath.Split(f.PathURL.Path)
if objectDir != "" {
// Create any missing top level directories.
if e := os.MkdirAll(objectDir, 0o777); e != nil {
err := f.toClientError(e, f.PathURL.Path)
return 0, err.Trace(f.PathURL.Path)
}
// Check if object name is empty, it must be an empty directory
if objectName == "" {
return 0, nil
}
}
objectPath := f.PathURL.Path
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
// We cannot resume this operation, then we
// should remove any partial download if any.
defer os.Remove(objectPartPath)
tmpFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_WRONLY, 0o666)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return 0, err.Trace(f.PathURL.Path)
}
attr := make(map[string]string)
if _, ok := opts.metadata[metadataKey]; ok && opts.isPreserve {
attr, e = parseAttribute(opts.metadata)
if e != nil {
tmpFile.Close()
return 0, probe.NewError(e)
}
err := preserveAttributes(tmpFile, attr)
if err != nil {
console.Println(console.Colorize("Error", fmt.Sprintf("unable to preserve attributes, continuing to copy the content %s\n", err.ToGoError())))
}
}
totalWritten, e := io.CopyN(tmpFile, hookreader.NewHook(reader, progress), size)
if e != nil {
tmpFile.Close()
return 0, probe.NewError(e)
}
// Close the input reader as well, if possible.
closer, ok := reader.(io.Closer)
if ok {
if e = closer.Close(); e != nil {
tmpFile.Close()
return totalWritten, probe.NewError(e)
}
}
// Close the file before renaming, we need to do this
// specifically for windows users - windows explicitly
// disallows renames on Open() fd's by default.
if e = tmpFile.Close(); e != nil {
return totalWritten, probe.NewError(e)
}
// Following verification is needed only for input size greater than '0'.
if size > 0 {
// Unexpected ExcessRead (more data was written than expected).
if totalWritten > size {
return totalWritten, probe.NewError(UnexpectedExcessRead{
TotalSize: size,
TotalWritten: totalWritten,
})
}
}
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return totalWritten, err.Trace(objectPartPath, objectPath)
}
if len(attr) != 0 && opts.isPreserve {
atime, mtime, err := parseAtimeMtime(attr)
if err != nil {
return totalWritten, err.Trace()
}
if !atime.IsZero() && !mtime.IsZero() {
if e := os.Chtimes(objectPath, atime, mtime); e != nil {
return totalWritten, probe.NewError(e)
}
}
}
return totalWritten, nil
}
// PutPart - create a new file with metadata, reading up to N bytes.
func (f *fsClient) PutPart(ctx context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (int64, *probe.Error) {
if size < 0 {
return f.put(ctx, reader, size, progress, opts)
}
return f.putN(ctx, reader, size, progress, opts)
}
// ShareDownload - share download not implemented for filesystem.
func (f *fsClient) ShareDownload(ctx context.Context, versionID string, expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(APINotImplemented{
@@ -1297,3 +1407,11 @@ func (f *fsClient) Restore(_ context.Context, _ string, _ int) *probe.Error {
APIType: "filesystem",
})
}
// OD Get - not implemented
func (f *fsClient) GetPart(ctx context.Context, _ int) (io.ReadCloser, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
API: "GetPart",
APIType: "filesystem",
})
}
+25
View File
@@ -1114,6 +1114,11 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
return ui.Size, nil
}
// PutPart - upload an object with custom metadata. (Same as Put)
func (c *S3Client) PutPart(ctx context.Context, reader io.Reader, size int64, progress io.Reader, putOpts PutOptions) (int64, *probe.Error) {
return c.Put(ctx, reader, size, progress, putOpts)
}
// Remove incomplete uploads.
func (c *S3Client) removeIncompleteObjects(ctx context.Context, bucket string, objectsCh <-chan minio.ObjectInfo) <-chan minio.RemoveObjectResult {
removeObjectErrorCh := make(chan minio.RemoveObjectResult)
@@ -2843,3 +2848,23 @@ func (c *S3Client) Restore(ctx context.Context, versionID string, days int) *pro
}
return nil
}
// GetPart gets an object in a given number of parts
func (c *S3Client) GetPart(ctx context.Context, part int) (io.ReadCloser, *probe.Error) {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return nil, probe.NewError(BucketNameEmpty{})
}
if object == "" {
return nil, probe.NewError(ObjectNameEmpty{})
}
getOO := minio.GetObjectOptions{}
if part > 0 {
getOO.PartNumber = part
}
reader, e := c.api.GetObject(ctx, bucket, object, getOO)
if e != nil {
return nil, probe.NewError(e)
}
return reader, nil
}
+4
View File
@@ -173,6 +173,10 @@ type Client interface {
// Restore an object
Restore(ctx context.Context, versionID string, days int) *probe.Error
// OD operations
GetPart(ctx context.Context, part int) (io.ReadCloser, *probe.Error)
PutPart(ctx context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (n int64, err *probe.Error)
}
// ClientContent - Content container for content metadata
+1
View File
@@ -453,6 +453,7 @@ var appCmds = []cli.Command{
updateCmd,
readyCmd,
pingCmd,
odCmd,
}
func printMCVersion(c *cli.Context) {
+185
View File
@@ -0,0 +1,185 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"strings"
"time"
json "github.com/minio/colorjson"
madmin "github.com/minio/madmin-go"
humanize "github.com/dustin/go-humanize"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
)
// make a bucket.
var odCmd = cli.Command{
Name: "od",
Usage: "measure single stream upload and download",
Action: mainOD,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [OPERANDS]
OPERANDS:
if= Source stream to upload
of= Target path to upload to
size= Size of each part. If not specified, will be calculated from the source stream size.
parts= Number of parts to upload. If not specified, will calculated from the source file size.
skip= Number of parts to skip.
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
EXAMPLES:
1. Upload 200MiB of a file to a bucket in 5 parts of size 40MiB.
{{.HelpName}} if=file.txt of=play/my-bucket/file.txt size=40MiB parts=5
2. Upload a full file to a bucket with 40MiB parts.
{{.HelpName}} if=file.txt of=play/my-bucket/file.txt size=40MiB
3. Upload a full file to a bucket in 5 parts.
{{.HelpName}} if=file.txt of=play/my-bucket/file.txt parts=5
`,
}
type odMessage struct {
Status string `json:"status"`
Type string `json:"type"`
Source string `json:"source"`
Target string `json:"target"`
PartSize uint64 `json:"partSize"`
TotalSize int64 `json:"totalSize"`
Parts int `json:"parts"`
Skip int `json:"skip"`
Elapsed int64 `json:"elapsed"`
}
func (o odMessage) String() string {
cleanSize := humanize.IBytes(uint64(o.TotalSize))
elapsed := time.Duration(o.Elapsed) * time.Millisecond
speed := humanize.IBytes(uint64(float64(o.TotalSize) / elapsed.Seconds()))
if o.Type == "S3toFS" && o.Parts == 0 {
return fmt.Sprintf("Transferred: %s, Full file, Time: %s, Speed: %s/s", cleanSize, elapsed, speed)
}
return fmt.Sprintf("Transferred: %s, Parts: %d, Time: %s, Speed: %s/s", cleanSize, o.Parts, elapsed, speed)
}
func (o odMessage) JSON() string {
odMessageBytes, e := json.MarshalIndent(o, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(odMessageBytes)
}
// getOdUrls returns the URLs for the object download.
func getOdUrls(ctx context.Context, args madmin.KVS) (odURLs URLs, e error) {
inFile := args.Get("if")
outFile := args.Get("of")
// Check if outFile is a folder or a file.
opts := prepareCopyURLsOpts{
sourceURLs: []string{inFile},
targetURL: outFile,
}
odType, _, err := guessCopyURLType(ctx, opts)
fatalIf(err, "Unable to guess copy URL type")
// Get content of inFile, set up URLs.
switch odType {
case copyURLsTypeA:
odURLs = prepareOdUrls(ctx, inFile, "", outFile)
case copyURLsTypeB:
return URLs{}, fmt.Errorf("invalid source path %s, destination cannot be a directory", outFile)
default:
return URLs{}, fmt.Errorf("invalid source path %s, source cannot be a directory", inFile)
}
return odURLs, nil
}
func prepareOdUrls(ctx context.Context, sourceURL, sourceVersion string, targetURL string) URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
// Placeholder encryption key database
var encKeyDB map[string][]prefixSSEPair
_, sourceContent, err := url2Stat(ctx, sourceURL, sourceVersion, false, encKeyDB, time.Time{}, false)
if err != nil {
// Source does not exist or insufficient privileges.
return URLs{Error: err}
}
// All OK.. We can proceed. Type A
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL, encKeyDB)
}
// odCheckType checks if request is a download or upload and calls the appropriate function
func odCheckType(ctx context.Context, odURLs URLs, args madmin.KVS) (message, error) {
if odURLs.SourceAlias != "" && odURLs.TargetAlias == "" {
return odDownload(ctx, odURLs, args)
}
var odType string
if odURLs.SourceAlias == "" && odURLs.TargetAlias != "" {
odType = "FStoS3"
} else if odURLs.SourceAlias != "" && odURLs.TargetAlias != "" {
odType = "S3toS3"
} else {
odType = "FStoFS"
}
return odCopy(ctx, odURLs, args, odType)
}
// mainOd is the entry point for the od command.
func mainOD(cliCtx *cli.Context) error {
ctx, cancelCopy := context.WithCancel(globalContext)
defer cancelCopy()
if !cliCtx.Args().Present() {
cli.ShowCommandHelpAndExit(cliCtx, "od", 1) // last argument is exit code
}
var kvsArgs madmin.KVS
for _, arg := range cliCtx.Args() {
kv := strings.SplitN(arg, "=", 2)
kvsArgs.Set(kv[0], kv[1])
}
// Get content from source.
odURLs, e := getOdUrls(ctx, kvsArgs)
fatalIf(probe.NewError(e), "Unable to get source and target URLs")
message, e := odCheckType(ctx, odURLs, kvsArgs)
fatalIf(probe.NewError(e), "Unable to transfer object")
// Print message.
printMsg(message)
return nil
}
+287
View File
@@ -0,0 +1,287 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"io"
"math"
"path/filepath"
"strconv"
"time"
madmin "github.com/minio/madmin-go"
humanize "github.com/dustin/go-humanize"
)
// odSetSizes sets necessary values for object transfer.
func odSetSizes(odURLs URLs, args madmin.KVS) (combinedSize int64, partSize uint64, parts int, skip int64, e error) {
// If parts not specified, set to 0, else scan for integer.
p := args.Get("parts")
if p == "" {
parts = 0
} else {
parts, e = strconv.Atoi(p)
if e != nil {
return 0, 0, 0, 0, e
}
}
// Get number of parts to skip, defaults to 0.
sk := args.Get("skip")
var skipInt int
if sk == "" {
skipInt = 0
} else {
skipInt, e = strconv.Atoi(sk)
if e != nil {
return 0, 0, 0, 0, e
}
}
sourceSize := odURLs.SourceContent.Size
// If neither parts nor size is specified, copy full file in 1 part.
s := args.Get("size")
if parts <= 1 && s == "" {
return sourceSize, uint64(sourceSize), 1, 0, nil
}
// If size is not specified, calculate the size based on parts and upload full file.
if s == "" {
partSize = uint64(math.Ceil(float64(sourceSize) / float64(parts)))
skip = int64(skipInt) * int64(partSize)
parts = parts - skipInt
return -1, partSize, parts, skip, nil
}
partSize, e = humanize.ParseBytes(s)
if e != nil {
return 0, 0, 0, 0, e
}
// Convert skipInt to bytes.
skip = int64(skipInt) * int64(partSize)
// If source has no content, calculate combined size and return.
// This is needed for when source is /dev/zero.
if sourceSize == 0 {
if parts == 0 {
parts = 1
}
combinedSize = int64(partSize * uint64(parts))
return combinedSize, partSize, parts, skip, nil
}
// If source is smaller than part size, upload in 1 part.
if partSize > uint64(sourceSize) {
return sourceSize, uint64(sourceSize), 1, 0, nil
}
// If parts is not specified, calculate number of parts and upload full file.
if parts < 1 {
parts = int(math.Ceil(float64(sourceSize)/float64(partSize))) - skipInt
return sourceSize, partSize, parts, skip, nil
}
combinedSize = int64(partSize * uint64(parts))
// If combined size is larger than source after skip, recalculate number of parts.
if sourceSize-skip < combinedSize {
combinedSize = sourceSize - skip
parts = int(math.Ceil(float64(sourceSize)/float64(partSize))) - skipInt
}
return combinedSize, partSize, parts, skip, nil
}
// odCopy copies a file/object from local to server, server to server, or local to local.
func odCopy(ctx context.Context, odURLs URLs, args madmin.KVS, odType string) (odMessage, error) {
// Set sizes.
combinedSize, partSize, parts, skip, e := odSetSizes(odURLs, args)
if e != nil {
return odMessage{}, e
}
sourceAlias := odURLs.SourceAlias
sourceURL := odURLs.SourceContent.URL
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetAlias := odURLs.TargetAlias
targetURL := odURLs.TargetContent.URL
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
getOpts := GetOptions{}
// Skip given number of parts.
if skip > 0 {
getOpts.RangeStart = skip
}
// Placeholder encryption key database.
var encKeyDB map[string][]prefixSSEPair
// Create reader from source.
reader, err := getSourceStreamFromURL(ctx, sourcePath, encKeyDB, getSourceOpts{GetOptions: getOpts})
fatalIf(err, "Unable to get source stream")
defer reader.Close()
putOpts := PutOptions{
storageClass: odURLs.TargetContent.StorageClass,
md5: odURLs.MD5,
multipartSize: partSize,
}
// Disable multipart on files too small for multipart upload.
if combinedSize < 5242880 && combinedSize > 0 {
putOpts.disableMultipart = true
}
// Used to get transfer time
pg := newAccounter(combinedSize)
// Write to target.
targetClnt, err := newClientFromAlias(targetAlias, targetURL.String())
fatalIf(err, "Unable to initialize target client")
// Put object.
total, err := targetClnt.PutPart(ctx, reader, combinedSize, pg, putOpts)
fatalIf(err, "Unable to put object")
// Get upload time.
elapsed := time.Since(pg.startTime)
message := odMessage{
Status: "success",
Type: odType,
Source: sourcePath,
Target: targetPath,
PartSize: partSize,
TotalSize: total,
Parts: parts,
Skip: int(uint64(skip) / partSize),
Elapsed: elapsed.Milliseconds(),
}
return message, nil
}
// odSetParts sets parts for object download.
func odSetParts(odURLs URLs, args madmin.KVS) (parts int, skip int, e error) {
if args.Get("size") != "" {
return 0, 0, fmt.Errorf("size cannot be specified getting from server")
}
p := args.Get("parts")
if p == "" {
return 0, 0, nil
}
parts, e = strconv.Atoi(p)
if e != nil {
return 0, 0, e
}
if parts < 1 {
return 0, 0, fmt.Errorf("parts must be at least 1")
}
sk := args.Get("skip")
if sk == "" {
skip = 0
} else {
skip, e = strconv.Atoi(sk)
}
if e != nil {
return 0, 0, e
}
return parts, skip, nil
}
// odDownload copies an object from server to local.
func odDownload(ctx context.Context, odURLs URLs, args madmin.KVS) (odMessage, error) {
/// Set number of parts to get.
parts, skip, e := odSetParts(odURLs, args)
if e != nil {
return odMessage{}, e
}
targetPath := odURLs.TargetContent.URL.Path
sourceAlias := odURLs.SourceAlias
sourceURL := odURLs.SourceContent.URL
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
// Get server client.
cli, err := newClientFromAlias(sourceAlias, sourceURL.String())
fatalIf(err, "Unable to initialize client")
var reader io.Reader
if parts == 0 {
// Get the full file.
reader = singleGet(ctx, cli)
} else {
// Get the file in parts.
reader = multiGet(ctx, cli, parts, skip)
}
// Accounter to get transfer time.
pg := newAccounter(-1)
// Upload the file.
total, err := putTargetStream(ctx, "", targetPath, "", "", "",
reader, -1, pg, PutOptions{})
fatalIf(err, "Unable to download object")
// Get upload time.
elapsed := time.Since(pg.startTime)
message := odMessage{
Status: "success",
Type: "S3toFS",
Source: sourcePath,
Target: targetPath,
TotalSize: total,
Parts: parts,
Skip: skip,
Elapsed: elapsed.Milliseconds(),
}
return message, nil
}
// singleGet helps odDownload download a single part.
func singleGet(ctx context.Context, cli Client) io.ReadCloser {
reader, err := cli.GetPart(ctx, 0)
fatalIf(err, "Unable to get object reader")
return reader
}
// multiGet helps odDownload download multiple parts.
func multiGet(ctx context.Context, cli Client, parts, skip int) io.Reader {
var readers []io.Reader
// Get reader for each part.
for i := 1 + skip; i <= parts; i++ {
reader, err := cli.GetPart(ctx, parts)
fatalIf(err, "Unable to get object reader")
readers = append(readers, reader)
}
reader := io.MultiReader(readers...)
return reader
}