Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e9625733d | ||
|
|
1513d76ca9 | ||
|
|
87dc0bf80e | ||
|
|
69c0d33543 | ||
|
|
8d891755e0 | ||
|
|
a9cd7869eb | ||
|
|
c40ab338a3 | ||
|
|
0fcd10d793 | ||
|
|
b7b75c5f46 | ||
|
|
b97b7b8987 | ||
|
|
8f3d514e3b | ||
|
|
bb3c0d45f2 | ||
|
|
9ebde383d4 | ||
|
|
cfea4fdc75 | ||
|
|
dd47bdfeaa | ||
|
|
ec9b92cbb7 | ||
|
|
975423abe2 | ||
|
|
3dd971f673 | ||
|
|
133dd1f7da | ||
|
|
bdefdc0169 | ||
|
|
c51e3b3ec9 | ||
|
|
88223f96be | ||
|
|
fa520cbd1a | ||
|
|
166db95464 | ||
|
|
0e27dd4ed4 | ||
|
|
2403e7a744 | ||
|
|
ea03e61fac | ||
|
|
f55e9c1997 | ||
|
|
7664bb2c8d | ||
|
|
09f832f597 | ||
|
|
4cc297ba4e | ||
|
|
bf731558cd | ||
|
|
949dd282f9 | ||
|
|
61b74e90bf | ||
|
|
3b479cf92e | ||
|
|
09c31c4ab2 | ||
|
|
71196b1013 | ||
|
|
72c8e92459 | ||
|
|
a6d82862cd | ||
|
|
672390b86a | ||
|
|
2e586e6b9d | ||
|
|
ad0bc4c33d | ||
|
|
a75dca16bd | ||
|
|
4e3b501528 | ||
|
|
dc2ad27429 | ||
|
|
b99c313366 | ||
|
|
e13751f5d5 | ||
|
|
ca650e227a | ||
|
|
df8bb795ba | ||
|
|
2fe7d04043 | ||
|
|
138d7656ba | ||
|
|
2018319125 | ||
|
|
c8c5c15249 | ||
|
|
32d8ef24ef | ||
|
|
f82a7b13c1 | ||
|
|
49c2beec79 | ||
|
|
24a72e4a33 | ||
|
|
c7166eac3a | ||
|
|
20dd7011b9 | ||
|
|
f23f814764 | ||
|
|
e1617a504b | ||
|
|
89930fed29 | ||
|
|
8c262e1f3f | ||
|
|
e6a6cfcebf | ||
|
|
bb43b2adf1 | ||
|
|
2d6a960f94 |
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Bug report template
|
||||
title: ''
|
||||
labels: community, triage
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Expected behavior
|
||||
|
||||
## Actual behavior
|
||||
|
||||
## Steps to reproduce the behavior
|
||||
|
||||
## mc --version
|
||||
- (paste output of `mc --version`)
|
||||
|
||||
## System information
|
||||
@@ -0,0 +1,39 @@
|
||||
# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app
|
||||
|
||||
# Number of days of inactivity before a closed issue or pull request is locked
|
||||
daysUntilLock: 365
|
||||
|
||||
# Skip issues and pull requests created before a given timestamp. Timestamp must
|
||||
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
|
||||
skipCreatedBefore: false
|
||||
|
||||
# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
|
||||
exemptLabels: []
|
||||
|
||||
# Label to add before locking, such as `outdated`. Set to `false` to disable
|
||||
lockLabel: false
|
||||
|
||||
# Comment to post before locking. Set to `false` to disable
|
||||
lockComment: >-
|
||||
|
||||
This thread has been automatically locked since there has not been
|
||||
any recent activity after it was closed. Please open a new issue for
|
||||
related bugs.
|
||||
|
||||
# Assign `resolved` as the reason for locking. Set to `false` to disable
|
||||
setLockReason: true
|
||||
|
||||
# Limit to only `issues` or `pulls`
|
||||
only: issues
|
||||
|
||||
# Optionally, specify configuration settings just for `issues` or `pulls`
|
||||
# issues:
|
||||
# exemptLabels:
|
||||
# - help-wanted
|
||||
# lockLabel: outdated
|
||||
|
||||
# pulls:
|
||||
# daysUntilLock: 30
|
||||
|
||||
# Repository to extend settings from
|
||||
# _extends: repo
|
||||
@@ -0,0 +1,59 @@
|
||||
# Configuration for probot-stale - https://github.com/probot/stale
|
||||
|
||||
# Number of days of inactivity before an Issue or Pull Request becomes stale
|
||||
daysUntilStale: 90
|
||||
|
||||
# Number of days of inactivity before an Issue or Pull Request with the stale label is closed.
|
||||
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
|
||||
daysUntilClose: 30
|
||||
|
||||
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
|
||||
onlyLabels: []
|
||||
|
||||
# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
|
||||
exemptLabels:
|
||||
- "security"
|
||||
- "pending discussion"
|
||||
|
||||
# Set to true to ignore issues in a project (defaults to false)
|
||||
exemptProjects: false
|
||||
|
||||
# Set to true to ignore issues in a milestone (defaults to false)
|
||||
exemptMilestones: false
|
||||
|
||||
# Set to true to ignore issues with an assignee (defaults to false)
|
||||
exemptAssignees: false
|
||||
|
||||
# Label to use when marking as stale
|
||||
staleLabel: stale
|
||||
|
||||
# Comment to post when marking as stale. Set to `false` to disable
|
||||
markComment: >-
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed after 21 days if no further activity
|
||||
occurs. Thank you for your contributions.
|
||||
# Comment to post when removing the stale label.
|
||||
# unmarkComment: >
|
||||
# Your comment here.
|
||||
|
||||
# Comment to post when closing a stale Issue or Pull Request.
|
||||
# closeComment: >
|
||||
# Your comment here.
|
||||
|
||||
# Limit the number of actions per hour, from 1-30. Default is 30
|
||||
limitPerRun: 1
|
||||
|
||||
# Limit to only `issues` or `pulls`
|
||||
# only: issues
|
||||
|
||||
# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls':
|
||||
# pulls:
|
||||
# daysUntilStale: 30
|
||||
# markComment: >
|
||||
# This pull request has been automatically marked as stale because it has not had
|
||||
# recent activity. It will be closed if no further activity occurs. Thank you
|
||||
# for your contributions.
|
||||
|
||||
# issues:
|
||||
# exemptLabels:
|
||||
# - confirmed
|
||||
@@ -0,0 +1,52 @@
|
||||
name: "Code scanning - action"
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
schedule:
|
||||
- cron: '0 19 * * 0'
|
||||
|
||||
jobs:
|
||||
CodeQL-Build:
|
||||
|
||||
# CodeQL runs on ubuntu-latest and windows-latest
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
# We must fetch at least the immediate parents so that if this is
|
||||
# a pull request then we can checkout the head.
|
||||
fetch-depth: 2
|
||||
|
||||
# If this run was triggered by a pull request event, then checkout
|
||||
# the head of the pull request instead of the merge commit.
|
||||
- run: git checkout HEAD^2
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v1
|
||||
# Override language selection by uncommenting this and choosing your languages
|
||||
# with:
|
||||
# languages: go, javascript, csharp, python, cpp, java
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v1
|
||||
@@ -30,14 +30,18 @@ jobs:
|
||||
if: matrix.os == 'windows-latest'
|
||||
env:
|
||||
GO111MODULE: on
|
||||
run: go test -v -race ./...
|
||||
run: |
|
||||
go build --ldflags="-s -w" -o %GOPATH%\bin\mc.exe
|
||||
go test -v -race --timeout 30m ./...
|
||||
- name: Build on ${{ matrix.os }}
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
env:
|
||||
GO111MODULE: on
|
||||
run: |
|
||||
make
|
||||
diff -au <(gofmt -d *.go) <(printf "")
|
||||
diff -au <(gofmt -d cmd) <(printf "")
|
||||
diff -au <(gofmt -d pkg) <(printf "")
|
||||
go test -v -race ./...
|
||||
make test
|
||||
diff -au <(gofmt -s -d cmd) <(printf "")
|
||||
diff -au <(gofmt -s -d pkg) <(printf "")
|
||||
make test-race
|
||||
make verify
|
||||
make crosscompile
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
linters-settings:
|
||||
golint:
|
||||
min-confidence: 0
|
||||
|
||||
misspell:
|
||||
locale: US
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- typecheck
|
||||
- goimports
|
||||
- misspell
|
||||
- govet
|
||||
- golint
|
||||
- ineffassign
|
||||
- gosimple
|
||||
- deadcode
|
||||
- structcheck
|
||||
|
||||
issues:
|
||||
exclude-use-default: false
|
||||
exclude:
|
||||
- instead of using struct literal
|
||||
- should have a package comment
|
||||
- error strings should not be capitalized or end with punctuation or a newline
|
||||
service:
|
||||
golangci-lint-version: 1.20.0 # use the fixed version to not introduce new linters unexpectedly
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
project_name: mc
|
||||
|
||||
release:
|
||||
name_template: "Version {{.Version}}"
|
||||
disable: true
|
||||
github:
|
||||
owner: minio
|
||||
name: mc
|
||||
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
- GO111MODULE=on
|
||||
|
||||
before:
|
||||
hooks:
|
||||
- make clean
|
||||
- go generate ./...
|
||||
- go mod tidy
|
||||
- go mod download
|
||||
|
||||
builds:
|
||||
-
|
||||
goos:
|
||||
- linux
|
||||
- darwin
|
||||
- windows
|
||||
- freebsd
|
||||
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
- arm
|
||||
- ppc64le
|
||||
- s390x
|
||||
|
||||
goarm:
|
||||
- 7
|
||||
|
||||
ignore:
|
||||
- goos: darwin
|
||||
goarch: arm64
|
||||
- goos: darwin
|
||||
goarch: arm
|
||||
- goos: darwin
|
||||
goarch: ppc64le
|
||||
- goos: darwin
|
||||
goarch: s390x
|
||||
- goos: windows
|
||||
goarch: arm64
|
||||
- goos: windows
|
||||
goarch: arm
|
||||
- goos: windows
|
||||
goarch: ppc64le
|
||||
- goos: windows
|
||||
goarch: s390x
|
||||
- goos: freebsd
|
||||
goarch: arm
|
||||
- goos: freebsd
|
||||
goarch: arm64
|
||||
- goos: freebsd
|
||||
goarch: ppc64le
|
||||
- goos: freebsd
|
||||
goarch: s390x
|
||||
|
||||
flags:
|
||||
- -tags=kqueue
|
||||
- -trimpath
|
||||
|
||||
ldflags:
|
||||
- "-s -w -X github.com/minio/mc/cmd.Version={{.Version}} -X github.com/minio/mc/cmd.ReleaseTag={{.Tag}} -X github.com/minio/mc/cmd.CommitID={{.FullCommit}} -X github.com/minio/mc/cmd.ShortCommitID={{.ShortCommit}}"
|
||||
|
||||
archives:
|
||||
-
|
||||
format: binary
|
||||
name_template: "{{ .Binary }}-release/{{ .Os }}-{{ .Arch }}/{{ .Binary }}.{{ .Version }}"
|
||||
|
||||
nfpms:
|
||||
-
|
||||
id: minio
|
||||
package_name: mc
|
||||
vendor: MinIO, Inc.
|
||||
homepage: https://min.io/
|
||||
maintainer: dev@min.io
|
||||
description: MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
|
||||
license: Apache 2.0
|
||||
bindir: /usr/bin
|
||||
formats:
|
||||
- deb
|
||||
- rpm
|
||||
overrides:
|
||||
deb:
|
||||
file_name_template: "{{ .Binary }}-release/debs/{{ .ProjectName }}-{{ .Version }}_{{ .Arch }}"
|
||||
replacements:
|
||||
arm: armv7
|
||||
files:
|
||||
"NOTICE": "/usr/share/mc/NOTICE"
|
||||
"CREDITS": "/usr/share/mc/CREDITS"
|
||||
"LICENSE": "/usr/share/mc/LICENSE"
|
||||
"README.md": "/usr/share/mc/README.md"
|
||||
rpm:
|
||||
file_name_template: "{{ .Binary }}-release/rpms/{{ .ProjectName }}-{{ .Version }}.{{ .Arch }}"
|
||||
replacements:
|
||||
amd64: x86_64
|
||||
arm64: aarch64
|
||||
arm: armv7
|
||||
files:
|
||||
"NOTICE": "/usr/share/mc/NOTICE"
|
||||
"CREDITS": "/usr/share/mc/CREDITS"
|
||||
"LICENSE": "/usr/share/mc/LICENSE"
|
||||
"README.md": "/usr/share/mc/README.md"
|
||||
|
||||
checksum:
|
||||
algorithm: sha256
|
||||
|
||||
signs:
|
||||
-
|
||||
signature: "${artifact}.asc"
|
||||
cmd: "sh"
|
||||
args:
|
||||
- '-c'
|
||||
- 'gpg --quiet --detach-sign -a ${artifact}'
|
||||
artifacts: all
|
||||
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- '^Update yaml files'
|
||||
|
||||
dockers:
|
||||
-
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
dockerfile: Dockerfile.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}
|
||||
- minio/mc:latest
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: ppc64le
|
||||
dockerfile: Dockerfile.ppc64le.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-ppc64le
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: s390x
|
||||
dockerfile: Dockerfile.s390x.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-s390x
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
goarm: ''
|
||||
dockerfile: Dockerfile.arm64.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-arm64
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: arm
|
||||
goarm: '7'
|
||||
dockerfile: Dockerfile.arm.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-arm
|
||||
+5
-5
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.13-alpine
|
||||
FROM golang:1.13-alpine as build
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
@@ -11,12 +11,12 @@ RUN \
|
||||
git clone https://github.com/minio/mc && cd mc && \
|
||||
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
|
||||
|
||||
FROM alpine:3.10
|
||||
FROM alpine:3.12
|
||||
|
||||
COPY --from=0 /go/bin/mc /usr/bin/mc
|
||||
COPY --from=build /go/bin/mc /usr/bin/mc
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf
|
||||
apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/master/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM arm32v7/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM arm64v8/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
+3
-5
@@ -1,10 +1,8 @@
|
||||
FROM alpine:3.10
|
||||
FROM alpine:3.12
|
||||
|
||||
COPY mc /usr/bin/
|
||||
COPY CREDITS /
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf \
|
||||
chmod +x /usr/bin/mc
|
||||
RUN apk add --no-cache ca-certificates
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM ppc64le/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
+5
-6
@@ -1,11 +1,10 @@
|
||||
FROM alpine:3.10
|
||||
FROM alpine:3.12
|
||||
|
||||
MAINTAINER MinIO Inc <dev@min.io>
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
apk add --no-cache --virtual .build-deps curl && \
|
||||
curl https://dl.min.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc && apk del .build-deps
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM s390x/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -18,18 +18,12 @@ checks:
|
||||
|
||||
getdeps:
|
||||
@mkdir -p ${GOPATH}/bin
|
||||
@which golint 1>/dev/null || (echo "Installing golint" && GO111MODULE=off go get -u golang.org/x/lint/golint)
|
||||
ifeq ($(GOARCH),s390x)
|
||||
@which staticcheck 1>/dev/null || (echo "Installing staticcheck" && GO111MODULE=off go get honnef.co/go/tools/cmd/staticcheck)
|
||||
else
|
||||
@which staticcheck 1>/dev/null || (echo "Installing staticcheck" && wget --quiet https://github.com/dominikh/go-tools/releases/download/2019.2.3/staticcheck_${GOOS}_${GOARCH}.tar.gz && tar xf staticcheck_${GOOS}_${GOARCH}.tar.gz && mv staticcheck/staticcheck ${GOPATH}/bin/staticcheck && chmod +x ${GOPATH}/bin/staticcheck && rm -f staticcheck_${GOOS}_${GOARCH}.tar.gz && rm -rf staticcheck)
|
||||
endif
|
||||
@which misspell 1>/dev/null || (echo "Installing misspell" && GO111MODULE=off go get -u github.com/client9/misspell/cmd/misspell)
|
||||
@which golangci-lint 1>/dev/null || (echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.27.0)
|
||||
|
||||
crosscompile:
|
||||
@(env bash $(PWD)/buildscripts/cross-compile.sh)
|
||||
|
||||
verifiers: getdeps vet fmt lint staticcheck spelling
|
||||
verifiers: getdeps vet fmt lint
|
||||
|
||||
docker: build
|
||||
@docker build -t $(TAG) . -f Dockerfile.dev
|
||||
@@ -44,19 +38,9 @@ fmt:
|
||||
@GO111MODULE=on gofmt -d pkg/
|
||||
|
||||
lint:
|
||||
@echo "Running $@"
|
||||
@GO111MODULE=on ${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/cmd/...
|
||||
@GO111MODULE=on ${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/pkg/...
|
||||
|
||||
staticcheck:
|
||||
@echo "Running $@"
|
||||
@GO111MODULE=on ${GOPATH}/bin/staticcheck github.com/minio/mc/cmd/...
|
||||
@GO111MODULE=on ${GOPATH}/bin/staticcheck github.com/minio/mc/pkg/...
|
||||
|
||||
spelling:
|
||||
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find cmd/`
|
||||
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find pkg/`
|
||||
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find docs/`
|
||||
@echo "Running $@ check"
|
||||
@GO111MODULE=on ${GOPATH}/bin/golangci-lint cache clean
|
||||
@GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml
|
||||
|
||||
# Builds mc, runs the verifiers then runs the tests.
|
||||
check: test
|
||||
@@ -66,9 +50,16 @@ test: verifiers build
|
||||
@echo "Running functional tests"
|
||||
@(env bash $(PWD)/functional-tests.sh)
|
||||
|
||||
coverage: build
|
||||
@echo "Running all coverage for MinIO"
|
||||
@(env bash $(PWD)/buildscripts/go-coverage.sh)
|
||||
test-race: verifiers build
|
||||
@echo "Running unit tests under -race"
|
||||
@GO111MODULE=on go test -race -v --timeout 20m ./... 1>/dev/null
|
||||
|
||||
# Verify mc binary
|
||||
verify:
|
||||
@echo "Verifying build with race"
|
||||
@GO111MODULE=on CGO_ENABLED=1 go build -race -tags kqueue -trimpath --ldflags "$(LDFLAGS)" -o $(PWD)/mc 1>/dev/null
|
||||
@echo "Running functional tests"
|
||||
@(env bash $(PWD)/functional-tests.sh)
|
||||
|
||||
# Builds mc locally.
|
||||
build: checks
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
MinIO Client (C) 2014, 2015 MinIO, Inc.
|
||||
MinIO Client (C) 2014-2020 MinIO, Inc.
|
||||
|
||||
This product includes software developed at MinIO, Inc.
|
||||
(https://min.io/).
|
||||
|
||||
@@ -8,7 +8,7 @@ function _init() {
|
||||
export CGO_ENABLED=0
|
||||
|
||||
## List of architectures and OS to test coss compilation.
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386"
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386 windows/amd64"
|
||||
}
|
||||
|
||||
function _build() {
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
|
||||
GO111MODULE=on CGO_ENABLED=0 go test -v -coverprofile=coverage.txt -covermode=atomic ./...
|
||||
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 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 cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminQuotaFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "fifo",
|
||||
Usage: "set fifo quota, allowing automatic deletion of older content",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "hard",
|
||||
Usage: "set a hard quota, disallowing writes after quota is reached",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "clear",
|
||||
Usage: "clears bucket quota configured for bucket",
|
||||
},
|
||||
}
|
||||
|
||||
// quotaMessage container for content message structure
|
||||
type quotaMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Quota uint64 `json:"quota,omitempty"`
|
||||
QuotaType string `json:"type,omitempty"`
|
||||
}
|
||||
|
||||
func (q quotaMessage) String() string {
|
||||
switch q.op {
|
||||
case "set":
|
||||
return console.Colorize("QuotaMessage",
|
||||
fmt.Sprintf("Successfully set bucket quota of %s with %s type on `%s`", humanize.IBytes(q.Quota), q.QuotaType, q.Bucket))
|
||||
case "unset":
|
||||
return console.Colorize("QuotaMessage",
|
||||
fmt.Sprintf("Successfully cleared bucket quota configured on `%s`", q.Bucket))
|
||||
default:
|
||||
return console.Colorize("QuotaInfo",
|
||||
fmt.Sprintf("Bucket `%s` has %s quota of %s", q.Bucket, q.QuotaType, humanize.IBytes(q.Quota)))
|
||||
}
|
||||
}
|
||||
|
||||
func (q quotaMessage) JSON() string {
|
||||
jsonMessageBytes, e := json.MarshalIndent(q, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
var adminBucketQuotaCmd = cli.Command{
|
||||
Name: "quota",
|
||||
Usage: "Manage bucket quota",
|
||||
Action: mainAdminBucketQuota,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminQuotaFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [--fifo QUOTA | --hard QUOTA | --clear]
|
||||
|
||||
QUOTA
|
||||
quota accepts human-readable case-insensitive number
|
||||
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
|
||||
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
|
||||
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
|
||||
also accepted. Without suffixes the unit is bytes.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Display bucket quota configured for "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
|
||||
2. Set FIFO quota for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 64kB
|
||||
|
||||
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1gb
|
||||
|
||||
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketQuotaSyntax - validate all the passed arguments
|
||||
func checkAdminBucketQuotaSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "quota", 1) // last argument is exit code
|
||||
}
|
||||
|
||||
if ctx.IsSet("hard") && ctx.IsSet("fifo") {
|
||||
fatalIf(errInvalidArgument(), "Only one of --hard or --fifo flags can be set")
|
||||
}
|
||||
if (ctx.IsSet("hard") || ctx.IsSet("fifo")) && len(ctx.Args()) == 0 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "please specify bucket and quota")
|
||||
}
|
||||
if ctx.IsSet("clear") && len(ctx.Args()) == 0 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "clear flag must be passed with target alone")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminBucketQuota is the handler for "mc admin bucket quota" command.
|
||||
func mainAdminBucketQuota(ctx *cli.Context) error {
|
||||
checkAdminBucketQuotaSyntax(ctx)
|
||||
|
||||
console.SetColor("QuotaMessage", color.New(color.FgGreen))
|
||||
console.SetColor("QuotaInfo", color.New(color.FgBlue))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
quotaStr := ctx.String("fifo")
|
||||
if ctx.IsSet("hard") {
|
||||
quotaStr = ctx.String("hard")
|
||||
}
|
||||
_, targetURL := url2Alias(args[0])
|
||||
if ctx.IsSet("fifo") || ctx.IsSet("hard") && len(args) == 1 {
|
||||
qType := madmin.FIFOQuota
|
||||
if ctx.IsSet("hard") {
|
||||
qType = madmin.HardQuota
|
||||
}
|
||||
quota, e := humanize.ParseBytes(quotaStr)
|
||||
fatalIf(probe.NewError(e).Trace(quotaStr), "Unable to parse quota")
|
||||
if e = client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{Quota: quota, Type: qType}); e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to set bucket quota")
|
||||
}
|
||||
printMsg(quotaMessage{
|
||||
op: "set",
|
||||
Bucket: targetURL,
|
||||
Quota: quota,
|
||||
QuotaType: string(qType),
|
||||
Status: "success",
|
||||
})
|
||||
} else if ctx.Bool("clear") && len(args) == 1 {
|
||||
if err := client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{}); err != nil {
|
||||
fatalIf(probe.NewError(err).Trace(args...), "Unable to clear bucket quota config")
|
||||
}
|
||||
printMsg(quotaMessage{
|
||||
op: "unset",
|
||||
Bucket: targetURL,
|
||||
Status: "success",
|
||||
})
|
||||
|
||||
} else {
|
||||
qCfg, e := client.GetBucketQuota(globalContext, targetURL)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket quota")
|
||||
printMsg(quotaMessage{
|
||||
op: "get",
|
||||
Bucket: targetURL,
|
||||
Quota: qCfg.Quota,
|
||||
QuotaType: string(qCfg.Type),
|
||||
Status: "success",
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 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 cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminBucketCmd = cli.Command{
|
||||
Name: "bucket",
|
||||
Usage: "manage buckets defined in the MinIO server",
|
||||
Action: mainAdminBucket,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminBucketQuotaCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminBucket is the handle for "mc admin bucket" command.
|
||||
func mainAdminBucket(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "quota", "usage" have their own main.
|
||||
}
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
var adminConfigExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "export all config keys to STDOUT",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigExport,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
var adminConfigGetCmd = cli.Command{
|
||||
Name: "get",
|
||||
Usage: "interactively retrieve a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigGet,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -43,7 +43,7 @@ var historyListFlags = []cli.Flag{
|
||||
var adminConfigHistoryCmd = cli.Command{
|
||||
Name: "history",
|
||||
Usage: "show all historic configuration changes",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigHistory,
|
||||
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -30,7 +30,7 @@ import (
|
||||
var adminConfigImportCmd = cli.Command{
|
||||
Name: "import",
|
||||
Usage: "import multiple config keys from STDIN",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigImport,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -37,7 +37,7 @@ var adminConfigEnvFlags = []cli.Flag{
|
||||
var adminConfigResetCmd = cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "interactively reset a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigReset,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -64,7 +64,7 @@ type configResetMessage struct {
|
||||
// String colorized service status message.
|
||||
func (u configResetMessage) String() (msg string) {
|
||||
msg += console.Colorize("ResetConfigSuccess",
|
||||
"Reseteting key has been successful.\n")
|
||||
"Key is successfully reset.\n")
|
||||
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("ResetConfigSuccess",
|
||||
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
|
||||
|
||||
@@ -29,7 +29,7 @@ import (
|
||||
var adminConfigRestoreCmd = cli.Command{
|
||||
Name: "restore",
|
||||
Usage: "rollback back changes to a specific config history",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigRestore,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -31,7 +31,7 @@ import (
|
||||
var adminConfigSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "interactively set a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigSet,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminConfigCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "manage MinIO server configuration",
|
||||
Action: mainAdminConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminConfigGetCmd,
|
||||
|
||||
@@ -49,7 +49,7 @@ var adminConsoleCmd = cli.Command{
|
||||
Name: "console",
|
||||
Usage: "show console logs for MinIO server",
|
||||
Action: mainAdminConsole,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminConsoleFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -185,8 +185,7 @@ func mainAdminConsole(ctx *cli.Context) error {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "please set a proper limit, for example: '--limit 5' to display last 5 logs, omit this flag to display all available logs")
|
||||
}
|
||||
}
|
||||
var logType string
|
||||
logType = strings.ToLower(ctx.String("type"))
|
||||
logType := strings.ToLower(ctx.String("type"))
|
||||
if logType != "minio" && logType != "application" && logType != "all" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Invalid value for --type flag. Valid options are [minio, application, all]")
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ var adminGroupAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add users to a new or existing group",
|
||||
Action: mainAdminGroupAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -24,7 +24,7 @@ var adminGroupDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "Disable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -30,7 +30,7 @@ var adminGroupEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "Enable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -27,7 +27,7 @@ var adminGroupInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display group info",
|
||||
Action: mainAdminGroupInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -27,7 +27,7 @@ var adminGroupListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "display list of groups",
|
||||
Action: mainAdminGroupList,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -28,7 +28,7 @@ var adminGroupRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove group or members from a group",
|
||||
Action: mainAdminGroupRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminGroupCmd = cli.Command{
|
||||
Name: "group",
|
||||
Usage: "manage groups",
|
||||
Action: mainAdminGroup,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminGroupAddCmd,
|
||||
|
||||
+2
-2
@@ -67,7 +67,7 @@ var adminHealCmd = cli.Command{
|
||||
Name: "heal",
|
||||
Usage: "heal disks, buckets and objects on MinIO server",
|
||||
Action: mainAdminHeal,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminHealFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -221,7 +221,7 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
fatalIf(err.Trace(clnt.GetURL().String()), "Unable to create client for URL ", aliasedURL)
|
||||
return nil
|
||||
}
|
||||
for content := range clnt.List(false, false, false, DirNone) {
|
||||
for content := range clnt.List(globalContext, false, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
|
||||
return nil
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ var adminInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display MinIO server information",
|
||||
Action: mainAdminInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -28,7 +28,7 @@ var adminKMSKeyStatusCmd = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "request status information for a KMS master key",
|
||||
Action: mainAdminKMSKeyStatus,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminKMSKeyCmd = cli.Command{
|
||||
Name: "key",
|
||||
Usage: "Manage KMS master keys: Request key status information",
|
||||
Action: mainAdminKMSKey,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminKMSKeyStatusCmd,
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminKMSCmd = cli.Command{
|
||||
Name: "kms",
|
||||
Usage: "perform KMS management operations",
|
||||
Action: mainAdminKMS,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminKMSKeyCmd,
|
||||
|
||||
+1
-1
@@ -34,7 +34,6 @@ var adminCmd = cli.Command{
|
||||
Usage: "manage MinIO servers",
|
||||
Action: mainAdmin,
|
||||
HideHelpCommand: true,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
adminServiceCmd,
|
||||
@@ -52,6 +51,7 @@ var adminCmd = cli.Command{
|
||||
adminPrometheusCmd,
|
||||
adminKMSCmd,
|
||||
adminOBDCmd,
|
||||
adminBucketCmd,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ var adminOBDCmd = cli.Command{
|
||||
Name: "obd",
|
||||
Usage: "run on-board diagnostics",
|
||||
Action: mainAdminOBD,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminOBDFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -33,7 +33,7 @@ var adminPolicyAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add new policy",
|
||||
Action: mainAdminPolicyAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -29,7 +29,7 @@ var adminPolicyInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "show info on a policy",
|
||||
Action: mainAdminPolicyInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -27,7 +27,7 @@ var adminPolicyListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "list all policies",
|
||||
Action: mainAdminPolicyList,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -27,7 +27,7 @@ var adminPolicyRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove policy",
|
||||
Action: mainAdminPolicyRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -30,7 +30,7 @@ var adminPolicySetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "set IAM policy on a user or group",
|
||||
Action: mainAdminPolicySet,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminPolicyCmd = cli.Command{
|
||||
Name: "policy",
|
||||
Usage: "manage policies defined in the MinIO server",
|
||||
Action: mainAdminPolicy,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminPolicyAddCmd,
|
||||
|
||||
@@ -38,7 +38,7 @@ var adminProfileStartCmd = cli.Command{
|
||||
Name: "start",
|
||||
Usage: "start recording profile data",
|
||||
Action: mainAdminProfileStart,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminProfileStartFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -31,7 +31,7 @@ var adminProfileStopCmd = cli.Command{
|
||||
Name: "stop",
|
||||
Usage: "stop and download profile data",
|
||||
Action: mainAdminProfileStop,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -24,7 +24,6 @@ var adminProfileCmd = cli.Command{
|
||||
Name: "profile",
|
||||
Usage: "generate profile data for debugging purposes",
|
||||
Action: mainAdminProfile,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminProfileStartCmd,
|
||||
|
||||
@@ -40,7 +40,7 @@ var adminPrometheusGenerateCmd = cli.Command{
|
||||
Name: "generate",
|
||||
Usage: "generates prometheus config",
|
||||
Action: mainAdminPrometheusGenerate,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -138,7 +138,7 @@ func checkAdminPrometheusSyntax(ctx *cli.Context) {
|
||||
func generatePrometheusConfig(ctx *cli.Context) error {
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
alias := args.Get(0)
|
||||
alias := cleanAlias(args.Get(0))
|
||||
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errInvalidAlias(alias), "Invalid alias.")
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminPrometheusCmd = cli.Command{
|
||||
Name: "prometheus",
|
||||
Usage: "manages prometheus config",
|
||||
Action: mainAdminPrometheus,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Subcommands: []cli.Command{
|
||||
|
||||
@@ -30,7 +30,7 @@ var adminServiceRestartCmd = cli.Command{
|
||||
Name: "restart",
|
||||
Usage: "restart all MinIO servers",
|
||||
Action: mainAdminServiceRestart,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -28,7 +28,7 @@ var adminServiceStopCmd = cli.Command{
|
||||
Name: "stop",
|
||||
Usage: "stop MinIO server",
|
||||
Action: mainAdminServiceStop,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminServiceCmd = cli.Command{
|
||||
Name: "service",
|
||||
Usage: "restart and stop all MinIO servers",
|
||||
Action: mainAdminService,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Subcommands: []cli.Command{
|
||||
|
||||
@@ -31,7 +31,7 @@ import (
|
||||
var adminTopLocksCmd = cli.Command{
|
||||
Name: "locks",
|
||||
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminTopLocks,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminTopCmd = cli.Command{
|
||||
Name: "top",
|
||||
Usage: "provide top like statistics for MinIO",
|
||||
Action: mainAdminTop,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminTopLocksCmd,
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ var adminTraceCmd = cli.Command{
|
||||
Name: "trace",
|
||||
Usage: "show http trace for MinIO server",
|
||||
Action: mainAdminTrace,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminTraceFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ var adminServerUpdateCmd = cli.Command{
|
||||
Name: "update",
|
||||
Usage: "update all MinIO servers",
|
||||
Action: mainAdminServerUpdate,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -34,7 +34,7 @@ var adminUserAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new user",
|
||||
Action: mainAdminUserAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -28,7 +28,7 @@ var adminUserDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable user",
|
||||
Action: mainAdminUserDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -28,7 +28,7 @@ var adminUserEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable user",
|
||||
Action: mainAdminUserEnable,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -27,7 +27,7 @@ var adminUserInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display info of a user",
|
||||
Action: mainAdminUserInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -27,7 +27,7 @@ var adminUserListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "list all users",
|
||||
Action: mainAdminUserList,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -27,7 +27,7 @@ var adminUserRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove user",
|
||||
Action: mainAdminUserRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -22,7 +22,6 @@ var adminUserCmd = cli.Command{
|
||||
Name: "user",
|
||||
Usage: "manage users",
|
||||
Action: mainAdminUser,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminUserAddCmd,
|
||||
|
||||
+38
-17
@@ -29,7 +29,31 @@ import (
|
||||
// fsComplete knows how to complete file/dir names by the given path
|
||||
type fsComplete struct{}
|
||||
|
||||
func (fs fsComplete) Predict(a complete.Args) (prediction []string) {
|
||||
// predictPathWithTilde completes an FS path which starts with a `~/`
|
||||
func (fs fsComplete) predictPathWithTilde(a complete.Args) []string {
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil || homeDir == "" {
|
||||
return nil
|
||||
}
|
||||
// Clean the home directory path
|
||||
homeDir = strings.TrimRight(homeDir, "/")
|
||||
|
||||
// Replace the first occurrence of ~ with the real path and complete
|
||||
a.Last = strings.Replace(a.Last, "~", homeDir, 1)
|
||||
predictions := complete.PredictFiles("*").Predict(a)
|
||||
|
||||
// Restore ~ to avoid disturbing the completion user experience
|
||||
for i := range predictions {
|
||||
predictions[i] = strings.Replace(predictions[i], homeDir, "~", 1)
|
||||
}
|
||||
|
||||
return predictions
|
||||
}
|
||||
|
||||
func (fs fsComplete) Predict(a complete.Args) []string {
|
||||
if strings.HasPrefix(a.Last, "~/") {
|
||||
return fs.predictPathWithTilde(a)
|
||||
}
|
||||
return complete.PredictFiles("*").Predict(a)
|
||||
}
|
||||
|
||||
@@ -72,7 +96,7 @@ func completeS3Path(s3Path string) (prediction []string) {
|
||||
|
||||
// List dirPath content and only pick elements that corresponds
|
||||
// to the path that we want to complete
|
||||
for content := range clnt.List(false, false, false, DirFirst) {
|
||||
for content := range clnt.List(globalContext, false, false, false, DirFirst) {
|
||||
cmplS3Path := alias + getKey(content)
|
||||
if content.Type.IsDir() {
|
||||
if !strings.HasSuffix(cmplS3Path, "/") {
|
||||
@@ -228,6 +252,10 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/event/list": aliasCompleter,
|
||||
"/event/remove": aliasCompleter,
|
||||
|
||||
"/tag/list": s3Completer,
|
||||
"/tag/remove": s3Completer,
|
||||
"/tag/set": s3Completer,
|
||||
|
||||
"/share/download": s3Completer,
|
||||
"/share/list": nil,
|
||||
"/share/upload": s3Completer,
|
||||
@@ -235,18 +263,15 @@ var completeCmds = map[string]complete.Predictor{
|
||||
// Admin API commands MinIO only.
|
||||
"/admin/heal": s3Completer,
|
||||
|
||||
"/admin/info/server": aliasCompleter,
|
||||
"/admin/info/cpu": aliasCompleter,
|
||||
"/admin/info/mem": aliasCompleter,
|
||||
"/admin/info": aliasCompleter,
|
||||
|
||||
"/admin/config/get": adminConfigCompleter,
|
||||
"/admin/config/set": adminConfigCompleter,
|
||||
"/admin/config/del": adminConfigCompleter,
|
||||
"/admin/config/import": aliasCompleter,
|
||||
"/admin/config/export": aliasCompleter,
|
||||
"/admin/config/history/restore": aliasCompleter,
|
||||
"/admin/config/history/list": aliasCompleter,
|
||||
"/admin/config/history/clear": aliasCompleter,
|
||||
"/admin/config/get": adminConfigCompleter,
|
||||
"/admin/config/set": adminConfigCompleter,
|
||||
"/admin/config/reset": adminConfigCompleter,
|
||||
"/admin/config/import": aliasCompleter,
|
||||
"/admin/config/export": aliasCompleter,
|
||||
"/admin/config/history": aliasCompleter,
|
||||
"/admin/config/restore": aliasCompleter,
|
||||
|
||||
"/admin/trace": aliasCompleter,
|
||||
"/admin/console": aliasCompleter,
|
||||
@@ -281,10 +306,6 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/admin/group/remove": aliasCompleter,
|
||||
"/admin/group/info": aliasCompleter,
|
||||
|
||||
"/session/clear": nil,
|
||||
"/session/list": nil,
|
||||
"/session/resume": nil,
|
||||
|
||||
"/config/host/add": nil,
|
||||
"/config/host/list": aliasCompleter,
|
||||
"/config/host/remove": aliasCompleter,
|
||||
|
||||
+16
-12
@@ -18,6 +18,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -43,7 +44,7 @@ var catCmd = cli.Command{
|
||||
Name: "cat",
|
||||
Usage: "display object contents",
|
||||
Action: mainCat,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(append(catFlags, ioFlags...), globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -139,7 +140,7 @@ func checkCatSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
// catURL displays contents of a URL to stdout.
|
||||
func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
|
||||
func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
|
||||
var reader io.ReadCloser
|
||||
size := int64(-1)
|
||||
switch sourceURL {
|
||||
@@ -152,11 +153,11 @@ func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error
|
||||
// downloaded object is equal to the original one. FS files
|
||||
// are ignored since some of them have zero size though they
|
||||
// have contents like files under /proc.
|
||||
client, content, err := url2Stat(sourceURL, false, encKeyDB)
|
||||
client, content, err := url2Stat(ctx, sourceURL, false, encKeyDB)
|
||||
if err == nil && client.GetURL().Type == objectStorage {
|
||||
size = content.Size
|
||||
}
|
||||
if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil {
|
||||
if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
defer reader.Close()
|
||||
@@ -210,17 +211,20 @@ func catOut(r io.Reader, size int64) *probe.Error {
|
||||
}
|
||||
|
||||
// mainCat is the main entry point for cat command.
|
||||
func mainCat(ctx *cli.Context) error {
|
||||
func mainCat(cliCtx *cli.Context) error {
|
||||
ctx, cancelCat := context.WithCancel(globalContext)
|
||||
defer cancelCat()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'cat' cli arguments.
|
||||
checkCatSyntax(ctx)
|
||||
checkCatSyntax(cliCtx)
|
||||
|
||||
// Set command flags from context.
|
||||
stdinMode := false
|
||||
if !ctx.Args().Present() {
|
||||
if !cliCtx.Args().Present() {
|
||||
stdinMode = true
|
||||
}
|
||||
|
||||
@@ -231,11 +235,11 @@ func mainCat(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// if Args contain `-`, we need to preserve its order specially.
|
||||
args := []string(ctx.Args())
|
||||
if ctx.Args().First() == "-" {
|
||||
args := []string(cliCtx.Args())
|
||||
if cliCtx.Args().First() == "-" {
|
||||
for i, arg := range os.Args {
|
||||
if arg == "cat" {
|
||||
// Overwrite ctx.Args with os.Args.
|
||||
// Overwrite cliCtx.Args with os.Args.
|
||||
args = os.Args[i+1:]
|
||||
break
|
||||
}
|
||||
@@ -244,7 +248,7 @@ func mainCat(ctx *cli.Context) error {
|
||||
|
||||
// Convert arguments to URLs: expand alias, fix format.
|
||||
for _, url := range args {
|
||||
fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
fatalIf(catURL(ctx, url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+11
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* MinIO Client (C) 2017 MinIO, Inc.
|
||||
* MinIO Client (C) 2017-2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -26,8 +26,10 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mattn/go-ieproxy"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v6/pkg/credentials"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
@@ -63,9 +65,15 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
|
||||
var api *madmin.AdminClient
|
||||
var found bool
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
// Admin API only supports signature v4.
|
||||
creds := credentials.NewStaticV4(config.AccessKey, config.SecretKey, config.SessionToken)
|
||||
|
||||
// Not found. Instantiate a new MinIO
|
||||
var e error
|
||||
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
|
||||
api, e = madmin.NewWithOptions(hostName, &madmin.Options{
|
||||
Creds: creds,
|
||||
Secure: useTLS,
|
||||
})
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
@@ -83,7 +91,7 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
|
||||
}
|
||||
|
||||
var transport http.RoundTripper = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
Proxy: ieproxy.GetProxyFunc(),
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 15 * time.Second,
|
||||
|
||||
+160
-144
@@ -20,7 +20,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -34,13 +33,14 @@ import (
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rjeczalik/notify"
|
||||
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
"github.com/minio/mc/pkg/disk"
|
||||
"github.com/minio/mc/pkg/hookreader"
|
||||
"github.com/minio/mc/pkg/ioutils"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go/v6"
|
||||
"github.com/minio/minio-go/v6/pkg/encrypt"
|
||||
"github.com/minio/minio/pkg/bucket/object/tagging"
|
||||
"github.com/minio/minio-go/v6/pkg/tags"
|
||||
)
|
||||
|
||||
// filesystem client
|
||||
@@ -51,12 +51,13 @@ type fsClient struct {
|
||||
const (
|
||||
partSuffix = ".part.minio"
|
||||
slashSeperator = "/"
|
||||
metaDataKey = "X-Amz-Meta-Mc-Attrs"
|
||||
)
|
||||
|
||||
var ( // GOOS specific ignore list.
|
||||
ignoreFiles = map[string][]string{
|
||||
"darwin": {"*.DS_Store"},
|
||||
"default": {""},
|
||||
"default": {"lost+found"},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -118,7 +119,7 @@ func (f *fsClient) GetURL() ClientURL {
|
||||
}
|
||||
|
||||
// Select replies a stream of query results.
|
||||
func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
|
||||
func (f *fsClient) Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
API: "Select",
|
||||
APIType: "filesystem",
|
||||
@@ -126,16 +127,16 @@ func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts Select
|
||||
}
|
||||
|
||||
// Watches for all fs events on an input path.
|
||||
func (f *fsClient) Watch(params watchParams) (*WatchObject, *probe.Error) {
|
||||
eventChan := make(chan EventInfo)
|
||||
func (f *fsClient) Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error) {
|
||||
eventChan := make(chan []EventInfo)
|
||||
errorChan := make(chan *probe.Error)
|
||||
doneChan := make(chan bool)
|
||||
doneChan := make(chan struct{})
|
||||
// Make the channel buffered to ensure no event is dropped. Notify will drop
|
||||
// an event if the receiver is not able to keep up the sending pace.
|
||||
in, out := PipeChan(1000)
|
||||
|
||||
var fsEvents []notify.Event
|
||||
for _, event := range params.events {
|
||||
for _, event := range options.Events {
|
||||
switch event {
|
||||
case "put":
|
||||
fsEvents = append(fsEvents, EventTypePut...)
|
||||
@@ -151,7 +152,7 @@ func (f *fsClient) Watch(params watchParams) (*WatchObject, *probe.Error) {
|
||||
// Set up a watchpoint listening for events within a directory tree rooted
|
||||
// at current working directory. Dispatch remove events to c.
|
||||
recursivePath := f.PathURL.Path
|
||||
if params.recursive {
|
||||
if options.Recursive {
|
||||
recursivePath = f.PathURL.Path + "..."
|
||||
}
|
||||
if e := notify.Watch(recursivePath, in, fsEvents...); e != nil {
|
||||
@@ -192,73 +193,81 @@ func (f *fsClient) Watch(params watchParams) (*WatchObject, *probe.Error) {
|
||||
// we want files
|
||||
continue
|
||||
}
|
||||
eventChan <- EventInfo{
|
||||
eventChan <- []EventInfo{{
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Size: i.Size(),
|
||||
Path: event.Path(),
|
||||
Type: EventCreate,
|
||||
}
|
||||
}}
|
||||
} else if IsDeleteEvent(event.Event()) {
|
||||
eventChan <- EventInfo{
|
||||
eventChan <- []EventInfo{{
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Path: event.Path(),
|
||||
Type: EventRemove,
|
||||
}
|
||||
}}
|
||||
} else if IsGetEvent(event.Event()) {
|
||||
eventChan <- EventInfo{
|
||||
eventChan <- []EventInfo{{
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Path: event.Path(),
|
||||
Type: EventAccessed,
|
||||
}
|
||||
}}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return &WatchObject{
|
||||
eventInfoChan: eventChan,
|
||||
errorChan: errorChan,
|
||||
doneChan: doneChan,
|
||||
EventInfoChan: eventChan,
|
||||
ErrorChan: errorChan,
|
||||
DoneChan: doneChan,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func isStreamFile(objectPath string) bool {
|
||||
switch objectPath {
|
||||
case os.DevNull:
|
||||
fallthrough
|
||||
case os.Stdin.Name():
|
||||
fallthrough
|
||||
case os.Stdout.Name():
|
||||
fallthrough
|
||||
case os.Stderr.Name():
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
|
||||
mode, e := strconv.ParseUint(attr["mode"], 10, 32)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
if val, ok := attr["mode"]; ok {
|
||||
mode, e := strconv.ParseUint(val, 0, 32)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// Attempt to change the file mode.
|
||||
if e := fd.Chmod(os.FileMode(mode)); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Attempt to change the file mode.
|
||||
if e := fd.Chmod(os.FileMode(mode)); e != nil {
|
||||
return probe.NewError(e)
|
||||
var uid, gid int
|
||||
var gidExists, uidExists bool
|
||||
var e error
|
||||
if val, ok := attr["uid"]; ok {
|
||||
uid, e = strconv.Atoi(val)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
uidExists = true
|
||||
}
|
||||
|
||||
uid, e := strconv.Atoi(attr["uid"])
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
gid, e := strconv.Atoi(attr["gid"])
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
if val, ok := attr["gid"]; ok {
|
||||
gid, e = strconv.Atoi(val)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
gidExists = true
|
||||
}
|
||||
|
||||
// Attempt to change the owner.
|
||||
if e := fd.Chown(uid, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
if gidExists && uidExists {
|
||||
if e := fd.Chown(uid, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
} else if uidExists {
|
||||
if e := fd.Chown(uid, -1); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
} else {
|
||||
if e := fd.Chown(-1, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -266,7 +275,7 @@ func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
|
||||
|
||||
/// Object operations.
|
||||
|
||||
func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) {
|
||||
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metadata map[string][]string, progress io.Reader, preserve bool) (int64, *probe.Error) {
|
||||
// ContentType is not handled on purpose.
|
||||
// For filesystem this is a redundant information.
|
||||
|
||||
@@ -287,79 +296,52 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
|
||||
}
|
||||
|
||||
objectPath := f.PathURL.Path
|
||||
avoidResumeUpload := isStreamFile(objectPath)
|
||||
|
||||
// Write to a temporary file "object.part.minio" before commit.
|
||||
objectPartPath := objectPath + partSuffix
|
||||
if avoidResumeUpload {
|
||||
objectPartPath = objectPath
|
||||
}
|
||||
|
||||
// If exists, open in append mode. If not create it the part file.
|
||||
partFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
|
||||
// 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, 0666)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return 0, err.Trace(f.PathURL.Path)
|
||||
}
|
||||
|
||||
attr := make(map[string]string)
|
||||
if len(metadata["mc-attrs"]) != 0 {
|
||||
attr, e = parseAttribute(metadata["mc-attrs"][0])
|
||||
if len(metadata[metaDataKey]) != 0 && preserve {
|
||||
attr, e = parseAttribute(metadata[metaDataKey][0])
|
||||
if e != nil {
|
||||
tmpFile.Close()
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
if err := preserveAttributes(partFile, attr); err != nil {
|
||||
if err := preserveAttributes(tmpFile, attr); err != nil {
|
||||
tmpFile.Close()
|
||||
return 0, err.Trace(objectPath)
|
||||
}
|
||||
}
|
||||
|
||||
// Get stat to get the current size.
|
||||
partSt, e := os.Stat(objectPartPath)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, objectPartPath)
|
||||
return 0, err.Trace(objectPartPath)
|
||||
}
|
||||
|
||||
var totalWritten int64
|
||||
// Current file offset.
|
||||
var currentOffset = partSt.Size()
|
||||
|
||||
if !isStdIO(reader) && size > 0 {
|
||||
reader = hookreader.NewHook(reader, progress)
|
||||
if seeker, ok := reader.(io.Seeker); ok {
|
||||
if _, e = seeker.Seek(currentOffset, 0); e != nil {
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
// Discard bytes until currentOffset.
|
||||
if _, e = io.CopyN(ioutil.Discard, progress, currentOffset); e != nil {
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reader = hookreader.NewHook(reader, progress)
|
||||
// Discard bytes until currentOffset.
|
||||
if _, e = io.CopyN(ioutil.Discard, reader, currentOffset); e != nil {
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
n, e := io.Copy(partFile, reader)
|
||||
totalWritten, e := io.Copy(tmpFile, hookreader.NewHook(reader, progress))
|
||||
if e != nil {
|
||||
tmpFile.Close()
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
|
||||
// Save currently copied total into totalWritten.
|
||||
totalWritten = n + currentOffset
|
||||
|
||||
// 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 rename.
|
||||
if e = partFile.Close(); e != nil {
|
||||
// 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)
|
||||
}
|
||||
|
||||
@@ -380,45 +362,56 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
|
||||
})
|
||||
}
|
||||
}
|
||||
if !avoidResumeUpload {
|
||||
// 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)
|
||||
|
||||
// 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 && preserve {
|
||||
var atime, mtime int64
|
||||
var e error
|
||||
var atimeChanged, mtimeChanged bool
|
||||
if val, ok := attr["atime"]; ok {
|
||||
atime, e = strconv.ParseInt(val, 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
atimeChanged = true
|
||||
}
|
||||
|
||||
if len(attr) != 0 {
|
||||
atime, e := strconv.ParseInt(attr["atime"], 10, 64)
|
||||
if val, ok := attr["mtime"]; ok {
|
||||
mtime, e = strconv.ParseInt(val, 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
mtimeChanged = true
|
||||
}
|
||||
|
||||
mtime, e := strconv.ParseInt(attr["mtime"], 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
|
||||
// Attempt to change the access and modify time
|
||||
// Attempt to change the access and modify time
|
||||
if atimeChanged && mtimeChanged {
|
||||
if e := os.Chtimes(objectPath, time.Unix(atime, 0), time.Unix(mtime, 0)); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return totalWritten, nil
|
||||
}
|
||||
|
||||
// Put - create a new file with metadata.
|
||||
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, disableMultipart bool) (int64, *probe.Error) {
|
||||
if metadata["mc-attrs"] != "" {
|
||||
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
|
||||
if metadata[metaDataKey] != "" {
|
||||
meta := make(map[string][]string)
|
||||
meta["mc-attrs"] = append(meta["mc-attrs"], metadata["mc-attrs"])
|
||||
return f.put(reader, size, meta, progress)
|
||||
meta[metaDataKey] = append(meta[metaDataKey], metadata[metaDataKey])
|
||||
return f.put(ctx, reader, size, meta, progress, preserve)
|
||||
}
|
||||
return f.put(reader, size, nil, progress)
|
||||
return f.put(ctx, reader, size, nil, progress, preserve)
|
||||
}
|
||||
|
||||
// ShareDownload - share download not implemented for filesystem.
|
||||
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
func (f *fsClient) ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(APINotImplemented{
|
||||
API: "ShareDownload",
|
||||
APIType: "filesystem",
|
||||
@@ -434,7 +427,7 @@ func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentTy
|
||||
}
|
||||
|
||||
// Copy - copy data from source to destination
|
||||
func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error {
|
||||
func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
|
||||
rc, e := os.Open(source)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, source)
|
||||
@@ -443,14 +436,14 @@ func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, t
|
||||
defer rc.Close()
|
||||
|
||||
destination := f.PathURL.Path
|
||||
if _, err := f.put(rc, size, map[string][]string{}, progress); err != nil {
|
||||
if _, err := f.put(ctx, rc, size, map[string][]string{}, progress, preserve); err != nil {
|
||||
return err.Trace(destination, source)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get returns reader and any additional metadata.
|
||||
func (f *fsClient) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
|
||||
func (f *fsClient) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
|
||||
fileData, e := os.Open(f.PathURL.Path)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
@@ -504,7 +497,7 @@ func deleteFile(deletePath string) error {
|
||||
}
|
||||
|
||||
// Remove - remove entry read from clientContent channel.
|
||||
func (f *fsClient) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error {
|
||||
func (f *fsClient) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error {
|
||||
errorCh := make(chan *probe.Error)
|
||||
|
||||
// Goroutine reads from contentCh and removes the entry in content.
|
||||
@@ -512,22 +505,29 @@ func (f *fsClient) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh
|
||||
defer close(errorCh)
|
||||
|
||||
for content := range contentCh {
|
||||
if content.Err != nil {
|
||||
errorCh <- content.Err
|
||||
continue
|
||||
}
|
||||
name := content.URL.Path
|
||||
// Add partSuffix for incomplete uploads.
|
||||
if isIncomplete {
|
||||
name += partSuffix
|
||||
}
|
||||
if e := deleteFile(name); e != nil {
|
||||
if os.IsPermission(e) {
|
||||
// Ignore permission error.
|
||||
errorCh <- probe.NewError(PathInsufficientPermission{Path: content.URL.Path})
|
||||
} else if os.IsNotExist(e) && isRemoveBucket {
|
||||
// ignore PathNotFound for dir removal.
|
||||
return
|
||||
} else {
|
||||
errorCh <- probe.NewError(e)
|
||||
return
|
||||
}
|
||||
e := deleteFile(name)
|
||||
if e == nil {
|
||||
continue
|
||||
}
|
||||
if os.IsNotExist(e) && isRemoveBucket {
|
||||
// ignore PathNotFound for dir removal.
|
||||
return
|
||||
}
|
||||
if os.IsPermission(e) {
|
||||
// Ignore permission error.
|
||||
errorCh <- probe.NewError(PathInsufficientPermission{Path: content.URL.Path})
|
||||
} else {
|
||||
errorCh <- probe.NewError(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -536,7 +536,7 @@ func (f *fsClient) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh
|
||||
}
|
||||
|
||||
// List - list files and folders.
|
||||
func (f *fsClient) List(isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent {
|
||||
func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent {
|
||||
contentCh := make(chan *ClientContent)
|
||||
filteredCh := make(chan *ClientContent)
|
||||
|
||||
@@ -910,7 +910,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *ClientContent, isMetad
|
||||
}
|
||||
|
||||
// MakeBucket - create a new bucket.
|
||||
func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error {
|
||||
func (f *fsClient) MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error {
|
||||
// TODO: ignoreExisting has no effect currently. In the future, we want
|
||||
// to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll()
|
||||
// otherwise.
|
||||
@@ -923,7 +923,7 @@ func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *pro
|
||||
}
|
||||
|
||||
// Set object lock configuration of bucket.
|
||||
func (f *fsClient) SetObjectLockConfig(mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) *probe.Error {
|
||||
func (f *fsClient) SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetObjectLockConfig",
|
||||
APIType: "filesystem",
|
||||
@@ -931,15 +931,15 @@ func (f *fsClient) SetObjectLockConfig(mode *minio.RetentionMode, validity *uint
|
||||
}
|
||||
|
||||
// Get object lock configuration of bucket.
|
||||
func (f *fsClient) GetObjectLockConfig() (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, perr *probe.Error) {
|
||||
return nil, nil, nil, probe.NewError(APINotImplemented{
|
||||
func (f *fsClient) GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
|
||||
return "", 0, "", probe.NewError(APINotImplemented{
|
||||
API: "GetObjectLockConfig",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// GetAccessRules - unsupported API
|
||||
func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
|
||||
func (f *fsClient) GetAccessRules(ctx context.Context) (map[string]string, *probe.Error) {
|
||||
return map[string]string{}, probe.NewError(APINotImplemented{
|
||||
API: "GetBucketPolicy",
|
||||
APIType: "filesystem",
|
||||
@@ -947,7 +947,7 @@ func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
|
||||
}
|
||||
|
||||
// Set object retention for a given object.
|
||||
func (f *fsClient) PutObjectRetention(mode *minio.RetentionMode, retainUntilDate *time.Time, bypassGovernance bool) *probe.Error {
|
||||
func (f *fsClient) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectRetention",
|
||||
APIType: "filesystem",
|
||||
@@ -955,7 +955,7 @@ func (f *fsClient) PutObjectRetention(mode *minio.RetentionMode, retainUntilDate
|
||||
}
|
||||
|
||||
// Set object legal hold for a given object.
|
||||
func (f *fsClient) PutObjectLegalHold(lhold *minio.LegalHoldStatus) *probe.Error {
|
||||
func (f *fsClient) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectLegalHold",
|
||||
APIType: "filesystem",
|
||||
@@ -963,7 +963,7 @@ func (f *fsClient) PutObjectLegalHold(lhold *minio.LegalHoldStatus) *probe.Error
|
||||
}
|
||||
|
||||
// GetAccess - get access policy permissions.
|
||||
func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Error) {
|
||||
func (f *fsClient) GetAccess(ctx context.Context) (access string, policyJSON string, err *probe.Error) {
|
||||
// For windows this feature is not implemented.
|
||||
if runtime.GOOS == "windows" {
|
||||
return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
|
||||
@@ -988,7 +988,7 @@ func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Err
|
||||
}
|
||||
|
||||
// SetAccess - set access policy permissions.
|
||||
func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
|
||||
func (f *fsClient) SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error {
|
||||
// For windows this feature is not implemented.
|
||||
// JSON policy for fs is not yet implemented.
|
||||
if runtime.GOOS == "windows" || isJSON {
|
||||
@@ -1020,7 +1020,7 @@ func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
|
||||
}
|
||||
|
||||
// Stat - get metadata from path.
|
||||
func (f *fsClient) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) {
|
||||
func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) {
|
||||
st, err := f.fsStat(isIncomplete)
|
||||
if err != nil {
|
||||
return nil, err.Trace(f.PathURL.String())
|
||||
@@ -1050,7 +1050,7 @@ func (f *fsClient) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (
|
||||
if err != nil {
|
||||
return content, nil
|
||||
}
|
||||
content.Metadata["mc-attrs"] = fileAttr
|
||||
content.Metadata[metaDataKey] = fileAttr
|
||||
}
|
||||
|
||||
return content, nil
|
||||
@@ -1096,15 +1096,15 @@ func (f *fsClient) AddUserAgent(_, _ string) {
|
||||
}
|
||||
|
||||
// Get Object Tags
|
||||
func (f *fsClient) GetObjectTagging() (tagging.Tagging, *probe.Error) {
|
||||
return tagging.Tagging{}, probe.NewError(APINotImplemented{
|
||||
func (f *fsClient) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) {
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
API: "GetObjectTagging",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// Set Object tags
|
||||
func (f *fsClient) SetObjectTagging(tagMap map[string]string) *probe.Error {
|
||||
func (f *fsClient) SetTags(ctx context.Context, tags string) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1112,9 +1112,25 @@ func (f *fsClient) SetObjectTagging(tagMap map[string]string) *probe.Error {
|
||||
}
|
||||
|
||||
// Delete object tags
|
||||
func (f *fsClient) DeleteObjectTagging() *probe.Error {
|
||||
func (f *fsClient) DeleteTags(ctx context.Context) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "DeleteObjectTagging",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// Get lifecycle configuration for a given bucket, not implemented.
|
||||
func (f *fsClient) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) {
|
||||
return ilm.LifecycleConfiguration{}, probe.NewError(APINotImplemented{
|
||||
API: "GetLifecycle",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// Set lifecycle configuration for a given bucket, not implemented.
|
||||
func (f *fsClient) SetLifecycle(ctx context.Context, _ ilm.LifecycleConfiguration) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetLifecycle",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
+24
-25
@@ -45,7 +45,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
var n int64
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -56,7 +56,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -65,7 +65,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
// Verify previously create files and list them.
|
||||
var contents []*ClientContent
|
||||
for content := range fsClient.List(false, false, false, DirNone) {
|
||||
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -84,7 +84,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -93,7 +93,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List non recursive to list only top level files.
|
||||
for content := range fsClient.List(false, false, false, DirNone) {
|
||||
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -109,7 +109,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false, false, DirNone) {
|
||||
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -144,7 +144,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -153,7 +153,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false, false, DirNone) {
|
||||
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -194,7 +194,7 @@ func (s *TestSuite) TestPutBucket(c *C) {
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1", true, false)
|
||||
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
@@ -208,9 +208,9 @@ func (s *TestSuite) TestStatBucket(c *C) {
|
||||
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1", true, false)
|
||||
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
_, err = fsClient.Stat(false, false, nil)
|
||||
_, err = fsClient.Stat(context.Background(), false, false, nil)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
@@ -223,15 +223,15 @@ func (s *TestSuite) TestBucketACLFails(c *C) {
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1", true, false)
|
||||
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// On windows setting permissions is not supported.
|
||||
if runtime.GOOS != "windows" {
|
||||
err = fsClient.SetAccess("readonly", false)
|
||||
err = fsClient.SetAccess(context.Background(), "readonly", false)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
_, _, err = fsClient.GetAccess()
|
||||
_, _, err = fsClient.GetAccess(context.Background())
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
}
|
||||
@@ -251,7 +251,7 @@ func (s *TestSuite) TestPut(c *C) {
|
||||
var n int64
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
}
|
||||
@@ -271,11 +271,11 @@ func (s *TestSuite) TestGet(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get(nil)
|
||||
reader, err = fsClient.Get(context.Background(), nil)
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, e = io.Copy(&results, reader)
|
||||
@@ -299,11 +299,11 @@ func (s *TestSuite) TestGetRange(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get(nil)
|
||||
reader, err = fsClient.Get(context.Background(), nil)
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
buf := make([]byte, 5)
|
||||
@@ -330,11 +330,11 @@ func (s *TestSuite) TestStatObject(c *C) {
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(dataLen), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
content, err := fsClient.Stat(false, false, nil)
|
||||
content, err := fsClient.Stat(context.Background(), false, false, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(dataLen))
|
||||
}
|
||||
@@ -352,14 +352,13 @@ func (s *TestSuite) TestCopy(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello world"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, nil, nil, nil, false)
|
||||
err = fsClientTarget.Copy(context.Background(), sourcePath, int64(len(data)), nil, nil, nil, nil, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
+444
-360
File diff suppressed because it is too large
Load Diff
@@ -171,14 +171,14 @@ func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
s3c, err := S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket("us-east-1", true, false)
|
||||
err = s3c.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
|
||||
s3c, err = S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false, false, DirNone) {
|
||||
for content := range s3c.List(globalContext, false, false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
@@ -187,7 +187,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
s3c, err = S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false, false, DirNone) {
|
||||
for content := range s3c.List(globalContext, false, false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
@@ -196,7 +196,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
s3c, err = S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false, false, DirNone) {
|
||||
for content := range s3c.List(globalContext, false, false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
@@ -223,11 +223,11 @@ func (s *TestSuite) TestObjectOperations(c *C) {
|
||||
reader = bytes.NewReader(object.data)
|
||||
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(object.data)))
|
||||
|
||||
reader, err = s3c.Get(nil)
|
||||
reader, err = s3c.Get(context.Background(), nil)
|
||||
c.Assert(err, IsNil)
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
|
||||
+16
-3
@@ -18,6 +18,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
@@ -132,6 +133,18 @@ func joinURLs(url1, url2 *ClientURL) *ClientURL {
|
||||
return url1
|
||||
}
|
||||
|
||||
// Clone the url into a new object.
|
||||
func (u ClientURL) Clone() ClientURL {
|
||||
return ClientURL{
|
||||
Type: u.Type,
|
||||
Scheme: u.Scheme,
|
||||
Host: u.Host,
|
||||
Path: u.Path,
|
||||
SchemeSeparator: u.SchemeSeparator,
|
||||
Separator: u.Separator,
|
||||
}
|
||||
}
|
||||
|
||||
// String convert URL into its canonical form.
|
||||
func (u ClientURL) String() string {
|
||||
var buf bytes.Buffer
|
||||
@@ -171,7 +184,7 @@ func urlJoinPath(url1, url2 string) string {
|
||||
}
|
||||
|
||||
// url2Stat returns stat info for URL.
|
||||
func url2Stat(urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) {
|
||||
func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) {
|
||||
client, err = newClient(urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
@@ -179,7 +192,7 @@ func url2Stat(urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair)
|
||||
alias, _ := url2Alias(urlStr)
|
||||
sse := getSSE(urlStr, encKeyDB[alias])
|
||||
|
||||
content, err = client.Stat(false, fileAttr, sse)
|
||||
content, err = client.Stat(ctx, false, fileAttr, sse)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
@@ -219,7 +232,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
|
||||
isRecursive := false
|
||||
isIncomplete := incomplete
|
||||
isFetchMeta := false
|
||||
for entry := range clnt.List(isRecursive, isIncomplete, isFetchMeta, DirNone) {
|
||||
for entry := range clnt.List(globalContext, isRecursive, isIncomplete, isFetchMeta, DirNone) {
|
||||
return entry.Err == nil
|
||||
}
|
||||
return false
|
||||
|
||||
+44
-34
@@ -22,10 +22,11 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go/v6"
|
||||
"github.com/minio/minio-go/v6/pkg/encrypt"
|
||||
"github.com/minio/minio/pkg/bucket/object/tagging"
|
||||
"github.com/minio/minio-go/v6/pkg/tags"
|
||||
)
|
||||
|
||||
// DirOpt - list directory option.
|
||||
@@ -46,50 +47,56 @@ const defaultMultipartThreadsNum = 4
|
||||
// Client - client interface
|
||||
type Client interface {
|
||||
// Common operations
|
||||
Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error)
|
||||
List(isRecursive, isIncomplete, isFetchMeta bool, showDir DirOpt) <-chan *ClientContent
|
||||
Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error)
|
||||
List(ctx context.Context, isRecursive, isIncomplete, isFetchMeta bool, showDir DirOpt) <-chan *ClientContent
|
||||
|
||||
// Bucket operations
|
||||
MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error
|
||||
SetObjectLockConfig(mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) *probe.Error
|
||||
GetObjectLockConfig() (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, perr *probe.Error)
|
||||
MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error
|
||||
// Object lock config
|
||||
SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error
|
||||
GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
|
||||
|
||||
// Access policy operations.
|
||||
GetAccess() (access string, policyJSON string, error *probe.Error)
|
||||
GetAccessRules() (policyRules map[string]string, error *probe.Error)
|
||||
SetAccess(access string, isJSON bool) *probe.Error
|
||||
GetAccess(ctx context.Context) (access string, policyJSON string, error *probe.Error)
|
||||
GetAccessRules(ctx context.Context) (policyRules map[string]string, error *probe.Error)
|
||||
SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error
|
||||
|
||||
// I/O operations
|
||||
Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error
|
||||
Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, isPreserve bool) *probe.Error
|
||||
|
||||
// Runs select expression on object storage on specific files.
|
||||
Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
|
||||
Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
|
||||
|
||||
// I/O operations with metadata.
|
||||
Get(sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
|
||||
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, disableMultipart bool) (n int64, err *probe.Error)
|
||||
Get(ctx context.Context, sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
|
||||
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, isPreserve bool) (n int64, err *probe.Error)
|
||||
|
||||
// Object Locking related API
|
||||
PutObjectRetention(mode *minio.RetentionMode, retainUntilDate *time.Time, bypassGovernance bool) *probe.Error
|
||||
PutObjectLegalHold(hold *minio.LegalHoldStatus) *probe.Error
|
||||
PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
|
||||
PutObjectLegalHold(ctx context.Context, hold minio.LegalHoldStatus) *probe.Error
|
||||
|
||||
// I/O operations with expiration
|
||||
ShareDownload(expires time.Duration) (string, *probe.Error)
|
||||
ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
|
||||
|
||||
// Watch events
|
||||
Watch(params watchParams) (*WatchObject, *probe.Error)
|
||||
Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error)
|
||||
|
||||
// Delete operations
|
||||
Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) (errorCh <-chan *probe.Error)
|
||||
Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) (errorCh <-chan *probe.Error)
|
||||
// GetURL returns back internal url
|
||||
GetURL() ClientURL
|
||||
|
||||
AddUserAgent(app, version string)
|
||||
|
||||
// Object Tag operations
|
||||
GetObjectTagging() (tagging.Tagging, *probe.Error)
|
||||
SetObjectTagging(tagMap map[string]string) *probe.Error
|
||||
DeleteObjectTagging() *probe.Error
|
||||
// Tagging operations
|
||||
GetTags(ctx context.Context) (*tags.Tags, *probe.Error)
|
||||
SetTags(ctx context.Context, tags string) *probe.Error
|
||||
DeleteTags(ctx context.Context) *probe.Error
|
||||
|
||||
// Lifecycle operations
|
||||
GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error)
|
||||
SetLifecycle(ctx context.Context, lfcCfg ilm.LifecycleConfiguration) *probe.Error
|
||||
}
|
||||
|
||||
// ClientContent - Content container for content metadata
|
||||
@@ -103,26 +110,29 @@ type ClientContent struct {
|
||||
UserMetadata map[string]string
|
||||
ETag string
|
||||
Expires time.Time
|
||||
Retention bool
|
||||
RetentionEnabled bool
|
||||
RetentionMode string
|
||||
RetentionDuration string
|
||||
BypassGovernance bool
|
||||
LegalHoldEnabled bool
|
||||
LegalHold string
|
||||
Err *probe.Error
|
||||
|
||||
Err *probe.Error
|
||||
}
|
||||
|
||||
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
|
||||
type Config struct {
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Signature string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
Insecure bool
|
||||
Lookup minio.BucketLookupType
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
SessionToken string
|
||||
Signature string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
Insecure bool
|
||||
Lookup minio.BucketLookupType
|
||||
}
|
||||
|
||||
// SelectObjectOpts - opts entered for select API
|
||||
|
||||
+144
-84
@@ -104,10 +104,10 @@ func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
|
||||
// Check if the passed URL represents a folder. It may or may not exist yet.
|
||||
// If it exists, we can easily check if it is a folder, if it doesn't exist,
|
||||
// we can guess if the url is a folder from how it looks.
|
||||
func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool {
|
||||
func isAliasURLDir(ctx context.Context, aliasURL string, keys map[string][]prefixSSEPair) bool {
|
||||
// If the target url exists, check if it is a directory
|
||||
// and return immediately.
|
||||
_, targetContent, err := url2Stat(aliasURL, false, keys)
|
||||
_, targetContent, err := url2Stat(ctx, aliasURL, false, keys)
|
||||
if err == nil {
|
||||
return targetContent.Type.IsDir()
|
||||
}
|
||||
@@ -141,24 +141,24 @@ func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool {
|
||||
}
|
||||
|
||||
// getSourceStreamMetadataFromURL gets a reader from URL.
|
||||
func getSourceStreamMetadataFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
|
||||
func getSourceStreamMetadataFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
|
||||
metadata map[string]string, err *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
sseKey := getSSE(urlStr, encKeyDB[alias])
|
||||
return getSourceStream(alias, urlStrFull, true, sseKey)
|
||||
return getSourceStream(ctx, alias, urlStrFull, true, sseKey, false)
|
||||
}
|
||||
|
||||
// getSourceStreamFromURL gets a reader from URL.
|
||||
func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
|
||||
func getSourceStreamFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(urlStr)
|
||||
}
|
||||
sse := getSSE(urlStr, encKeyDB[alias])
|
||||
reader, _, err = getSourceStream(alias, urlStrFull, false, sse)
|
||||
reader, _, err = getSourceStream(ctx, alias, urlStrFull, false, sse, false)
|
||||
return reader, err
|
||||
}
|
||||
|
||||
@@ -186,13 +186,36 @@ func probeContentType(reader io.Reader) (ctype string, err *probe.Error) {
|
||||
return ctype, nil
|
||||
}
|
||||
|
||||
// Verify if reader is a generic ReaderAt
|
||||
func isReadAt(reader io.Reader) (ok bool) {
|
||||
var v *os.File
|
||||
v, ok = reader.(*os.File)
|
||||
if ok {
|
||||
// Stdin, Stdout and Stderr all have *os.File type
|
||||
// which happen to also be io.ReaderAt compatible
|
||||
// we need to add special conditions for them to
|
||||
// be ignored by this function.
|
||||
for _, f := range []string{
|
||||
"/dev/stdin",
|
||||
"/dev/stdout",
|
||||
"/dev/stderr",
|
||||
} {
|
||||
if f == v.Name() {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// getSourceStream gets a reader from URL.
|
||||
func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
|
||||
func getSourceStream(ctx context.Context, alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide, preserve bool) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
|
||||
sourceClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
reader, err = sourceClnt.Get(sse)
|
||||
reader, err = sourceClnt.Get(ctx, sse)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
@@ -204,7 +227,7 @@ func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.Se
|
||||
if mok {
|
||||
oinfo, e := mo.Stat()
|
||||
if e != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
return nil, nil, probe.NewError(e).Trace(alias, urlStr)
|
||||
}
|
||||
st = &ClientContent{}
|
||||
st.Time = oinfo.LastModified
|
||||
@@ -218,7 +241,7 @@ func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.Se
|
||||
}
|
||||
st.ETag = oinfo.ETag
|
||||
} else {
|
||||
st, err = sourceClnt.Stat(false, false, sse)
|
||||
st, err = sourceClnt.Stat(ctx, false, preserve, sse)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
@@ -267,22 +290,29 @@ func putTargetRetention(ctx context.Context, alias string, urlStr string, metada
|
||||
retainUntilDate = t.UTC()
|
||||
}
|
||||
}
|
||||
if err := targetClnt.PutObjectRetention(&lockMode, &retainUntilDate, false); err != nil {
|
||||
if err := targetClnt.PutObjectRetention(ctx, lockMode, retainUntilDate, false); err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// putTargetStream writes to URL from Reader.
|
||||
func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, disableMultipart bool) (int64, *probe.Error) {
|
||||
func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
metadata[AmzObjectLockMode] = mode
|
||||
metadata[AmzObjectLockRetainUntilDate] = until
|
||||
metadata[AmzObjectLockLegalHold] = legalHold
|
||||
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse, disableMultipart)
|
||||
|
||||
if mode != "" {
|
||||
metadata[AmzObjectLockMode] = mode
|
||||
}
|
||||
if until != "" {
|
||||
metadata[AmzObjectLockRetainUntilDate] = until
|
||||
}
|
||||
if legalHold != "" {
|
||||
metadata[AmzObjectLockLegalHold] = legalHold
|
||||
}
|
||||
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse, md5, disableMultipart, preserve)
|
||||
if err != nil {
|
||||
return n, err.Trace(alias, urlStr)
|
||||
}
|
||||
@@ -290,20 +320,21 @@ func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold
|
||||
}
|
||||
|
||||
// putTargetStreamWithURL writes to URL from reader. If length=-1, read until EOF.
|
||||
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide, disableMultipart bool) (int64, *probe.Error) {
|
||||
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide, md5, disableMultipart, preserve bool, metadata map[string]string) (int64, *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
}
|
||||
contentType := guessURLContentType(urlStr)
|
||||
metadata := map[string]string{
|
||||
"Content-Type": contentType,
|
||||
if metadata == nil {
|
||||
metadata = map[string]string{}
|
||||
}
|
||||
return putTargetStream(context.Background(), alias, urlStrFull, "", "", "", reader, size, metadata, nil, sse, disableMultipart)
|
||||
metadata["Content-Type"] = contentType
|
||||
return putTargetStream(context.Background(), alias, urlStrFull, "", "", "", reader, size, metadata, nil, sse, md5, disableMultipart, preserve)
|
||||
}
|
||||
|
||||
// copySourceToTargetURL copies to targetURL from source.
|
||||
func copySourceToTargetURL(alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error {
|
||||
func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error {
|
||||
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
@@ -313,7 +344,7 @@ func copySourceToTargetURL(alias, urlStr, source, mode, until, legalHold string,
|
||||
metadata[AmzObjectLockMode] = mode
|
||||
metadata[AmzObjectLockRetainUntilDate] = until
|
||||
metadata[AmzObjectLockLegalHold] = legalHold
|
||||
err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart)
|
||||
err = targetClnt.Copy(ctx, source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart, false)
|
||||
|
||||
if err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
@@ -338,23 +369,23 @@ func filterMetadata(metadata map[string]string) map[string]string {
|
||||
|
||||
// getAllMetadata - returns a map of user defined function
|
||||
// by combining the usermetadata of object and values passed by attr keyword
|
||||
func getAllMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) {
|
||||
func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs, preserve bool) (map[string]string, *probe.Error) {
|
||||
metadata := make(map[string]string)
|
||||
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sourceAlias, sourceURLStr)
|
||||
}
|
||||
st, err := sourceClnt.Stat(false, false, srcSSE)
|
||||
st, err := sourceClnt.Stat(ctx, false, preserve, srcSSE)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sourceAlias, sourceURLStr)
|
||||
}
|
||||
|
||||
for k, v := range st.Metadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
return filterMetadata(metadata), nil
|
||||
@@ -363,7 +394,7 @@ func getAllMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide,
|
||||
// uploadSourceToTargetURL - uploads to targetURL from source.
|
||||
// optionally optimizes copy for object sizes <= 5GiB by using
|
||||
// server side copy operation.
|
||||
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair, preserve bool) URLs {
|
||||
sourceAlias := urls.SourceAlias
|
||||
sourceURL := urls.SourceContent.URL
|
||||
targetAlias := urls.TargetAlias
|
||||
@@ -377,74 +408,131 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
|
||||
|
||||
var err *probe.Error
|
||||
var metadata = map[string]string{}
|
||||
var mode, until, legalHold string
|
||||
|
||||
var mode, until string
|
||||
var pErr error
|
||||
// add object retention fields in metadata
|
||||
if urls.TargetContent.RetentionDuration != "" && urls.TargetContent.RetentionMode != "" {
|
||||
// add object retention fields in metadata for target, if target wants
|
||||
// to override defaults from source, usually happens in `cp` command.
|
||||
// for the most part source metadata is copied over.
|
||||
if urls.TargetContent.RetentionEnabled {
|
||||
m := minio.RetentionMode(strings.ToUpper(urls.TargetContent.RetentionMode))
|
||||
|
||||
dur, unit := parseRetentionValidity(urls.TargetContent.RetentionDuration, m)
|
||||
var dur uint64
|
||||
var unit minio.ValidityUnit
|
||||
dur, unit, err = parseRetentionValidity(urls.TargetContent.RetentionDuration, m)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(targetURL.String()))
|
||||
}
|
||||
|
||||
mode = urls.TargetContent.RetentionMode
|
||||
|
||||
until, pErr = getRetainUntilDate(dur, unit)
|
||||
until, err = getRetainUntilDate(dur, unit)
|
||||
if err != nil {
|
||||
return urls.WithError(probe.NewError(pErr).Trace(sourceURL.String()))
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// add object legal hold fields in metadata for target, if target wants
|
||||
// to override defaults from source, usually happens in `cp` command.
|
||||
// for the most part source metadata is copied over.
|
||||
if urls.TargetContent.LegalHoldEnabled {
|
||||
switch minio.LegalHoldStatus(urls.TargetContent.LegalHold) {
|
||||
case minio.LegalHoldDisabled:
|
||||
case minio.LegalHoldEnabled:
|
||||
default:
|
||||
return urls.WithError(errInvalidArgument().Trace(urls.TargetContent.LegalHold))
|
||||
}
|
||||
legalHold = urls.TargetContent.LegalHold
|
||||
}
|
||||
|
||||
for k, v := range urls.SourceContent.UserMetadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
for k, v := range urls.SourceContent.Metadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
// Optimize for server side copy if the host is same.
|
||||
if sourceAlias == targetAlias {
|
||||
for k, v := range urls.SourceContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
for k, v := range urls.SourceContent.Metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
// If no metadata populated already by the caller
|
||||
// just do a Stat() to obtain the metadata.
|
||||
if len(metadata) == 0 {
|
||||
metadata, err = getAllMetadata(sourceAlias, sourceURL.String(), srcSSE, urls)
|
||||
if len(metadata) == 0 && preserve {
|
||||
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// Get metadata from target content as well
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
// Get userMetadata from target content as well
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
sourcePath := filepath.ToSlash(sourceURL.Path)
|
||||
if urls.SourceContent.Retention {
|
||||
if urls.SourceContent.RetentionEnabled {
|
||||
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, mode, until, urls.TargetContent.LegalHold, length,
|
||||
progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart)
|
||||
|
||||
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until,
|
||||
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart)
|
||||
} else {
|
||||
if len(metadata) == 0 {
|
||||
metadata, err = getAllMetadata(sourceAlias, sourceURL.String(), srcSSE, urls)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
if urls.SourceContent.RetentionEnabled {
|
||||
// If no metadata populated already by the caller
|
||||
// just do a Stat() to obtain the metadata.
|
||||
if len(metadata) == 0 && preserve {
|
||||
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
}
|
||||
}
|
||||
if urls.SourceContent.Retention {
|
||||
|
||||
// Get metadata from target content as well
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
// Get userMetadata from target content as well
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
|
||||
var reader io.ReadCloser
|
||||
// Proceed with regular stream copy.
|
||||
reader, metadata, err = getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE)
|
||||
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), true, srcSSE, preserve)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
// Get metadata from target content as well
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
// Get userMetadata from target content as well
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
if isReadAt(reader) {
|
||||
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), mode, until,
|
||||
legalHold, reader, length, filterMetadata(metadata),
|
||||
progress, tgtSSE, urls.MD5, urls.DisableMultipart, preserve)
|
||||
} else {
|
||||
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), mode, until,
|
||||
legalHold, io.LimitReader(reader, length),
|
||||
length, filterMetadata(metadata), progress, tgtSSE, urls.MD5,
|
||||
urls.DisableMultipart, preserve)
|
||||
}
|
||||
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), mode, until, urls.TargetContent.LegalHold, reader, length, filterMetadata(metadata),
|
||||
progress, tgtSSE, urls.DisableMultipart)
|
||||
}
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
@@ -497,31 +585,3 @@ func newClient(aliasedURL string) (Client, *probe.Error) {
|
||||
}
|
||||
return newClientFromAlias(alias, urlStrFull)
|
||||
}
|
||||
|
||||
// Return the file attribute value present in metadata
|
||||
func getFileAttrMeta(sURLs URLs, encKeyDB map[string][]prefixSSEPair) (string, *probe.Error) {
|
||||
sourceAlias := sURLs.SourceAlias
|
||||
sourceURL := sURLs.SourceContent.URL
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sURLs.SourceContent.URL.Path))
|
||||
srcSSE := getSSE(sourcePath, encKeyDB[sourceAlias])
|
||||
|
||||
statSourceURL := sURLs.SourceAlias + getKey(sURLs.SourceContent)
|
||||
srcClt, err := newClient(statSourceURL)
|
||||
if err != nil {
|
||||
return "", err.Trace(sourceURL.String())
|
||||
}
|
||||
|
||||
sourceMeta, err := srcClt.Stat(false, true, srcSSE)
|
||||
if err != nil {
|
||||
return "", err.Trace(sourceURL.String())
|
||||
}
|
||||
attrValue := ""
|
||||
if sourceMeta.Metadata["X-Amz-Meta-Mc-Attrs"] != "" {
|
||||
attrValue = sourceMeta.Metadata["X-Amz-Meta-Mc-Attrs"]
|
||||
} else if sourceMeta.Metadata["X-Amz-Meta-S3cmd-Attrs"] != "" {
|
||||
attrValue = sourceMeta.Metadata["X-Amz-Meta-S3cmd-Attrs"]
|
||||
} else if sourceMeta.Metadata["mc-attrs"] != "" {
|
||||
attrValue = sourceMeta.Metadata["mc-attrs"]
|
||||
}
|
||||
return attrValue, nil
|
||||
}
|
||||
|
||||
+19
-14
@@ -18,6 +18,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
@@ -49,7 +50,7 @@ var configHostAddCmd = cli.Command{
|
||||
ShortName: "a",
|
||||
Usage: "add a new host to configuration file",
|
||||
Action: mainConfigHostAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(hostAddFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -101,7 +102,7 @@ func checkConfigHostAddSyntax(ctx *cli.Context, accessKey string, secretKey stri
|
||||
"Incorrect number of arguments for host add command.")
|
||||
}
|
||||
|
||||
alias := args.Get(0)
|
||||
alias := cleanAlias(args.Get(0))
|
||||
url := args.Get(1)
|
||||
api := ctx.String("api")
|
||||
bucketLookup := ctx.String("lookup")
|
||||
@@ -159,7 +160,7 @@ func addHost(alias string, hostCfgV9 hostConfigV9) {
|
||||
|
||||
// probeS3Signature - auto probe S3 server signature: issue a Stat call
|
||||
// using v4 signature then v2 in case of failure.
|
||||
func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
func probeS3Signature(ctx context.Context, accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
probeBucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "probe-bucket-sign-")
|
||||
// Test s3 connection for API auto probe
|
||||
s3Config := &Config{
|
||||
@@ -178,7 +179,7 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if _, err := s3Client.Stat(false, false, nil); err != nil {
|
||||
if _, err := s3Client.Stat(ctx, false, false, nil); err != nil {
|
||||
e := err.ToGoError()
|
||||
if _, ok := e.(BucketDoesNotExist); ok {
|
||||
// Bucket doesn't exist, means signature probing worked successfully.
|
||||
@@ -209,7 +210,7 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
|
||||
// BuildS3Config constructs an S3 Config and does
|
||||
// signature auto-probe when needed.
|
||||
func BuildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
|
||||
func BuildS3Config(ctx context.Context, url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
|
||||
|
||||
s3Config := NewS3Config(url, &hostConfigV9{
|
||||
AccessKey: accessKey,
|
||||
@@ -225,7 +226,7 @@ func BuildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *pro
|
||||
return s3Config, nil
|
||||
}
|
||||
// Probe S3 signature version
|
||||
api, err := probeS3Signature(accessKey, secretKey, url)
|
||||
api, err := probeS3Signature(ctx, accessKey, secretKey, url)
|
||||
if err != nil {
|
||||
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
|
||||
}
|
||||
@@ -272,22 +273,26 @@ func fetchHostKeys(args cli.Args) (string, string) {
|
||||
return accessKey, secretKey
|
||||
}
|
||||
|
||||
func mainConfigHostAdd(ctx *cli.Context) error {
|
||||
func mainConfigHostAdd(cli *cli.Context) error {
|
||||
|
||||
console.SetColor("HostMessage", color.New(color.FgGreen))
|
||||
var (
|
||||
args = ctx.Args()
|
||||
args = cli.Args()
|
||||
alias = cleanAlias(args.Get(0))
|
||||
url = trimTrailingSeparator(args.Get(1))
|
||||
api = ctx.String("api")
|
||||
lookup = ctx.String("lookup")
|
||||
api = cli.String("api")
|
||||
lookup = cli.String("lookup")
|
||||
)
|
||||
accessKey, secretKey := fetchHostKeys(args)
|
||||
checkConfigHostAddSyntax(ctx, accessKey, secretKey)
|
||||
checkConfigHostAddSyntax(cli, accessKey, secretKey)
|
||||
|
||||
s3Config, err := BuildS3Config(url, accessKey, secretKey, api, lookup)
|
||||
fatalIf(err.Trace(ctx.Args()...), "Unable to initialize new config from the provided credentials.")
|
||||
ctx, cancelHostAdd := context.WithCancel(globalContext)
|
||||
defer cancelHostAdd()
|
||||
|
||||
addHost(ctx.Args().Get(0), hostConfigV9{
|
||||
s3Config, err := BuildS3Config(ctx, url, accessKey, secretKey, api, lookup)
|
||||
fatalIf(err.Trace(cli.Args()...), "Unable to initialize new config from the provided credentials.")
|
||||
|
||||
addHost(alias, hostConfigV9{
|
||||
URL: s3Config.HostURL,
|
||||
AccessKey: s3Config.AccessKey,
|
||||
SecretKey: s3Config.SecretKey,
|
||||
|
||||
+4
-10
@@ -30,7 +30,7 @@ var configHostListCmd = cli.Command{
|
||||
ShortName: "ls",
|
||||
Usage: "list hosts in configuration file",
|
||||
Action: mainConfigHostList,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -59,13 +59,6 @@ func checkConfigHostListSyntax(ctx *cli.Context) {
|
||||
fatalIf(errInvalidArgument().Trace(args...),
|
||||
"Incorrect number of arguments to list hosts.")
|
||||
}
|
||||
|
||||
if args.Get(0) != "" {
|
||||
if !isValidAlias(args.Get(0)) {
|
||||
fatalIf(errDummy().Trace(args.Get(0)),
|
||||
"Invalid alias `"+args.Get(0)+"`.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mainConfigHostList(ctx *cli.Context) error {
|
||||
@@ -79,8 +72,9 @@ func mainConfigHostList(ctx *cli.Context) error {
|
||||
console.SetColor("API", color.New(color.FgBlue))
|
||||
console.SetColor("Lookup", color.New(color.FgCyan))
|
||||
|
||||
args := ctx.Args()
|
||||
listHosts(args.Get(0)) // List all configured hosts.
|
||||
alias := cleanAlias(ctx.Args().Get(0))
|
||||
|
||||
listHosts(alias) // List all configured hosts.
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ var configHostRemoveCmd = cli.Command{
|
||||
ShortName: "rm",
|
||||
Usage: "remove a host from configuration file",
|
||||
Action: mainConfigHostRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -55,9 +55,9 @@ func checkConfigHostRemoveSyntax(ctx *cli.Context) {
|
||||
"Incorrect number of arguments for remove host command.")
|
||||
}
|
||||
|
||||
if !isValidAlias(args.Get(0)) {
|
||||
fatalIf(errDummy().Trace(args.Get(0)),
|
||||
"Invalid alias `"+args.Get(0)+"`.")
|
||||
alias := cleanAlias(args.Get(0))
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errDummy().Trace(alias), "Invalid alias `"+alias+"`.")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@ var configHostCmd = cli.Command{
|
||||
Name: "host",
|
||||
Usage: "add, remove and list hosts in configuration file",
|
||||
Action: mainConfigHost,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
configHostAddCmd,
|
||||
|
||||
@@ -37,7 +37,6 @@ var configCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "configure MinIO client",
|
||||
Action: mainConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
HideHelpCommand: true,
|
||||
Flags: append(configFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
|
||||
+6
-5
@@ -37,11 +37,12 @@ var (
|
||||
|
||||
// hostConfig configuration of a host.
|
||||
type hostConfigV9 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
Lookup string `json:"lookup"`
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
SessionToken string `json:"sessionToken,omitempty"`
|
||||
API string `json:"api"`
|
||||
Lookup string `json:"lookup"`
|
||||
}
|
||||
|
||||
// configV8 config version.
|
||||
|
||||
+54
-62
@@ -159,6 +159,14 @@ func isMcConfigExists() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// cleanAlias removes any forbidden trailing slashes or backslashes
|
||||
// before any validation to avoid annoying mc complaints.
|
||||
func cleanAlias(s string) string {
|
||||
s = strings.TrimSuffix(s, "/")
|
||||
s = strings.TrimSuffix(s, "\\")
|
||||
return s
|
||||
}
|
||||
|
||||
// isValidAlias - Check if alias valid.
|
||||
func isValidAlias(alias string) bool {
|
||||
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias)
|
||||
@@ -200,73 +208,56 @@ func mustGetHostConfig(alias string) *hostConfigV9 {
|
||||
return hostCfg
|
||||
}
|
||||
|
||||
var (
|
||||
hostKeys = regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)$")
|
||||
hostKeyTokens = regexp.MustCompile("^(https?://)(.*?):(.*?):(.*?)@(.*?)$")
|
||||
)
|
||||
|
||||
// parse url usually obtained from env.
|
||||
func parseEnvURL(envURL string) (*url.URL, string, string, *probe.Error) {
|
||||
u, e := url.Parse(envURL)
|
||||
func parseEnvURLStr(envURL string) (*url.URL, string, string, string, *probe.Error) {
|
||||
var accessKey, secretKey, sessionToken string
|
||||
var parsedURL string
|
||||
if hostKeyTokens.MatchString(envURL) {
|
||||
parts := hostKeyTokens.FindStringSubmatch(envURL)
|
||||
if len(parts) != 6 {
|
||||
return nil, "", "", "", errInvalidArgument().Trace(envURL)
|
||||
}
|
||||
accessKey = parts[2]
|
||||
secretKey = parts[3]
|
||||
sessionToken = parts[4]
|
||||
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[5])
|
||||
} else if hostKeys.MatchString(envURL) {
|
||||
parts := hostKeys.FindStringSubmatch(envURL)
|
||||
if len(parts) != 5 {
|
||||
return nil, "", "", "", errInvalidArgument().Trace(envURL)
|
||||
}
|
||||
accessKey = parts[2]
|
||||
secretKey = parts[3]
|
||||
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[4])
|
||||
}
|
||||
var u *url.URL
|
||||
var e error
|
||||
if parsedURL != "" {
|
||||
u, e = url.Parse(parsedURL)
|
||||
} else {
|
||||
u, e = url.Parse(envURL)
|
||||
}
|
||||
if e != nil {
|
||||
return nil, "", "", probe.NewError(e).Trace(envURL)
|
||||
return nil, "", "", "", probe.NewError(e)
|
||||
}
|
||||
|
||||
var accessKey, secretKey string
|
||||
// Check if username:password is provided in URL, with no
|
||||
// access keys or secret we proceed and perform anonymous
|
||||
// requests.
|
||||
if u.User != nil {
|
||||
accessKey = u.User.Username()
|
||||
secretKey, _ = u.User.Password()
|
||||
}
|
||||
|
||||
// Look for if URL has invalid values and return error.
|
||||
if !((u.Scheme == "http" || u.Scheme == "https") &&
|
||||
(u.Path == "/" || u.Path == "") && u.Opaque == "" &&
|
||||
!u.ForceQuery && u.RawQuery == "" && u.Fragment == "") {
|
||||
return nil, "", "", errInvalidArgument().Trace(u.String())
|
||||
return nil, "", "", "", errInvalidArgument().Trace(u.String())
|
||||
}
|
||||
|
||||
// Now that we have validated the URL to be in expected style.
|
||||
u.User = nil
|
||||
|
||||
return u, accessKey, secretKey, nil
|
||||
}
|
||||
|
||||
// parse url usually obtained from env.
|
||||
func parseEnvURLStr(envURL string) (*url.URL, string, string, *probe.Error) {
|
||||
var envURLStr string
|
||||
u, accessKey, secretKey, err := parseEnvURL(envURL)
|
||||
if err != nil {
|
||||
// url parsing can fail when accessKey/secretKey contains non url encoded values
|
||||
// such as #. Strip accessKey/secretKey from envURL and parse again.
|
||||
re := regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)$")
|
||||
res := re.FindAllStringSubmatch(envURL, -1)
|
||||
// regex will return full match, scheme, accessKey, secretKey and endpoint:port as
|
||||
// captured groups.
|
||||
if res == nil || len(res[0]) != 5 {
|
||||
return nil, "", "", err
|
||||
}
|
||||
for k, v := range res[0] {
|
||||
if k == 2 {
|
||||
accessKey = v
|
||||
}
|
||||
if k == 3 {
|
||||
secretKey = v
|
||||
}
|
||||
if k == 1 || k == 4 {
|
||||
envURLStr = fmt.Sprintf("%s%s", envURLStr, v)
|
||||
}
|
||||
}
|
||||
u, _, _, err = parseEnvURL(envURLStr)
|
||||
if err != nil {
|
||||
return nil, "", "", err
|
||||
if accessKey == "" && secretKey == "" {
|
||||
if u.User != nil {
|
||||
accessKey = u.User.Username()
|
||||
secretKey, _ = u.User.Password()
|
||||
}
|
||||
}
|
||||
// Check if username:password is provided in URL, with no
|
||||
// access keys or secret we proceed and perform anonymous
|
||||
// requests.
|
||||
if u.User != nil {
|
||||
accessKey = u.User.Username()
|
||||
secretKey, _ = u.User.Password()
|
||||
}
|
||||
return u, accessKey, secretKey, nil
|
||||
return u, accessKey, secretKey, sessionToken, nil
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -275,16 +266,17 @@ const (
|
||||
)
|
||||
|
||||
func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
|
||||
u, accessKey, secretKey, err := parseEnvURLStr(envURL)
|
||||
u, accessKey, secretKey, sessionToken, err := parseEnvURLStr(envURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(envURL)
|
||||
}
|
||||
|
||||
return &hostConfigV9{
|
||||
URL: u.String(),
|
||||
API: "S3v4",
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
URL: u.String(),
|
||||
API: "S3v4",
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
SessionToken: sessionToken,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
+73
-23
@@ -21,11 +21,12 @@ import "testing"
|
||||
// Tests valid host URL functionality.
|
||||
func TestParseEnvURLStr(t *testing.T) {
|
||||
testCases := []struct {
|
||||
hostURL string
|
||||
accessKey string
|
||||
secretKey string
|
||||
hostname string
|
||||
port string
|
||||
hostURL string
|
||||
accessKey string
|
||||
secretKey string
|
||||
sessionToken string
|
||||
hostname string
|
||||
port string
|
||||
}{
|
||||
{
|
||||
hostURL: "https://minio:minio1#23@localhost:9000",
|
||||
@@ -48,30 +49,79 @@ func TestParseEnvURLStr(t *testing.T) {
|
||||
hostname: "localhost",
|
||||
port: "9000",
|
||||
},
|
||||
{
|
||||
hostURL: "https://minio:minio123:token@localhost:9000",
|
||||
accessKey: "minio",
|
||||
secretKey: "minio123",
|
||||
sessionToken: "token",
|
||||
hostname: "localhost",
|
||||
port: "9000",
|
||||
},
|
||||
{
|
||||
hostURL: "https://minio@localhost:9000",
|
||||
accessKey: "minio",
|
||||
hostname: "localhost",
|
||||
port: "9000",
|
||||
},
|
||||
{
|
||||
hostURL: "https://minio:@localhost:9000",
|
||||
accessKey: "minio",
|
||||
hostname: "localhost",
|
||||
port: "9000",
|
||||
},
|
||||
{
|
||||
hostURL: "https://:@localhost:9000",
|
||||
hostname: "localhost",
|
||||
port: "9000",
|
||||
},
|
||||
{
|
||||
hostURL: "https://:minio123@localhost:9000",
|
||||
hostname: "localhost",
|
||||
secretKey: "minio123",
|
||||
port: "9000",
|
||||
},
|
||||
{
|
||||
hostURL: "https://:minio123:token@localhost:9000",
|
||||
hostname: "localhost",
|
||||
secretKey: "minio123",
|
||||
sessionToken: "token",
|
||||
port: "9000",
|
||||
},
|
||||
{
|
||||
hostURL: "https://:minio123:@localhost:9000",
|
||||
hostname: "localhost",
|
||||
secretKey: "minio123",
|
||||
port: "9000",
|
||||
},
|
||||
}
|
||||
|
||||
for i, testCase := range testCases {
|
||||
url, ak, sk, err := parseEnvURLStr(testCase.hostURL)
|
||||
if testCase.accessKey != ak {
|
||||
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.accessKey, ak)
|
||||
}
|
||||
if testCase.secretKey != sk {
|
||||
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.secretKey, sk)
|
||||
}
|
||||
if testCase.hostname != url.Hostname() {
|
||||
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.hostname, url.Hostname())
|
||||
}
|
||||
if testCase.port != url.Port() {
|
||||
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.port, url.Port())
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Expected test to pass. Failed with err %s", i+1, err)
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
t.Run("", func(t *testing.T) {
|
||||
url, ak, sk, token, err := parseEnvURLStr(testCase.hostURL)
|
||||
if testCase.accessKey != ak {
|
||||
t.Fatalf("Expected %s, got %s", testCase.accessKey, ak)
|
||||
}
|
||||
if testCase.secretKey != sk {
|
||||
t.Fatalf("Expected %s, got %s", testCase.secretKey, sk)
|
||||
}
|
||||
if testCase.sessionToken != token {
|
||||
t.Fatalf("Expected %s, got %s", testCase.sessionToken, token)
|
||||
}
|
||||
if testCase.hostname != url.Hostname() {
|
||||
t.Fatalf("Expected %s, got %s", testCase.hostname, url.Hostname())
|
||||
}
|
||||
if testCase.port != url.Port() {
|
||||
t.Fatalf("Expected %s, got %s", testCase.port, url.Port())
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Expected test to pass. Failed with err %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEnvURLStrInvalid(t *testing.T) {
|
||||
_, _, _, err := parseEnvURLStr("")
|
||||
_, _, _, _, err := parseEnvURLStr("")
|
||||
if err == nil {
|
||||
t.Fatalf("Expected failure")
|
||||
}
|
||||
|
||||
+77
-55
@@ -73,6 +73,10 @@ var (
|
||||
Name: "disable-multipart",
|
||||
Usage: "disable multipart upload feature",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "md5",
|
||||
Usage: "force all upload(s) to calculate md5sum checksum",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: rmFlag,
|
||||
Usage: "retention mode to be applied on the object (governance, compliance)",
|
||||
@@ -100,7 +104,7 @@ var cpCmd = cli.Command{
|
||||
Name: "cp",
|
||||
Usage: "copy objects",
|
||||
Action: mainCopy,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(append(cpFlags, ioFlags...), globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -212,7 +216,7 @@ type ProgressReader interface {
|
||||
}
|
||||
|
||||
// doCopy - Copy a single file from source to destination
|
||||
func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) URLs {
|
||||
func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair, isMvCmd bool, preserve bool) URLs {
|
||||
if cpURLs.Error != nil {
|
||||
cpURLs.Error = cpURLs.Error.Trace()
|
||||
return cpURLs
|
||||
@@ -238,30 +242,30 @@ func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[st
|
||||
})
|
||||
}
|
||||
|
||||
urls := uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB)
|
||||
urls := uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB, preserve)
|
||||
if isMvCmd && urls.Error == nil {
|
||||
bgRemove(sourcePath)
|
||||
bgRemove(ctx, sourcePath)
|
||||
}
|
||||
|
||||
return urls
|
||||
}
|
||||
|
||||
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
|
||||
func doCopyFake(cpURLs URLs, pg Progress, isMvCmd bool) URLs {
|
||||
func doCopyFake(ctx context.Context, cpURLs URLs, pg Progress, isMvCmd bool) URLs {
|
||||
if progressReader, ok := pg.(*progressBar); ok {
|
||||
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
|
||||
}
|
||||
|
||||
if isMvCmd {
|
||||
sourcePath := filepath.ToSlash(filepath.Join(cpURLs.SourceAlias, cpURLs.SourceContent.URL.Path))
|
||||
bgRemove(sourcePath)
|
||||
bgRemove(ctx, sourcePath)
|
||||
}
|
||||
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
|
||||
func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) {
|
||||
func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) {
|
||||
// Separate source and target. 'cp' can take only one target,
|
||||
// but any number of sources.
|
||||
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
|
||||
@@ -285,7 +289,7 @@ func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (total
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
|
||||
URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
|
||||
done := false
|
||||
for !done {
|
||||
select {
|
||||
@@ -337,10 +341,7 @@ func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (total
|
||||
return
|
||||
}
|
||||
|
||||
func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) error {
|
||||
ctx, cancelCopy := context.WithCancel(globalContext)
|
||||
defer cancelCopy()
|
||||
|
||||
func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) error {
|
||||
var isCopied func(string) bool
|
||||
var totalObjects, totalBytes int64
|
||||
|
||||
@@ -362,7 +363,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
isCopied = isLastFactory(session.Header.LastCopied)
|
||||
|
||||
if !session.HasData() {
|
||||
totalBytes, totalObjects = doPrepareCopyURLs(session, cancelCopy)
|
||||
totalBytes, totalObjects = doPrepareCopyURLs(ctx, session, cancelCopy)
|
||||
} else {
|
||||
totalBytes, totalObjects = session.Header.TotalBytes, session.Header.TotalObjects
|
||||
}
|
||||
@@ -399,7 +400,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
|
||||
go func() {
|
||||
totalBytes := int64(0)
|
||||
for cpURLs := range prepareCopyURLs(sourceURLs, targetURL, isRecursive,
|
||||
for cpURLs := range prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive,
|
||||
encKeyDB, olderThan, newerThan) {
|
||||
if cpURLs.Error != nil {
|
||||
// Print in new line and adjust to top so that we
|
||||
@@ -419,6 +420,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
} else {
|
||||
totalBytes += cpURLs.SourceContent.Size
|
||||
pg.SetTotal(totalBytes)
|
||||
totalObjects++
|
||||
}
|
||||
cpURLsCh <- cpURLs
|
||||
}
|
||||
@@ -469,17 +471,25 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
// update Object retention related fields
|
||||
if session != nil {
|
||||
cpURLs.TargetContent.RetentionMode = session.Header.CommandStringFlags[rmFlag]
|
||||
if cpURLs.TargetContent.RetentionMode != "" {
|
||||
cpURLs.TargetContent.RetentionEnabled = true
|
||||
}
|
||||
cpURLs.TargetContent.RetentionDuration = session.Header.CommandStringFlags[rdFlag]
|
||||
cpURLs.TargetContent.LegalHold = session.Header.CommandStringFlags[lhFlag]
|
||||
cpURLs.TargetContent.LegalHold = strings.ToUpper(session.Header.CommandStringFlags[lhFlag])
|
||||
if cpURLs.TargetContent.LegalHold != "" {
|
||||
cpURLs.TargetContent.LegalHoldEnabled = true
|
||||
}
|
||||
} else {
|
||||
if rm := cli.String(rmFlag); rm != "" {
|
||||
cpURLs.TargetContent.RetentionMode = rm
|
||||
cpURLs.TargetContent.RetentionEnabled = true
|
||||
}
|
||||
if rd := cli.String(rdFlag); rd != "" {
|
||||
cpURLs.TargetContent.RetentionDuration = rd
|
||||
}
|
||||
if lh := cli.String(lhFlag); lh != "" {
|
||||
cpURLs.TargetContent.LegalHold = lh
|
||||
cpURLs.TargetContent.LegalHold = strings.ToUpper(lh)
|
||||
cpURLs.TargetContent.LegalHoldEnabled = true
|
||||
}
|
||||
}
|
||||
if cli.String("attr") != "" {
|
||||
@@ -489,29 +499,18 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
}
|
||||
}
|
||||
|
||||
// If one needs to store the file system information by passing -a flag
|
||||
if preserve := cli.Bool("preserve"); preserve {
|
||||
attrValue, pErr := getFileAttrMeta(cpURLs, encKeyDB)
|
||||
if pErr != nil {
|
||||
errorIf(pErr, "Unable to fetch file meta info for %s", cpURLs.SourceAlias)
|
||||
continue
|
||||
}
|
||||
|
||||
if attrValue != "" {
|
||||
cpURLs.TargetContent.Metadata["mc-attrs"] = attrValue
|
||||
}
|
||||
}
|
||||
|
||||
preserve := cli.Bool("preserve")
|
||||
cpURLs.MD5 = cli.Bool("md5")
|
||||
cpURLs.DisableMultipart = cli.Bool("disable-multipart")
|
||||
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied != nil && isCopied(cpURLs.SourceContent.URL.String()) {
|
||||
queueCh <- func() URLs {
|
||||
return doCopyFake(cpURLs, pg, isMvCmd)
|
||||
return doCopyFake(ctx, cpURLs, pg, isMvCmd)
|
||||
}
|
||||
} else {
|
||||
queueCh <- func() URLs {
|
||||
return doCopy(ctx, cpURLs, pg, encKeyDB, isMvCmd)
|
||||
return doCopy(ctx, cpURLs, pg, encKeyDB, isMvCmd, preserve)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -519,6 +518,8 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
}()
|
||||
|
||||
var retErr error
|
||||
errSeen := false
|
||||
cpAllFilesErr := true
|
||||
|
||||
loop:
|
||||
for {
|
||||
@@ -544,6 +545,7 @@ loop:
|
||||
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
|
||||
session.Save()
|
||||
}
|
||||
cpAllFilesErr = false
|
||||
} else {
|
||||
|
||||
// Set exit status for any copy error
|
||||
@@ -557,9 +559,23 @@ loop:
|
||||
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
|
||||
if isErrIgnored(cpURLs.Error) {
|
||||
cpAllFilesErr = false
|
||||
continue loop
|
||||
}
|
||||
|
||||
errSeen = true
|
||||
if progressReader, pgok := pg.(*progressBar); pgok {
|
||||
if progressReader.ProgressBar.Get() > 0 {
|
||||
writeContSize := (int)(cpURLs.SourceContent.Size)
|
||||
totalPGSize := (int)(progressReader.ProgressBar.Total)
|
||||
written := (int)(progressReader.ProgressBar.Get())
|
||||
if totalPGSize > writeContSize && written > writeContSize {
|
||||
progressReader.ProgressBar.Set((written - writeContSize))
|
||||
progressReader.ProgressBar.Update()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if session != nil {
|
||||
// For critical errors we should exit. Session
|
||||
// can be resumed after the user figures out
|
||||
@@ -571,7 +587,9 @@ loop:
|
||||
}
|
||||
|
||||
if progressReader, ok := pg.(*progressBar); ok {
|
||||
if progressReader.ProgressBar.Get() > 0 {
|
||||
if (errSeen && totalObjects == 1) || (cpAllFilesErr && totalObjects > 1) {
|
||||
console.Eraseline()
|
||||
} else if progressReader.ProgressBar.Get() > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
@@ -597,33 +615,36 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
|
||||
}
|
||||
|
||||
// mainCopy is the entry point for cp command.
|
||||
func mainCopy(ctx *cli.Context) error {
|
||||
func mainCopy(cliCtx *cli.Context) error {
|
||||
ctx, cancelCopy := context.WithCancel(globalContext)
|
||||
defer cancelCopy()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// Parse metadata.
|
||||
userMetaMap := make(map[string]string)
|
||||
if ctx.String("attr") != "" {
|
||||
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
|
||||
if cliCtx.String("attr") != "" {
|
||||
userMetaMap, err = getMetaDataEntry(cliCtx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", cliCtx.String("attr"))
|
||||
}
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx, encKeyDB, false)
|
||||
checkCopySyntax(ctx, cliCtx, encKeyDB, false)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
recursive := ctx.Bool("recursive")
|
||||
olderThan := ctx.String("older-than")
|
||||
newerThan := ctx.String("newer-than")
|
||||
storageClass := ctx.String("storage-class")
|
||||
retentionMode := ctx.String(rmFlag)
|
||||
retentionDuration := ctx.String(rdFlag)
|
||||
legalHold := ctx.String(lhFlag)
|
||||
recursive := cliCtx.Bool("recursive")
|
||||
olderThan := cliCtx.String("older-than")
|
||||
newerThan := cliCtx.String("newer-than")
|
||||
storageClass := cliCtx.String("storage-class")
|
||||
retentionMode := cliCtx.String(rmFlag)
|
||||
retentionDuration := cliCtx.String(rdFlag)
|
||||
legalHold := strings.ToUpper(cliCtx.String(lhFlag))
|
||||
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
|
||||
if key := ctx.String("encrypt-key"); key != "" {
|
||||
if key := cliCtx.String("encrypt-key"); key != "" {
|
||||
sseKeys = key
|
||||
}
|
||||
|
||||
@@ -631,12 +652,12 @@ func mainCopy(ctx *cli.Context) error {
|
||||
sseKeys, err = getDecodedKey(sseKeys)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
}
|
||||
sse := ctx.String("encrypt")
|
||||
sse := cliCtx.String("encrypt")
|
||||
|
||||
var session *sessionV8
|
||||
|
||||
if ctx.Bool("continue") {
|
||||
sessionID := getHash("cp", ctx.Args())
|
||||
if cliCtx.Bool("continue") {
|
||||
sessionID := getHash("cp", cliCtx.Args())
|
||||
if isSessionExists(sessionID) {
|
||||
session, err = loadSessionV8(sessionID)
|
||||
fatalIf(err.Trace(sessionID), "Unable to load session.")
|
||||
@@ -652,13 +673,14 @@ func mainCopy(ctx *cli.Context) error {
|
||||
session.Header.CommandStringFlags[lhFlag] = legalHold
|
||||
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
|
||||
session.Header.CommandStringFlags["encrypt"] = sse
|
||||
session.Header.CommandBoolFlags["session"] = ctx.Bool("continue")
|
||||
session.Header.CommandBoolFlags["session"] = cliCtx.Bool("continue")
|
||||
|
||||
if ctx.Bool("preserve") {
|
||||
session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve")
|
||||
if cliCtx.Bool("preserve") {
|
||||
session.Header.CommandBoolFlags["preserve"] = cliCtx.Bool("preserve")
|
||||
}
|
||||
session.Header.UserMetaData = userMetaMap
|
||||
session.Header.CommandBoolFlags["disable-multipart"] = ctx.Bool("disable-multipart")
|
||||
session.Header.CommandBoolFlags["md5"] = cliCtx.Bool("md5")
|
||||
session.Header.CommandBoolFlags["disable-multipart"] = cliCtx.Bool("disable-multipart")
|
||||
|
||||
var e error
|
||||
if session.Header.RootPath, e = os.Getwd(); e != nil {
|
||||
@@ -667,11 +689,11 @@ func mainCopy(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
session.Header.CommandArgs = cliCtx.Args()
|
||||
}
|
||||
}
|
||||
|
||||
e := doCopySession(ctx, session, encKeyDB, false)
|
||||
e := doCopySession(ctx, cancelCopy, cliCtx, session, encKeyDB, false)
|
||||
if session != nil {
|
||||
session.Delete()
|
||||
}
|
||||
|
||||
+27
-26
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"runtime"
|
||||
|
||||
@@ -24,27 +25,27 @@ import (
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
if len(ctx.Args()) < 2 {
|
||||
func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
if len(cliCtx.Args()) < 2 {
|
||||
if isMvCmd {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mv", 1) // last argument is exit code.
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "mv", 1) // last argument is exit code.
|
||||
}
|
||||
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "cp", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
URLs := cliCtx.Args()
|
||||
if len(URLs) < 2 {
|
||||
fatalIf(errDummy().Trace(ctx.Args()...), "Unable to parse source and target arguments.")
|
||||
fatalIf(errDummy().Trace(cliCtx.Args()...), "Unable to parse source and target arguments.")
|
||||
}
|
||||
|
||||
srcURLs := URLs[:len(URLs)-1]
|
||||
tgtURL := URLs[len(URLs)-1]
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
|
||||
// Verify if source(s) exists.
|
||||
for _, srcURL := range srcURLs {
|
||||
_, _, err := url2Stat(srcURL, false, encKeyDB)
|
||||
_, _, err := url2Stat(ctx, srcURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
console.Fatalf("Unable to validate source %s\n", srcURL)
|
||||
}
|
||||
@@ -58,11 +59,11 @@ func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMv
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.String(rdFlag) != "" && ctx.String(rmFlag) == "" {
|
||||
if cliCtx.String(rdFlag) != "" && cliCtx.String(rmFlag) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Both object retention flags `--%s` and `--%s` are required.\n", rdFlag, rmFlag))
|
||||
}
|
||||
|
||||
if ctx.String(rdFlag) == "" && ctx.String(rmFlag) != "" {
|
||||
if cliCtx.String(rdFlag) == "" && cliCtx.String(rmFlag) != "" {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Both object retention flags `--%s` and `--%s` are required.\n", rdFlag, rmFlag))
|
||||
}
|
||||
|
||||
@@ -72,38 +73,38 @@ func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMv
|
||||
}
|
||||
|
||||
// Guess CopyURLsType based on source and target URLs.
|
||||
copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive, encKeyDB)
|
||||
copyURLsType, err := guessCopyURLType(ctx, srcURLs, tgtURL, isRecursive, encKeyDB)
|
||||
if err != nil {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.")
|
||||
}
|
||||
|
||||
switch copyURLsType {
|
||||
case copyURLsTypeA: // File -> File.
|
||||
checkCopySyntaxTypeA(srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeA(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
case copyURLsTypeB: // File -> Folder.
|
||||
checkCopySyntaxTypeB(srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeB(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
case copyURLsTypeC: // Folder... -> Folder.
|
||||
checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeC(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd)
|
||||
case copyURLsTypeD: // File1...FileN -> Folder.
|
||||
checkCopySyntaxTypeD(srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeD(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.")
|
||||
}
|
||||
|
||||
// Preserve functionality not supported for windows
|
||||
if ctx.Bool("preserve") && runtime.GOOS == "windows" {
|
||||
if cliCtx.Bool("preserve") && runtime.GOOS == "windows" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Permissions are not preserved on windows platform.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
|
||||
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
func checkCopySyntaxTypeA(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL, false, keys)
|
||||
_, srcContent, err := url2Stat(ctx, srcURL, false, keys)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
@@ -112,13 +113,13 @@ func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]pre
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
|
||||
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
srcURL := srcURLs[0]
|
||||
_, srcContent, err := url2Stat(srcURL, false, keys)
|
||||
_, srcContent, err := url2Stat(ctx, srcURL, false, keys)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
@@ -126,7 +127,7 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]pre
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
|
||||
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
|
||||
}
|
||||
@@ -134,21 +135,21 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]pre
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
|
||||
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
func checkCopySyntaxTypeC(ctx context.Context, srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
// Check source.
|
||||
if len(srcURLs) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
|
||||
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
|
||||
}
|
||||
}
|
||||
|
||||
for _, srcURL := range srcURLs {
|
||||
c, srcContent, err := url2Stat(srcURL, false, keys)
|
||||
c, srcContent, err := url2Stat(ctx, srcURL, false, keys)
|
||||
// incomplete uploads are not necessary for copy operation, no need to verify for them.
|
||||
isIncomplete := false
|
||||
if err != nil {
|
||||
@@ -183,10 +184,10 @@ func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, key
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
|
||||
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
func checkCopySyntaxTypeD(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
// Source can be anything: file, dir, dir...
|
||||
// Check target if it is a dir
|
||||
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
|
||||
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
|
||||
if !tgtContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
|
||||
}
|
||||
|
||||
+19
-23
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -50,10 +51,10 @@ const (
|
||||
|
||||
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
|
||||
// functions to accurately report failure causes.
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
|
||||
func guessCopyURLType(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
|
||||
if len(sourceURLs) == 1 { // 1 Source, 1 Target
|
||||
sourceURL := sourceURLs[0]
|
||||
_, sourceContent, err := url2Stat(sourceURL, false, keys)
|
||||
_, sourceContent, err := url2Stat(ctx, sourceURL, false, keys)
|
||||
if err != nil {
|
||||
return copyURLsTypeInvalid, err
|
||||
}
|
||||
@@ -65,7 +66,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, k
|
||||
}
|
||||
|
||||
// If target is a folder, it is Type B.
|
||||
if isAliasURLDir(targetURL, keys) {
|
||||
if isAliasURLDir(ctx, targetURL, keys) {
|
||||
return copyURLsTypeB, nil
|
||||
}
|
||||
// else Type A.
|
||||
@@ -73,7 +74,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, k
|
||||
}
|
||||
|
||||
// Multiple source args and target is a folder. It is Type D.
|
||||
if isAliasURLDir(targetURL, keys) {
|
||||
if isAliasURLDir(ctx, targetURL, keys) {
|
||||
return copyURLsTypeD, nil
|
||||
}
|
||||
|
||||
@@ -82,13 +83,13 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, k
|
||||
|
||||
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
|
||||
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
func prepareCopyURLsTypeA(ctx context.Context, sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL, false, encKeyDB)
|
||||
_, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return URLs{Error: err.Trace(sourceURL)}
|
||||
@@ -115,13 +116,13 @@ func makeCopyContentTypeA(sourceAlias string, sourceContent *ClientContent, targ
|
||||
|
||||
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
|
||||
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
func prepareCopyURLsTypeB(ctx context.Context, sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL, false, encKeyDB)
|
||||
_, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
// Source does not exist or insufficient privileges.
|
||||
return URLs{Error: err.Trace(sourceURL)}
|
||||
@@ -149,7 +150,7 @@ func makeCopyContentTypeB(sourceAlias string, sourceContent *ClientContent, targ
|
||||
|
||||
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded clientURL.
|
||||
@@ -165,7 +166,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool, encKeyD
|
||||
}
|
||||
|
||||
isIncomplete := false
|
||||
for sourceContent := range sourceClient.List(isRecursive, isIncomplete, false, DirNone) {
|
||||
for sourceContent := range sourceClient.List(ctx, isRecursive, isIncomplete, false, DirNone) {
|
||||
if sourceContent.Err != nil {
|
||||
// Listing failed.
|
||||
copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
|
||||
@@ -191,11 +192,6 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL ClientURL, sourceContent
|
||||
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
|
||||
if pathSeparatorIndex > 1 {
|
||||
sourcePrefix := filepath.ToSlash(sourceURL.Path[:pathSeparatorIndex])
|
||||
// do not preserve unix cp behavior when copying from filesytem to
|
||||
// objectstore.
|
||||
if sourceAlias == "" && targetAlias != "" {
|
||||
sourcePrefix = sourceURL.Path
|
||||
}
|
||||
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
|
||||
}
|
||||
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
|
||||
@@ -204,12 +200,12 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL ClientURL, sourceContent
|
||||
|
||||
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
|
||||
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) {
|
||||
defer close(copyURLsCh)
|
||||
for _, sourceURL := range sourceURLs {
|
||||
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive, encKeyDB) {
|
||||
for cpURLs := range prepareCopyURLsTypeC(ctx, sourceURL, targetURL, isRecursive, encKeyDB) {
|
||||
copyURLsCh <- cpURLs
|
||||
}
|
||||
}
|
||||
@@ -218,24 +214,24 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
|
||||
}
|
||||
|
||||
// prepareCopyURLs - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair, olderThan, newerThan string) chan URLs {
|
||||
func prepareCopyURLs(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair, olderThan, newerThan string) chan URLs {
|
||||
copyURLsCh := make(chan URLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
|
||||
defer close(copyURLsCh)
|
||||
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive, encKeyDB)
|
||||
cpType, err := guessCopyURLType(ctx, sourceURLs, targetURL, isRecursive, encKeyDB)
|
||||
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
|
||||
|
||||
switch cpType {
|
||||
case copyURLsTypeA:
|
||||
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL, encKeyDB)
|
||||
copyURLsCh <- prepareCopyURLsTypeA(ctx, sourceURLs[0], targetURL, encKeyDB)
|
||||
case copyURLsTypeB:
|
||||
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB)
|
||||
copyURLsCh <- prepareCopyURLsTypeB(ctx, sourceURLs[0], targetURL, encKeyDB)
|
||||
case copyURLsTypeC:
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) {
|
||||
for cURLs := range prepareCopyURLsTypeC(ctx, sourceURLs[0], targetURL, isRecursive, encKeyDB) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
case copyURLsTypeD:
|
||||
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive, encKeyDB) {
|
||||
for cURLs := range prepareCopyURLsTypeD(ctx, sourceURLs, targetURL, isRecursive, encKeyDB) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
default:
|
||||
|
||||
+24
-17
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -37,7 +38,7 @@ var diffCmd = cli.Command{
|
||||
Name: "diff",
|
||||
Usage: "list differences in object name, size, and date between two buckets",
|
||||
Action: mainDiff,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(diffFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -90,6 +91,8 @@ func (d diffMessage) String() string {
|
||||
msg = console.Colorize("DiffSize", "! "+d.SecondURL)
|
||||
case differInMetadata:
|
||||
msg = console.Colorize("DiffMetadata", "! "+d.SecondURL)
|
||||
case differInAASourceMTime:
|
||||
msg = console.Colorize("DiffMMSourceMTime", "! "+d.SecondURL)
|
||||
default:
|
||||
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
|
||||
"Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.")
|
||||
@@ -107,23 +110,23 @@ func (d diffMessage) JSON() string {
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code
|
||||
func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(cliCtx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "diff", 1) // last argument is exit code
|
||||
}
|
||||
for _, arg := range ctx.Args() {
|
||||
for _, arg := range cliCtx.Args() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
fatalIf(errInvalidArgument().Trace(cliCtx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
URLs := ctx.Args()
|
||||
URLs := cliCtx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
|
||||
// Diff only works between two directories, verify them below.
|
||||
|
||||
// Verify if firstURL is accessible.
|
||||
_, firstContent, err := url2Stat(firstURL, false, encKeyDB)
|
||||
_, firstContent, err := url2Stat(ctx, firstURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
|
||||
}
|
||||
@@ -134,7 +137,7 @@ func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
}
|
||||
|
||||
// Verify if secondURL is accessible.
|
||||
_, secondContent, err := url2Stat(secondURL, false, encKeyDB)
|
||||
_, secondContent, err := url2Stat(ctx, secondURL, false, encKeyDB)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
|
||||
}
|
||||
@@ -146,7 +149,7 @@ func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
}
|
||||
|
||||
// doDiffMain runs the diff.
|
||||
func doDiffMain(firstURL, secondURL string) error {
|
||||
func doDiffMain(ctx context.Context, firstURL, secondURL string) error {
|
||||
// Source and targets are always directories
|
||||
sourceSeparator := string(newClientURL(firstURL).Separator)
|
||||
if !strings.HasSuffix(firstURL, sourceSeparator) {
|
||||
@@ -174,7 +177,7 @@ func doDiffMain(firstURL, secondURL string) error {
|
||||
}
|
||||
|
||||
// Diff first and second urls.
|
||||
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL, false) {
|
||||
for diffMsg := range objectDifference(ctx, firstClient, secondClient, firstURL, secondURL, true) {
|
||||
if diffMsg.Error != nil {
|
||||
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
|
||||
// Ignore error and proceed to next object.
|
||||
@@ -187,13 +190,16 @@ func doDiffMain(firstURL, secondURL string) error {
|
||||
}
|
||||
|
||||
// mainDiff main for 'diff'.
|
||||
func mainDiff(ctx *cli.Context) error {
|
||||
func mainDiff(cliCtx *cli.Context) error {
|
||||
ctx, cancelDiff := context.WithCancel(globalContext)
|
||||
defer cancelDiff()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'diff' cli arguments.
|
||||
checkDiffSyntax(ctx, encKeyDB)
|
||||
checkDiffSyntax(ctx, cliCtx, encKeyDB)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
|
||||
@@ -201,11 +207,12 @@ func mainDiff(ctx *cli.Context) error {
|
||||
console.SetColor("DiffOnlyInSecond", color.New(color.FgGreen))
|
||||
console.SetColor("DiffType", color.New(color.FgMagenta))
|
||||
console.SetColor("DiffSize", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffMetadata", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffMMSourceMTime", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
URLs := ctx.Args()
|
||||
URLs := cliCtx.Args()
|
||||
firstURL := URLs.Get(0)
|
||||
secondURL := URLs.Get(1)
|
||||
|
||||
return doDiffMain(firstURL, secondURL)
|
||||
return doDiffMain(ctx, firstURL, secondURL)
|
||||
}
|
||||
|
||||
+101
-46
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -32,13 +33,13 @@ import (
|
||||
type differType int
|
||||
|
||||
const (
|
||||
differInNone differType = iota // does not differ
|
||||
differInETag // differs in ETag
|
||||
differInSize // differs in size
|
||||
differInMetadata // differs in metadata
|
||||
differInType // differs in type, exfile/directory
|
||||
differInFirst // only in source (FIRST)
|
||||
differInSecond // only in target (SECOND)
|
||||
differInNone differType = iota // does not differ
|
||||
differInSize // differs in size
|
||||
differInMetadata // differs in metadata
|
||||
differInType // differs in type, exfile/directory
|
||||
differInFirst // only in source (FIRST)
|
||||
differInSecond // only in target (SECOND)
|
||||
differInAASourceMTime // differs in active-active source modtime
|
||||
)
|
||||
|
||||
func (d differType) String() string {
|
||||
@@ -49,6 +50,8 @@ func (d differType) String() string {
|
||||
return "size"
|
||||
case differInMetadata:
|
||||
return "metadata"
|
||||
case differInAASourceMTime:
|
||||
return "mm-source-mtime"
|
||||
case differInType:
|
||||
return "type"
|
||||
case differInFirst:
|
||||
@@ -59,26 +62,81 @@ func (d differType) String() string {
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
const multiMasterETagKey = "X-Amz-Meta-Mm-Etag"
|
||||
const multiMasterSTagKey = "X-Amz-Meta-Mm-Stag"
|
||||
const activeActiveSourceModTimeKey = "X-Amz-Meta-Mm-Source-Mtime"
|
||||
|
||||
func eTagMatch(src, tgt *ClientContent) bool {
|
||||
if tgt.UserMetadata[multiMasterETagKey] != "" {
|
||||
if tgt.UserMetadata[multiMasterETagKey] == src.UserMetadata[multiMasterETagKey] || tgt.UserMetadata[multiMasterETagKey] == src.ETag {
|
||||
return true
|
||||
func getSourceModTimeKey(metadata map[string]string) string {
|
||||
if metadata[activeActiveSourceModTimeKey] != "" {
|
||||
return metadata[activeActiveSourceModTimeKey]
|
||||
}
|
||||
if metadata[strings.ToLower(activeActiveSourceModTimeKey)] != "" {
|
||||
return metadata[strings.ToLower(activeActiveSourceModTimeKey)]
|
||||
}
|
||||
if metadata[strings.ToLower("Mm-Source-Mtime")] != "" {
|
||||
return metadata[strings.ToLower("Mm-Source-Mtime")]
|
||||
}
|
||||
if metadata["Mm-Source-Mtime"] != "" {
|
||||
return metadata["Mm-Source-Mtime"]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// activeActiveModTimeUpdated tries to calculate if the object copy in the target
|
||||
// is older than the one in the source by comparing the modtime of the data.
|
||||
func activeActiveModTimeUpdated(src, dst *ClientContent) bool {
|
||||
if src == nil || dst == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if src.Time.IsZero() || dst.Time.IsZero() {
|
||||
// This should only happen in a messy environment
|
||||
// but we are returning false anyway so the caller
|
||||
// function won't take any action.
|
||||
return false
|
||||
}
|
||||
|
||||
srcModTime := getSourceModTimeKey(src.UserMetadata)
|
||||
dstModTime := getSourceModTimeKey(dst.UserMetadata)
|
||||
if srcModTime == "" && dstModTime == "" {
|
||||
// No active-active mirror context found, consider src & dst as similar
|
||||
return false
|
||||
}
|
||||
|
||||
var srcOriginLastModified, dstOriginLastModified time.Time
|
||||
var err error
|
||||
if srcModTime != "" {
|
||||
srcOriginLastModified, err = time.Parse(time.RFC3339Nano, srcModTime)
|
||||
if err != nil {
|
||||
// failure to parse source modTime, modTime tampered ignore the file
|
||||
return false
|
||||
}
|
||||
}
|
||||
if src.UserMetadata[multiMasterETagKey] != "" {
|
||||
if src.UserMetadata[multiMasterETagKey] == tgt.UserMetadata[multiMasterETagKey] || src.UserMetadata[multiMasterETagKey] == tgt.ETag {
|
||||
return true
|
||||
if dstModTime != "" {
|
||||
dstOriginLastModified, err = time.Parse(time.RFC3339Nano, dstModTime)
|
||||
if err != nil {
|
||||
// failure to parse source modTime, modTime tampered ignore the file
|
||||
return false
|
||||
}
|
||||
}
|
||||
return src.ETag == tgt.ETag
|
||||
|
||||
srcActualModTime := src.Time
|
||||
if !srcOriginLastModified.IsZero() && srcOriginLastModified.After(src.Time) {
|
||||
srcActualModTime = srcOriginLastModified
|
||||
}
|
||||
|
||||
dstActualModTime := dst.Time
|
||||
if !dstOriginLastModified.IsZero() && dstOriginLastModified.After(dst.Time) {
|
||||
dstActualModTime = dstOriginLastModified
|
||||
}
|
||||
|
||||
return srcActualModTime.After(dstActualModTime)
|
||||
}
|
||||
|
||||
func metadataEqual(m1, m2 map[string]string) bool {
|
||||
for k, v := range m1 {
|
||||
if k == multiMasterETagKey || k == multiMasterSTagKey {
|
||||
if k == activeActiveSourceModTimeKey {
|
||||
continue
|
||||
}
|
||||
if k == strings.ToLower(activeActiveSourceModTimeKey) {
|
||||
continue
|
||||
}
|
||||
if m2[k] != v {
|
||||
@@ -86,7 +144,10 @@ func metadataEqual(m1, m2 map[string]string) bool {
|
||||
}
|
||||
}
|
||||
for k, v := range m2 {
|
||||
if k == multiMasterETagKey || k == multiMasterSTagKey {
|
||||
if k == activeActiveSourceModTimeKey {
|
||||
continue
|
||||
}
|
||||
if k == strings.ToLower(activeActiveSourceModTimeKey) {
|
||||
continue
|
||||
}
|
||||
if m1[k] != v {
|
||||
@@ -96,19 +157,19 @@ func metadataEqual(m1, m2 map[string]string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool) (diffCh chan diffMessage) {
|
||||
return difference(sourceClnt, targetClnt, sourceURL, targetURL, isMetadata, true, false, DirNone)
|
||||
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool) (diffCh chan diffMessage) {
|
||||
return difference(ctx, sourceClnt, targetClnt, sourceURL, targetURL, isMetadata, true, false, DirNone)
|
||||
}
|
||||
|
||||
func dirDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
|
||||
return difference(sourceClnt, targetClnt, sourceURL, targetURL, false, false, true, DirFirst)
|
||||
func dirDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
|
||||
return difference(ctx, sourceClnt, targetClnt, sourceURL, targetURL, false, false, true, DirFirst)
|
||||
}
|
||||
|
||||
func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt, diffCh chan<- diffMessage) *probe.Error {
|
||||
func differenceInternal(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt, diffCh chan<- diffMessage) *probe.Error {
|
||||
// Set default values for listing.
|
||||
isIncomplete := false // we will not compare any incomplete objects.
|
||||
srcCh := sourceClnt.List(isRecursive, isIncomplete, isMetadata, dirOpt)
|
||||
tgtCh := targetClnt.List(isRecursive, isIncomplete, isMetadata, dirOpt)
|
||||
srcCh := sourceClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
|
||||
tgtCh := targetClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
|
||||
|
||||
srcCtnt, srcOk := <-srcCh
|
||||
tgtCtnt, tgtOk := <-tgtCh
|
||||
@@ -205,21 +266,7 @@ func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL stri
|
||||
}
|
||||
continue
|
||||
}
|
||||
if eTagMatch(srcCtnt, tgtCtnt) {
|
||||
// If ETag matches, only thing that can differ is metadata.
|
||||
if isMetadata &&
|
||||
!metadataEqual(srcCtnt.UserMetadata, tgtCtnt.UserMetadata) &&
|
||||
!metadataEqual(srcCtnt.Metadata, tgtCtnt.Metadata) {
|
||||
// Regular files user requesting additional metadata to same file.
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInMetadata,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
}
|
||||
} else if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
|
||||
if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
|
||||
// Regular files differing in size.
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
@@ -228,6 +275,14 @@ func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL stri
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
} else if activeActiveModTimeUpdated(srcCtnt, tgtCtnt) {
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInAASourceMTime,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
} else if isMetadata &&
|
||||
!metadataEqual(srcCtnt.UserMetadata, tgtCtnt.UserMetadata) &&
|
||||
!metadataEqual(srcCtnt.Metadata, tgtCtnt.Metadata) {
|
||||
@@ -271,17 +326,17 @@ func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL stri
|
||||
|
||||
// objectDifference function finds the difference between all objects
|
||||
// recursively in sorted order from source and target.
|
||||
func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
|
||||
func difference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
|
||||
diffCh = make(chan diffMessage, 10000)
|
||||
|
||||
go func() {
|
||||
defer close(diffCh)
|
||||
|
||||
doneCh := make(chan struct{}, 1)
|
||||
defer close(doneCh)
|
||||
retryCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
for range newRetryTimerContinous(time.Second, time.Second*30, minio.MaxJitter, doneCh) {
|
||||
err := differenceInternal(sourceClnt, targetClnt, sourceURL, targetURL,
|
||||
for range newRetryTimerContinous(retryCtx, time.Second, time.Second*30, minio.MaxJitter) {
|
||||
err := differenceInternal(retryCtx, sourceClnt, targetClnt, sourceURL, targetURL,
|
||||
isMetadata, isRecursive, returnSimilar, dirOpt, diffCh)
|
||||
if err != nil {
|
||||
// handle this specifically for filesystem related errors.
|
||||
|
||||
+2
-2
@@ -48,7 +48,7 @@ var duCmd = cli.Command{
|
||||
Name: "du",
|
||||
Usage: "summarize disk usage recursively",
|
||||
Action: mainDu,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(append(duFlags, ioFlags...), globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -107,7 +107,7 @@ func du(urlStr string, depth int, encKeyDB map[string][]prefixSSEPair) (int64, e
|
||||
|
||||
isRecursive := false
|
||||
isIncomplete := false
|
||||
contentCh := clnt.List(isRecursive, isIncomplete, false, DirFirst)
|
||||
contentCh := clnt.List(globalContext, isRecursive, isIncomplete, false, DirFirst)
|
||||
size := int64(0)
|
||||
for content := range contentCh {
|
||||
if content.Err != nil {
|
||||
|
||||
+13
-9
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
@@ -52,7 +53,7 @@ var eventAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new bucket notification",
|
||||
Action: mainEventAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(eventAddFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -104,19 +105,22 @@ func (u eventAddMessage) String() string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventAdd(ctx *cli.Context) error {
|
||||
func mainEventAdd(cliCtx *cli.Context) error {
|
||||
ctx, cancelEventAdd := context.WithCancel(globalContext)
|
||||
defer cancelEventAdd()
|
||||
|
||||
console.SetColor("Event", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventAddSyntax(ctx)
|
||||
checkEventAddSyntax(cliCtx)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
path := args[0]
|
||||
arn := args[1]
|
||||
ignoreExisting := ctx.Bool("p")
|
||||
ignoreExisting := cliCtx.Bool("p")
|
||||
|
||||
event := strings.Split(ctx.String("event"), ",")
|
||||
prefix := ctx.String("prefix")
|
||||
suffix := ctx.String("suffix")
|
||||
event := strings.Split(cliCtx.String("event"), ",")
|
||||
prefix := cliCtx.String("prefix")
|
||||
suffix := cliCtx.String("suffix")
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
@@ -128,7 +132,7 @@ func mainEventAdd(ctx *cli.Context) error {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
err = s3Client.AddNotificationConfig(arn, event, prefix, suffix, ignoreExisting)
|
||||
err = s3Client.AddNotificationConfig(ctx, arn, event, prefix, suffix, ignoreExisting)
|
||||
fatalIf(err, "Cannot enable notification on the specified bucket.")
|
||||
printMsg(eventAddMessage{
|
||||
ARN: arn,
|
||||
|
||||
+9
-5
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fatih/color"
|
||||
@@ -34,7 +35,7 @@ var eventListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "list bucket notifications",
|
||||
Action: mainEventList,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(eventListFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -96,14 +97,17 @@ func (u eventListMessage) String() string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventList(ctx *cli.Context) error {
|
||||
func mainEventList(cliCtx *cli.Context) error {
|
||||
ctx, cancelEventList := context.WithCancel(globalContext)
|
||||
defer cancelEventList()
|
||||
|
||||
console.SetColor("ARN", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("Event", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Filter", color.New(color.Bold))
|
||||
|
||||
checkEventListSyntax(ctx)
|
||||
checkEventListSyntax(cliCtx)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
path := args[0]
|
||||
arn := ""
|
||||
if len(args) > 1 {
|
||||
@@ -120,7 +124,7 @@ func mainEventList(ctx *cli.Context) error {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
configs, err := s3Client.ListNotificationConfigs(arn)
|
||||
configs, err := s3Client.ListNotificationConfigs(ctx, arn)
|
||||
fatalIf(err, "Cannot list notifications on the specified bucket.")
|
||||
|
||||
for _, config := range configs {
|
||||
|
||||
@@ -27,7 +27,6 @@ var eventCmd = cli.Command{
|
||||
Usage: "configure object notifications",
|
||||
HideHelpCommand: true,
|
||||
Action: mainEvent,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(eventFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
eventAddCmd,
|
||||
|
||||
+12
-8
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/minio/minio-go/v6"
|
||||
@@ -53,7 +54,7 @@ var eventRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove a bucket notification; '--force' removes all bucket notifications",
|
||||
Action: mainEventRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(eventRemoveFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -102,12 +103,15 @@ func (u eventRemoveMessage) String() string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventRemove(ctx *cli.Context) error {
|
||||
func mainEventRemove(cliCtx *cli.Context) error {
|
||||
ctx, cancelEventRemove := context.WithCancel(globalContext)
|
||||
defer cancelEventRemove()
|
||||
|
||||
console.SetColor("Event", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventRemoveSyntax(ctx)
|
||||
checkEventRemoveSyntax(cliCtx)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
path := args.Get(0)
|
||||
|
||||
arn := ""
|
||||
@@ -126,11 +130,11 @@ func mainEventRemove(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// flags for the attributes of the even
|
||||
event := ctx.String("event")
|
||||
prefix := ctx.String("prefix")
|
||||
suffix := ctx.String("suffix")
|
||||
event := cliCtx.String("event")
|
||||
prefix := cliCtx.String("prefix")
|
||||
suffix := cliCtx.String("suffix")
|
||||
|
||||
err = s3Client.RemoveNotificationConfig(arn, event, prefix, suffix)
|
||||
err = s3Client.RemoveNotificationConfig(ctx, arn, event, prefix, suffix)
|
||||
if err != nil {
|
||||
if err.Cause == minio.ErrNoNotificationConfigMatch {
|
||||
fatalIf(err, "Remove event failed.")
|
||||
|
||||
+33
-29
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
@@ -84,7 +85,7 @@ var findCmd = cli.Command{
|
||||
Name: "find",
|
||||
Usage: "search for objects",
|
||||
Action: mainFind,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(findFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -154,8 +155,8 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
// checkFindSyntax - validate the passed arguments
|
||||
func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
args := ctx.Args()
|
||||
func checkFindSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
args := cliCtx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"./"} // No args just default to present directory.
|
||||
} else if args.Get(0) == "." {
|
||||
@@ -170,10 +171,10 @@ func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
|
||||
// Extract input URLs and validate.
|
||||
for _, url := range args {
|
||||
_, _, err := url2Stat(url, false, encKeyDB)
|
||||
_, _, err := url2Stat(ctx, url, false, encKeyDB)
|
||||
if err != nil && !isURLPrefixExists(url, false) {
|
||||
// Bucket name empty is a valid error for 'find myminio' unless we are using watch, treat it as such.
|
||||
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !ctx.Bool("watch") {
|
||||
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !cliCtx.Bool("watch") {
|
||||
continue
|
||||
}
|
||||
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
|
||||
@@ -207,18 +208,21 @@ type findContext struct {
|
||||
}
|
||||
|
||||
// mainFind - handler for mc find commands
|
||||
func mainFind(ctx *cli.Context) error {
|
||||
func mainFind(cliCtx *cli.Context) error {
|
||||
ctx, cancelFind := context.WithCancel(globalContext)
|
||||
defer cancelFind()
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("Find", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("FindExecErr", color.New(color.FgRed, color.Italic, color.Bold))
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
checkFindSyntax(ctx, encKeyDB)
|
||||
checkFindSyntax(ctx, cliCtx, encKeyDB)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"./"} // Not args present default to present directory.
|
||||
} else if args.Get(0) == "." {
|
||||
@@ -230,11 +234,11 @@ func mainFind(ctx *cli.Context) error {
|
||||
|
||||
var olderThan, newerThan string
|
||||
|
||||
if ctx.String("older-than") != "" {
|
||||
olderThan = ctx.String("older-than")
|
||||
if cliCtx.String("older-than") != "" {
|
||||
olderThan = cliCtx.String("older-than")
|
||||
}
|
||||
if ctx.String("newer-than") != "" {
|
||||
newerThan = ctx.String("newer-than")
|
||||
if cliCtx.String("newer-than") != "" {
|
||||
newerThan = cliCtx.String("newer-than")
|
||||
}
|
||||
|
||||
// Use 'e' to indicate Go error, this is a convention followed in `mc`. For probe.Error we call it
|
||||
@@ -242,14 +246,14 @@ func mainFind(ctx *cli.Context) error {
|
||||
var e error
|
||||
var largerSize, smallerSize uint64
|
||||
|
||||
if ctx.String("larger") != "" {
|
||||
largerSize, e = humanize.ParseBytes(ctx.String("larger"))
|
||||
fatalIf(probe.NewError(e).Trace(ctx.String("larger")), "Unable to parse input bytes.")
|
||||
if cliCtx.String("larger") != "" {
|
||||
largerSize, e = humanize.ParseBytes(cliCtx.String("larger"))
|
||||
fatalIf(probe.NewError(e).Trace(cliCtx.String("larger")), "Unable to parse input bytes.")
|
||||
}
|
||||
|
||||
if ctx.String("smaller") != "" {
|
||||
smallerSize, e = humanize.ParseBytes(ctx.String("smaller"))
|
||||
fatalIf(probe.NewError(e).Trace(ctx.String("smaller")), "Unable to parse input bytes.")
|
||||
if cliCtx.String("smaller") != "" {
|
||||
smallerSize, e = humanize.ParseBytes(cliCtx.String("smaller"))
|
||||
fatalIf(probe.NewError(e).Trace(cliCtx.String("smaller")), "Unable to parse input bytes.")
|
||||
}
|
||||
|
||||
targetAlias, _, hostCfg, err := expandAlias(args[0])
|
||||
@@ -260,20 +264,20 @@ func mainFind(ctx *cli.Context) error {
|
||||
targetFullURL = hostCfg.URL
|
||||
}
|
||||
|
||||
return doFind(&findContext{
|
||||
Context: ctx,
|
||||
maxDepth: ctx.Uint("maxdepth"),
|
||||
execCmd: ctx.String("exec"),
|
||||
printFmt: ctx.String("print"),
|
||||
namePattern: ctx.String("name"),
|
||||
pathPattern: ctx.String("path"),
|
||||
regexPattern: ctx.String("regex"),
|
||||
ignorePattern: ctx.String("ignore"),
|
||||
return doFind(ctx, &findContext{
|
||||
Context: cliCtx,
|
||||
maxDepth: cliCtx.Uint("maxdepth"),
|
||||
execCmd: cliCtx.String("exec"),
|
||||
printFmt: cliCtx.String("print"),
|
||||
namePattern: cliCtx.String("name"),
|
||||
pathPattern: cliCtx.String("path"),
|
||||
regexPattern: cliCtx.String("regex"),
|
||||
ignorePattern: cliCtx.String("ignore"),
|
||||
olderThan: olderThan,
|
||||
newerThan: newerThan,
|
||||
largerSize: largerSize,
|
||||
smallerSize: smallerSize,
|
||||
watch: ctx.Bool("watch"),
|
||||
watch: cliCtx.Bool("watch"),
|
||||
targetAlias: targetAlias,
|
||||
targetURL: args[0],
|
||||
targetFullURL: targetFullURL,
|
||||
|
||||
+35
-33
@@ -18,6 +18,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -131,42 +132,43 @@ func execFind(command string) {
|
||||
// watchFind - enables listening on the input path, listens for all file/object
|
||||
// created actions. Asynchronously executes the input command line, also allows
|
||||
// formatting for the command line in accordance with subsititution arguments.
|
||||
func watchFind(ctx *findContext) {
|
||||
func watchFind(ctxCtx context.Context, ctx *findContext) {
|
||||
// Watch is not enabled, return quickly.
|
||||
if !ctx.watch {
|
||||
return
|
||||
}
|
||||
params := watchParams{
|
||||
recursive: true,
|
||||
events: []string{"put"},
|
||||
options := WatchOptions{
|
||||
Recursive: true,
|
||||
Events: []string{"put"},
|
||||
}
|
||||
watchObj, err := ctx.clnt.Watch(params)
|
||||
fatalIf(err.Trace(ctx.targetAlias), "Cannot watch with given params.")
|
||||
watchObj, err := ctx.clnt.Watch(ctxCtx, options)
|
||||
fatalIf(err.Trace(ctx.targetAlias), "Cannot watch with given options.")
|
||||
|
||||
// Loop until user CTRL-C the command line.
|
||||
for {
|
||||
select {
|
||||
case <-globalContext.Done():
|
||||
console.Println()
|
||||
close(watchObj.doneChan)
|
||||
close(watchObj.DoneChan)
|
||||
return
|
||||
case event, ok := <-watchObj.Events():
|
||||
case events, ok := <-watchObj.Events():
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
time, e := time.Parse(time.RFC3339, event.Time)
|
||||
if e != nil {
|
||||
errorIf(probe.NewError(e).Trace(event.Time), "Unable to parse event time.")
|
||||
continue
|
||||
for _, event := range events {
|
||||
time, e := time.Parse(time.RFC3339, event.Time)
|
||||
if e != nil {
|
||||
errorIf(probe.NewError(e).Trace(event.Time), "Unable to parse event time.")
|
||||
continue
|
||||
}
|
||||
|
||||
find(ctxCtx, ctx, contentMessage{
|
||||
Key: getAliasedPath(ctx, event.Path),
|
||||
Time: time,
|
||||
Size: event.Size,
|
||||
})
|
||||
}
|
||||
|
||||
find(ctx, contentMessage{
|
||||
Key: getAliasedPath(ctx, event.Path),
|
||||
Time: time,
|
||||
Size: event.Size,
|
||||
})
|
||||
|
||||
case err, ok := <-watchObj.Errors():
|
||||
if !ok {
|
||||
return
|
||||
@@ -219,7 +221,7 @@ func getAliasedPath(ctx *findContext, path string) string {
|
||||
return trimSuffixAtMaxDepth(ctx.targetURL, aliasedPath, separator, ctx.maxDepth)
|
||||
}
|
||||
|
||||
func find(ctx *findContext, fileContent contentMessage) {
|
||||
func find(ctxCtx context.Context, ctx *findContext, fileContent contentMessage) {
|
||||
// Match the incoming content, didn't match return.
|
||||
if !matchFind(ctx, fileContent) {
|
||||
return
|
||||
@@ -227,27 +229,27 @@ func find(ctx *findContext, fileContent contentMessage) {
|
||||
|
||||
// proceed to either exec, format the output string.
|
||||
if ctx.execCmd != "" {
|
||||
execFind(stringsReplace(ctx.execCmd, fileContent))
|
||||
execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent))
|
||||
return
|
||||
}
|
||||
if ctx.printFmt != "" {
|
||||
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
|
||||
fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent)
|
||||
}
|
||||
printMsg(findMessage{fileContent})
|
||||
}
|
||||
|
||||
// doFind - find is main function body which interprets and executes
|
||||
// all the input parameters.
|
||||
func doFind(ctx *findContext) error {
|
||||
func doFind(ctxCtx context.Context, ctx *findContext) error {
|
||||
// If watch is enabled we will wait on the prefix perpetually
|
||||
// for all I/O events until canceled by user, if watch is not enabled
|
||||
// following defer is a no-op.
|
||||
defer watchFind(ctx)
|
||||
defer watchFind(ctxCtx, ctx)
|
||||
|
||||
var prevKeyName string
|
||||
|
||||
// iterate over all content which is within the given directory
|
||||
for content := range ctx.clnt.List(true, false, false, DirNone) {
|
||||
for content := range ctx.clnt.List(globalContext, true, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
@@ -287,11 +289,11 @@ func doFind(ctx *findContext) error {
|
||||
|
||||
// proceed to either exec, format the output string.
|
||||
if ctx.execCmd != "" {
|
||||
execFind(stringsReplace(ctx.execCmd, fileContent))
|
||||
execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent))
|
||||
continue
|
||||
}
|
||||
if ctx.printFmt != "" {
|
||||
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
|
||||
fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent)
|
||||
}
|
||||
|
||||
printMsg(findMessage{fileContent})
|
||||
@@ -304,7 +306,7 @@ func doFind(ctx *findContext) error {
|
||||
|
||||
// stringsReplace - formats the string to remove {} and replace each
|
||||
// with the appropriate argument
|
||||
func stringsReplace(args string, fileContent contentMessage) string {
|
||||
func stringsReplace(ctx context.Context, args string, fileContent contentMessage) string {
|
||||
// replace all instances of {}
|
||||
str := args
|
||||
if strings.Contains(str, "{}") {
|
||||
@@ -358,12 +360,12 @@ func stringsReplace(args string, fileContent contentMessage) string {
|
||||
|
||||
// replace all instances of {url}
|
||||
if strings.Contains(str, "{url}") {
|
||||
str = strings.Replace(str, "{url}", getShareURL(fileContent.Key), -1)
|
||||
str = strings.Replace(str, "{url}", getShareURL(ctx, fileContent.Key), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {"url"}
|
||||
if strings.Contains(str, `{"url"}`) {
|
||||
str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(fileContent.Key)), -1)
|
||||
str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(ctx, fileContent.Key)), -1)
|
||||
}
|
||||
|
||||
return str
|
||||
@@ -413,14 +415,14 @@ var defaultSevenDays = time.Duration(604800) * time.Second
|
||||
|
||||
// getShareURL is used in conjunction with the {url} substitution
|
||||
// argument to generate and return presigned URLs, returns error if any.
|
||||
func getShareURL(path string) string {
|
||||
func getShareURL(ctx context.Context, path string) string {
|
||||
targetAlias, targetURLFull, _, err := expandAlias(path)
|
||||
fatalIf(err.Trace(path), "Unable to expand alias.")
|
||||
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURLFull)
|
||||
fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.")
|
||||
|
||||
content, err := clnt.Stat(false, false, nil)
|
||||
content, err := clnt.Stat(ctx, false, false, nil)
|
||||
fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.")
|
||||
|
||||
// Skip if its a directory.
|
||||
@@ -433,7 +435,7 @@ func getShareURL(path string) string {
|
||||
fatalIf(err.Trace(targetAlias, objectURL), "Unable to initialize new client from alias.")
|
||||
|
||||
// Set default expiry for each url (point of no longer valid), to be 7 days
|
||||
shareURL, err := newClnt.ShareDownload(defaultSevenDays)
|
||||
shareURL, err := newClnt.ShareDownload(ctx, defaultSevenDays)
|
||||
fatalIf(err.Trace(targetAlias, objectURL), "Unable to generate share url.")
|
||||
|
||||
return shareURL
|
||||
|
||||
+2
-1
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -410,7 +411,7 @@ func TestStringReplace(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
gotStr := stringsReplace(testCase.str, testCase.content)
|
||||
gotStr := stringsReplace(context.Background(), testCase.str, testCase.content)
|
||||
if gotStr != testCase.expectedStr {
|
||||
t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedStr, gotStr)
|
||||
}
|
||||
|
||||
+3
-2
@@ -20,6 +20,7 @@ import (
|
||||
"bufio"
|
||||
"compress/bzip2"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
@@ -45,7 +46,7 @@ var headCmd = cli.Command{
|
||||
Name: "head",
|
||||
Usage: "display first 'n' lines of an object",
|
||||
Action: mainHead,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(append(headFlags, ioFlags...), globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -84,7 +85,7 @@ func headURL(sourceURL string, encKeyDB map[string][]prefixSSEPair, nlines int64
|
||||
default:
|
||||
var err *probe.Error
|
||||
var metadata map[string]string
|
||||
if reader, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil {
|
||||
if reader, metadata, err = getSourceStreamMetadataFromURL(context.Background(), sourceURL, encKeyDB); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
ctype := metadata["Content-Type"]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user