Compare commits

..
Author SHA1 Message Date
Anis Elleuch 7e9625733d ilm: Add doc to the complete mc guide (#3270) 2020-07-19 12:45:36 -07:00
kannappanr 1513d76ca9 Fix typos in the examples (#3289) 2020-07-10 22:17:54 -07:00
P R 87dc0bf80e mc ilm list cell alignment for text (#3291) 2020-07-10 22:17:54 -07:00
Harshavardhana 69c0d33543 support proper proxy for all transports (#3290)
fixes #3225
2020-07-10 22:17:54 -07:00
Harshavardhana 8d891755e0 move to latest released minio to fix policy (#3288)
fixes #3265
2020-07-10 22:17:54 -07:00
ebozduman a9cd7869eb Fixes copy with partial metadata failure (#3282) 2020-07-10 22:17:54 -07:00
Harshavardhana c40ab338a3 support goreleaser for mc (#3286) 2020-07-10 22:17:54 -07:00
ebozduman 0fcd10d793 Adds support to preserve X-Amz-Meta-Mc-Attrs when os -> fs (#3285) 2020-07-10 22:17:54 -07:00
Anis Elleuch b7b75c5f46 cli: Load global flags in initBeforeRunningCmd (#3283)
app.Before receives a cli.Context but without flags parsed. There is no
point calling ctx.Bool() or ctx.IsSet() at that stage.

However, flags are parsed in commands, so minio initialization and
setting global variables (globalJSON, globalQuiet, etc..) can be moved
to the Before function of all commands.

Avoid setting command.Before for non leaf commands, otherwise Before
function will be called multiples times until it reaches the leaf
command.
2020-07-10 22:17:54 -07:00
Anis Elleuch b97b7b8987 policy: Recalculate permission mode after setting a new one (#3280)
`mc policy set` can confuse users by showing that a bucket has 'none'
policy mode although issuing `mc policy get` will show it is `custom`
when the bucket already other policy statements for some sub-resources.

For better UX, mc will issue another request to get the real policy
mode.
2020-07-10 22:17:54 -07:00
poornas 8f3d514e3b Fix mc cp regression for recursive copy (#3278)
Fixes #3267. Revert commit dc430afe07
which attempted to preserve similar behavior across mc cp and mc
mirror, but introduces a regression for cp when wildcards are
specified.
2020-07-10 22:17:54 -07:00
Anis Elleuch bb3c0d45f2 s3: Use list object v1 in case of GCS (#3274) 2020-06-24 06:31:59 -07:00
Harshavardhana 9ebde383d4 make sure active/active enables watch by default (#3271)
- effectively use context everywhere
- effectively look for source-mtime in all
  variations
- `mc diff` should do metadata diff as well
2020-06-23 16:57:00 -07:00
Harshavardhana cfea4fdc75 fix: overwrite is implicit with active-active (#3268)
refactor lengthy options as mirrorOptions{} for
ease of readability and usage.
2020-06-23 09:31:19 -07:00
Harshavardhana dd47bdfeaa fix: support STS for admin commands (#3264) 2020-06-19 14:31:24 -07:00
ebozduman ec9b92cbb7 Apply global context for all apis (#3240) 2020-06-19 14:31:19 -07:00
poornas 975423abe2 Fix mc cp when legal-hold or retention is set (#3257)
- Send Content-MD5 header if default retention is set on the bucket
- legal-hold needs to be case insensitive
2020-06-16 11:28:25 -07:00
Harshavardhana 3dd971f673 rename multi-master to active-active (#3255) 2020-06-15 18:18:08 -07:00
321 changed files with 28868 additions and 27636 deletions
+52
View File
@@ -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
+12 -29
View File
@@ -4,17 +4,18 @@ on:
pull_request:
branches:
- master
push:
branches:
- master
jobs:
build:
name: Test on Go ${{ matrix.go-version }} and ${{ matrix.os }}
runs-on: ${{ matrix.os }}
env:
GO111MODULE: on
strategy:
matrix:
go-version: [1.17.x]
os: [ubuntu-latest, macos-latest, windows-latest]
go-version: [1.13.x]
os: [ubuntu-latest, windows-latest]
steps:
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
uses: actions/setup-go@v1
@@ -27,38 +28,20 @@ jobs:
- name: Build on ${{ matrix.os }}
if: matrix.os == 'windows-latest'
env:
GO111MODULE: on
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 == 'macos-latest'
run: |
go build --ldflags="-s -w" -o %GOPATH%\bin\mc
go test -v -race --timeout 30m ./...
- name: Build on ${{ matrix.os }}
if: matrix.os == 'ubuntu-latest'
env:
GO111MODULE: on
run: |
wget https://dl.min.io/server/minio/release/linux-amd64/minio && chmod +x minio
mkdir -p ~/.minio/certs/ && cp testdata/localhost.crt ~/.minio/certs/public.crt && cp testdata/localhost.key ~/.minio/certs/private.key
sudo cp testdata/localhost.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates
./minio server /tmp/test-xl/{1...4}/ & sleep 10
export SERVER_ENDPOINT=localhost:9000 ACCESS_KEY=minioadmin SECRET_KEY=minioadmin ENABLE_HTTPS=1
make
diff -au <(gofmt -d *.go) <(printf "")
diff -au <(gofmt -s -d cmd) <(printf "")
diff -au <(gofmt -s -d pkg) <(printf "")
make test-race
make verify
make crosscompile
vetchecks: # Run vet checks against one version.
env:
CGO_ENABLED: 0
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17.x
- name: Checkout code
uses: actions/checkout@v2
- name: Test 386
run: GOOS=linux GOARCH=386 go test -short ./...
+6 -20
View File
@@ -12,31 +12,17 @@ linters:
- goimports
- misspell
- govet
- revive
- golint
- ineffassign
- gosimple
- deadcode
- structcheck
- gomodguard
- gofmt
- unused
- structcheck
- varcheck
- gofumpt
linters-settings:
gofumpt:
lang-version: "1.17"
# Choose whether or not to use the extra rules that are disabled
# by default
extra-rules: false
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
- 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.43.0 # use the fixed version to not introduce new linters unexpectedly
golangci-lint-version: 1.20.0 # use the fixed version to not introduce new linters unexpectedly
+13562 -1960
View File
File diff suppressed because it is too large Load Diff
+5 -10
View File
@@ -1,4 +1,4 @@
FROM golang:1.17-alpine as builder
FROM golang:1.13-alpine as build
LABEL maintainer="MinIO Inc <dev@min.io>"
@@ -11,17 +11,12 @@ RUN \
git clone https://github.com/minio/mc && cd mc && \
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4
FROM alpine:3.12
ARG TARGETARCH
COPY --from=builder /go/bin/mc /usr/bin/mc
COPY --from=builder /go/mc/CREDITS /licenses/CREDITS
COPY --from=builder /go/mc/LICENSE /licenses/LICENSE
COPY --from=build /go/bin/mc /usr/bin/mc
RUN \
microdnf update --nodocs && \
microdnf install ca-certificates --nodocs && \
microdnf clean all
apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/master/CREDITS
ENTRYPOINT ["mc"]
+12
View File
@@ -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"]
+12
View File
@@ -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 -9
View File
@@ -1,14 +1,8 @@
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4
LABEL maintainer="MinIO Inc <dev@min.io>"
FROM alpine:3.12
COPY mc /usr/bin/
COPY CREDITS /licenses/CREDITS
COPY LICENSE /licenses/LICENSE
COPY CREDITS /
RUN \
microdnf update --nodocs && \
microdnf install ca-certificates --nodocs && \
microdnf clean all
RUN apk add --no-cache ca-certificates
ENTRYPOINT ["mc"]
+12
View File
@@ -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"]
+6 -15
View File
@@ -1,19 +1,10 @@
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4
FROM alpine:3.12
ARG TARGETARCH
MAINTAINER MinIO Inc <dev@min.io>
ARG RELEASE
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY CREDITS /licenses/CREDITS
COPY LICENSE /licenses/LICENSE
RUN \
microdnf update --nodocs && \
microdnf install curl ca-certificates shadow-utils --nodocs && \
microdnf clean all && \
curl -s -q https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE} -o /usr/bin/mc && \
chmod +x /usr/bin/mc
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"]
+12
View File
@@ -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"]
+202 -661
View File
@@ -1,661 +1,202 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
+8 -3
View File
@@ -18,13 +18,12 @@ checks:
getdeps:
@mkdir -p ${GOPATH}/bin
@echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.43.0
@echo "Installing stringer" && go install -v golang.org/x/tools/cmd/stringer@latest
@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 lint
verifiers: getdeps vet fmt lint
docker: build
@docker build -t $(TAG) . -f Dockerfile.dev
@@ -33,8 +32,14 @@ vet:
@echo "Running $@"
@GO111MODULE=on go vet github.com/minio/mc/...
fmt:
@echo "Running $@"
@GO111MODULE=on gofmt -d cmd/
@GO111MODULE=on gofmt -d pkg/
lint:
@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.
+39 -57
View File
@@ -1,40 +1,34 @@
# MinIO Client Quickstart Guide
[![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Go Report Card](https://goreportcard.com/badge/minio/mc)](https://goreportcard.com/report/minio/mc) [![Docker Pulls](https://img.shields.io/docker/pulls/minio/mc.svg?maxAge=604800)](https://hub.docker.com/r/minio/mc/) [![license](https://img.shields.io/badge/license-AGPL%20V3-blue)](https://github.com/minio/mc/blob/master/LICENSE)
[![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Go Report Card](https://goreportcard.com/badge/minio/mc)](https://goreportcard.com/report/minio/mc) [![Docker Pulls](https://img.shields.io/docker/pulls/minio/mc.svg?maxAge=604800)](https://hub.docker.com/r/minio/mc/)
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).
```
alias set, remove and list aliases in configuration file
ls list buckets and objects
mb make a bucket
rb remove a bucket
cp copy objects
mirror synchronize object(s) to a remote site
cat display object contents
head display first 'n' lines of an object
pipe stream STDIN to an object
share generate URL for temporary access to an object
find search for objects
sql run sql queries on objects
stat show object metadata
mv move objects
tree list buckets and objects in a tree format
du summarize disk usage recursively
retention set retention for object(s)
legalhold set legal hold for object(s)
diff list differences in object name, size, and date between two buckets
rm remove objects
encrypt manage bucket encryption config
event manage object notifications
watch listen for object notification events
undo undo PUT/DELETE operations
policy manage anonymous access to buckets and objects
tag manage tags for bucket(s) and object(s)
ilm manage bucket lifecycle
version manage bucket versioning
replicate configure server side bucket replication
admin manage MinIO servers
update update mc to latest release
ls list buckets and objects
mb make a bucket
rb remove a bucket
cat display object contents
head display first 'n' lines of an object
pipe stream STDIN to an object
share generate URL for temporary access to an object
cp copy objects
mirror synchronize objects to a remote site
find search for objects
sql run sql queries on objects
stat stat contents of objects
lock set and get object lock configuration
retention set object retention for objects with a given prefix
legalhold set object legal hold for objects
diff list differences in object name, size, and date between buckets
rm remove objects
event manage object notifications
watch watch for object events
policy manage anonymous access to objects
admin manage MinIO servers
session manage saved sessions for cp command
config manage mc configuration file
update check for a new software update
version print version info
```
## Docker Container
@@ -58,21 +52,6 @@ docker run -it --entrypoint=/bin/sh minio/mc
then use the [`mc config` command](#add-a-cloud-storage-service).
### GitLab CI
When using the Docker container in GitLab CI, you must [set the entrypoint to an empty string](https://docs.gitlab.com/ee/ci/docker/using_docker_images.html#overriding-the-entrypoint-of-an-image).
```
deploy:
image:
name: minio/mc
entrypoint: ['']
stage: deploy
before_script:
- mc alias set minio $MINIO_HOST $MINIO_ACCESS_KEY $MINIO_SECRET_KEY
script:
- mc cp <source> <destination>
```
## macOS
### Homebrew
Install mc packages using [Homebrew](http://brew.sh/)
@@ -106,10 +85,10 @@ mc.exe --help
```
## Install from Source
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.17](https://golang.org/dl/#stable)
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.13](https://golang.org/dl/#stable)
```sh
go install github.com/minio/mc@latest
GO111MODULE=on go get github.com/minio/mc
```
## Add a Cloud Storage Service
@@ -118,25 +97,25 @@ If you are planning to use `mc` only on POSIX compatible filesystems, you may sk
To add one or more Amazon S3 compatible hosts, please follow the instructions below. `mc` stores all its configuration information in ``~/.mc/config.json`` file.
```
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --path <BUCKET-LOOKUP-TYPE>
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --lookup <BUCKET-LOOKUP-TYPE>
```
`<ALIAS>` is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
Alias is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
Path is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "on", "off" as valid values to enable/disable path style requests.. By default, it is set to "auto" and SDK automatically determines the type of url lookup to use.
Lookup is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "dns", "path" or "auto" as valid values. By default, it is set to "auto" and SDK automatically determines the type of url lookup to use.
### Example - MinIO Cloud Storage
MinIO server startup banner displays URL, access and secret keys.
MinIO server displays URL, access and secret keys.
```
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
### Example - Amazon S3 Cloud Storage
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html).
```
mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
**Note**: As an IAM user on Amazon S3 you need to make sure the user has full access to the buckets or set the following restricted policy for your IAM user
@@ -170,7 +149,7 @@ mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJ
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)
```
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
## Test Your Setup
@@ -207,6 +186,9 @@ mc cp myobject.txt play/mybucket
myobject.txt: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00 % 41 B/s 0
```
<a name="everyday-use"></a>
## Everyday Use
### Shell aliases
@@ -239,4 +221,4 @@ cat cp event head mb pipe rm share stat
Please follow MinIO [Contributor's Guide](https://github.com/minio/mc/blob/master/CONTRIBUTING.md)
## License
Use of `mc` is governed by the GNU AGPLv3 license that can be found in the [LICENSE](https://github.com/minio/mc/blob/master/LICENSE) file.
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fminio%2Fmc.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fminio%2Fmc?ref=badge_large)
+4 -4
View File
@@ -92,7 +92,7 @@ make
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
```
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
```
别名就是给你的云存储服务起了一个短点的外号。S3 endpoint,access key和secret key是你的云存储服务提供的。API签名是可选参数,默认情况下,它被设置为"S3v4"。
@@ -101,21 +101,21 @@ mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--a
从MinIO服务获得URL、access key和secret key。
```
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
```
### 示例-Amazon S3云存储
参考[AWS Credentials指南](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)获取你的AccessKeyID和SecretAccessKey。
```
mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
```
### 示例-Google云存储
参考[Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)获取你的AccessKeyID和SecretAccessKey。
```
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
```
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
-1
View File
@@ -1 +0,0 @@
theme: jekyll-theme-minimal
+1
View File
@@ -22,3 +22,4 @@ check_minimum_version() {
return 0
}
-18
View File
@@ -1,22 +1,4 @@
#!/bin/bash
#
# Copyright (c) 2015-2021 MinIO, Inc.
#
# This file is part of MinIO Object Storage stack
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
_init() {
# Save release LDFLAGS
+10 -13
View File
@@ -1,21 +1,18 @@
#!/usr/bin/env bash
#
# Copyright (c) 2015-2021 MinIO, Inc.
# MinIO Client, (C) 2015, 2016, 2017, 2018, 2019 MinIO, Inc.
#
# This file is part of MinIO Object Storage stack
# 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
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# http://www.apache.org/licenses/LICENSE-2.0
#
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# 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.
#
# shellcheck source=buildscripts/build.env
+2 -22
View File
@@ -1,34 +1,14 @@
#!/bin/bash
#
# Copyright (c) 2015-2021 MinIO, Inc.
#
# This file is part of MinIO Object Storage stack
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
set -e
# Enable tracing if set.
[ -n "$BASH_XTRACEFD" ] && set -x
[ -n "$BASH_XTRACEFD" ] && set -ex
function _init() {
## All binaries are static make sure to disable CGO.
export CGO_ENABLED=0
## List of architectures and OS to test coss compilation.
SUPPORTED_OSARCH="linux/ppc64le linux/mips64 linux/arm64 linux/s390x darwin/arm64 darwin/amd64 freebsd/amd64 windows/amd64 linux/arm linux/386 netbsd/amd64 linux/mips openbsd/amd64"
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386 windows/amd64"
}
function _build() {
+15 -17
View File
@@ -1,22 +1,20 @@
//go:build ignore
// +build ignore
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2014, 2015, 2016, 2017, 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
+16 -18
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
@@ -22,7 +21,7 @@ import "path/filepath"
// isValidAccessPERM - is provided access perm string supported.
func (b accessPerms) isValidAccessPERM() bool {
switch b {
case accessNone, accessDownload, accessUpload, accessPrivate, accessPublic:
case accessNone, accessDownload, accessUpload, accessPublic:
return true
}
return false
@@ -40,7 +39,6 @@ const (
accessNone = accessPerms("none")
accessDownload = accessPerms("download")
accessUpload = accessPerms("upload")
accessPrivate = accessPerms("private")
accessPublic = accessPerms("public")
accessCustom = accessPerms("custom")
)
+16 -17
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2014, 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
@@ -24,7 +23,7 @@ import (
"time"
"github.com/cheggaaa/pb"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
+45 -47
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* 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
@@ -23,10 +22,10 @@ import (
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminQuotaFlags = []cli.Flag{
@@ -75,47 +74,46 @@ func (q quotaMessage) JSON() string {
}
var adminBucketQuotaCmd = cli.Command{
Name: "quota",
Usage: "manage bucket quota",
Action: mainAdminBucketQuota,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminQuotaFlags, globalFlags...),
Name: "quota",
Usage: "Manage bucket quota",
Action: mainAdminBucketQuota,
Before: initBeforeRunningCmd,
Flags: append(adminQuotaFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET [--fifo QUOTA | --hard QUOTA | --clear]
{{.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.
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}}
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display bucket quota configured for "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket
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
2. Set FIFO quota for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 10GB
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1gb
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
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, ctx.Command.Name, 1) // last argument is exit code
cli.ShowCommandHelpAndExit(ctx, "quota", 1) // last argument is exit code
}
if ctx.IsSet("hard") && ctx.IsSet("fifo") {
-309
View File
@@ -1,309 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"net/url"
"path"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/pkg/console"
)
var adminBucketRemoteAddFlags = []cli.Flag{
cli.StringFlag{
Name: "path",
Value: "auto",
Usage: "bucket path lookup supported by the server. Valid options are '[on,off,auto]'",
},
cli.StringFlag{
Name: "service",
Usage: "type of service. Valid options are '[replication]'",
},
cli.StringFlag{
Name: "region",
Usage: "region of the destination bucket (optional)",
},
cli.StringFlag{
Name: "bandwidth",
Usage: "Set bandwidth limit in bits per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
},
cli.BoolFlag{
Name: "sync",
Usage: "enable synchronous replication for this target. Default is async",
},
cli.UintFlag{
Name: "healthcheck-seconds",
Usage: "health check duration in seconds",
Value: 60,
},
cli.BoolFlag{
Name: "disable-proxy",
Usage: "disable proxying in active-active replication. If unset, default behavior is to proxy",
},
}
var adminBucketRemoteAddCmd = cli.Command{
Name: "add",
Usage: "add a new remote target",
Action: mainAdminBucketRemoteAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteAddFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET [--path | --region | --bandwidth] --service
TARGET:
Also called as alias/sourcebucketname
DEST_BUCKET:
Also called as remote target bucket.
DEST_URL:
Also called as remote endpoint.
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set a new remote replication target "targetbucket" in region "us-west-1" on https://minio.siteb.example.com for bucket 'sourcebucket'.
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
--service "replication" --region "us-west-1"
2. Set a new remote replication target 'targetbucket' in region "us-west-1" on https://minio.siteb.example.com for
bucket 'sourcebucket' with bandwidth set to 2 gigabits per second. Enable synchronous replication to the target
and perform health check of target every 100 seconds
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
--service "replication" --region "us-west-1 --bandwidth "2G" --sync
`,
}
// checkAdminBucketRemoteAddSyntax - validate all the passed arguments
func checkAdminBucketRemoteAddSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 2 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr > 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for remote add command.")
}
}
// RemoteMessage container for content message structure
type RemoteMessage struct {
op string
Status string `json:"status"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
SourceBucket string `json:"sourceBucket"`
TargetURL string `json:"TargetURL,omitempty"`
TargetBucket string `json:"TargetBucket,omitempty"`
RemoteARN string `json:"RemoteARN,omitempty"`
Path string `json:"path,omitempty"`
Region string `json:"region,omitempty"`
ServiceType string `json:"service"`
Bandwidth int64 `json:"bandwidth"`
ReplicationSync bool `json:"replicationSync"`
Proxy bool `json:"proxy"`
HealthCheckDuration time.Duration `json:"healthcheckDuration"`
ResetID string `json:"resetID"`
ResetBefore time.Time `json:"resetBeforeDate"`
}
func (r RemoteMessage) String() string {
switch r.op {
case "ls":
message := console.Colorize("TargetURL", fmt.Sprintf("%s ", r.TargetURL))
message += console.Colorize("SourceBucket", r.SourceBucket)
message += console.Colorize("Arrow", "->")
message += console.Colorize("TargetBucket", r.TargetBucket)
message += " "
message += console.Colorize("ARN", r.RemoteARN)
syncStr := " "
if r.ReplicationSync && r.ServiceType == string(madmin.ReplicationService) {
syncStr = "sync"
}
message += " " + console.Colorize("SyncLabel", syncStr)
proxyStr := " "
if r.Proxy && r.ServiceType == string(madmin.ReplicationService) {
proxyStr = "proxy"
}
message += " "
message += console.Colorize("ProxyLabel", proxyStr)
return message
case "rm":
return console.Colorize("RemoteMessage", "Removed remote target for `"+r.SourceBucket+"` bucket successfully.")
case "add":
return console.Colorize("RemoteMessage", "Remote ARN = `"+r.RemoteARN+"`.")
case "edit":
return console.Colorize("RemoteMessage", "Remote target updated successfully for target with ARN:`"+r.RemoteARN+"`.")
}
return ""
}
// JSON returns jsonified message
func (r RemoteMessage) JSON() string {
r.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(r, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func extractCredentialURL(argURL string) (accessKey, secretKey string, u *url.URL) {
var parsedURL string
if hostKeyTokens.MatchString(argURL) {
fatalIf(errInvalidArgument().Trace(argURL), "temporary tokens are not allowed for remote targets")
}
if hostKeys.MatchString(argURL) {
parts := hostKeys.FindStringSubmatch(argURL)
if len(parts) != 5 {
fatalIf(errInvalidArgument().Trace(argURL), "Unsupported remote target format, please check --help")
}
accessKey = parts[2]
secretKey = parts[3]
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[4])
}
var e error
if parsedURL == "" {
fatalIf(errInvalidArgument().Trace(argURL), "No valid credentials were detected")
}
u, e = url.Parse(parsedURL)
if e != nil {
fatalIf(errInvalidArgument().Trace(parsedURL), "Unsupported URL format %v", e)
}
return accessKey, secretKey, u
}
// fetchRemoteTarget - returns the dest bucket, dest endpoint, access and secret key
func fetchRemoteTarget(cli *cli.Context) (sourceBucket string, bktTarget *madmin.BucketTarget) {
args := cli.Args()
argCount := len(args)
if argCount < 2 {
fatalIf(probe.NewError(fmt.Errorf("Missing Remote target configuration")), "Unable to parse remote target")
}
_, sourceBucket = url2Alias(args[0])
p := cli.String("path")
if !isValidPath(p) {
fatalIf(errInvalidArgument().Trace(p),
"Unrecognized bucket path style. Valid options are `[on,off, auto]`.")
}
tgtURL := args[1]
accessKey, secretKey, u := extractCredentialURL(tgtURL)
var tgtBucket string
if u.Path != "" {
tgtBucket = path.Clean(u.Path[1:])
}
if e := s3utils.CheckValidBucketName(tgtBucket); e != nil {
fatalIf(probe.NewError(e).Trace(tgtURL), "Invalid target bucket specified")
}
serviceType := cli.String("service")
if !madmin.ServiceType(serviceType).IsValid() {
fatalIf(errInvalidArgument().Trace(serviceType), "Invalid service type. Valid option is `[replication]`.")
}
if cli.IsSet("sync") && serviceType != string(madmin.ReplicationService) {
fatalIf(errInvalidArgument(), "Invalid usage. --sync flag applies only to replication service")
}
bandwidthStr := cli.String("bandwidth")
bandwidth, err := getBandwidthInBytes(bandwidthStr)
if err != nil {
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
}
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
creds := &madmin.Credentials{AccessKey: accessKey, SecretKey: secretKey}
disableproxy := cli.Bool("disable-proxy")
bktTarget = &madmin.BucketTarget{
TargetBucket: tgtBucket,
Secure: u.Scheme == "https",
Credentials: creds,
Endpoint: u.Host,
Path: p,
API: "s3v4",
Type: madmin.ServiceType(serviceType),
Region: cli.String("region"),
BandwidthLimit: int64(bandwidth),
ReplicationSync: cli.Bool("sync"),
DisableProxy: disableproxy,
HealthCheckDuration: time.Duration(cli.Uint("healthcheck-seconds")) * time.Second,
}
return sourceBucket, bktTarget
}
func getBandwidthInBytes(bandwidthStr string) (bandwidth uint64, err error) {
if bandwidthStr != "" {
bandwidth, err = humanize.ParseBytes(bandwidthStr)
if err != nil {
return
}
}
bandwidth = bandwidth / 8
return
}
// mainAdminBucketRemoteAdd is the handle for "mc admin bucket remote set" command.
func mainAdminBucketRemoteAdd(ctx *cli.Context) error {
checkAdminBucketRemoteAddSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
sourceBucket, bktTarget := fetchRemoteTarget(ctx)
arn, e := client.SetRemoteTarget(globalContext, sourceBucket, bktTarget)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to configure remote target")
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
TargetURL: bktTarget.URL().String(),
TargetBucket: bktTarget.TargetBucket,
AccessKey: bktTarget.Credentials.AccessKey,
SourceBucket: sourceBucket,
RemoteARN: arn,
ReplicationSync: bktTarget.ReplicationSync,
Proxy: !bktTarget.DisableProxy,
})
return nil
}
-131
View File
@@ -1,131 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"testing"
)
func TestGetBandwidthInBytes(t *testing.T) {
type args struct {
bandwidthStr string
}
f1 := 999.123457 * 1024 * 1024 / 8
f2 := 10.123456790 * 1024 * 1024 * 1024 / 8
f3 := 10000.123456790 * 1024 * 1024 * 1024 / 8
f4 := (0.001*1024*1024*1024 + 1) / 8 // round up
tests := []struct {
name string
args args
want uint64
}{
{
name: "1MegaByte",
args: args{
bandwidthStr: "1Mi",
},
want: 1024 * 1024 / 8,
},
{
name: "1MegaBit",
args: args{
bandwidthStr: "1M",
},
want: 1000000 / 8,
},
{
name: "1GigaBit",
args: args{
bandwidthStr: "1G",
},
want: 1000000000 / 8,
},
{
name: "1GigaByte",
args: args{
bandwidthStr: "1Gi",
},
want: 1024 * 1024 * 1024 / 8,
},
{
name: "FractionalMegaBits",
args: args{
bandwidthStr: "999.123456789123456789M",
},
want: 999123457 / 8,
},
{
name: "FractionalGigaBits",
args: args{
bandwidthStr: "10.123456789123456789123456G",
},
want: 10123456789 / 8,
},
{
name: "FractionalBigGigaBits",
args: args{
bandwidthStr: "10000.123456789123456789123456G",
},
want: 10000123456789 / 8,
},
{
name: "FractionalMegaBytes",
args: args{
bandwidthStr: "999.123456789123456789Mi",
},
want: uint64(f1),
},
{
name: "FractionalGigaBytes",
args: args{
bandwidthStr: "10.123456789123456789123456Gi",
},
want: uint64(f2),
},
{
name: "FractionalBigGigaBytes",
args: args{
bandwidthStr: "10000.123456789123456789123456Gi",
},
want: uint64(f3),
},
{
name: "SmallGiga",
args: args{
bandwidthStr: "0.001Gi",
},
want: uint64(f4),
},
{
name: "LargeK",
args: args{
bandwidthStr: "1024Ki",
},
want: 1024 * 1024 / 8,
},
}
t.Parallel()
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got, err := getBandwidthInBytes(tt.args.bandwidthStr); err != nil || got != tt.want {
t.Errorf("getBandwidthInBytes() = %v, want %v", got, tt.want)
}
})
}
}
-196
View File
@@ -1,196 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"sort"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBandwidthInfoCmdFlags = []cli.Flag{
cli.StringFlag{
Name: "unit",
Value: "b",
Usage: "[b|bi|B|Bi] Display bandwidth in bits (IEC [bi] or SI [b]) or bytes (IEC [Bi] or SI [B])",
},
}
var adminBwInfoCmd = cli.Command{
Name: "bandwidth",
Usage: "Show bandwidth info for buckets on the MinIO server in bits or bytes per second. Ki,Bi,Mi,Gi represent IEC units.",
Action: mainAdminBwInfo,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: append(globalFlags, adminBandwidthInfoCmdFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} FLAGS TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show the bandwidth usage for all the buckets in a MinIO server setup
{{.Prompt}} {{.HelpName}} play/
2. Show the bandwidth usage for the bucket 'source-bucket' in a MinIO server setup
{{.Prompt}} {{.HelpName}} play/source-bucket
`,
}
func printTable(report madmin.Report, bits bool, iec bool) {
bucketMaxLength := 63
bucketColLength := 6
var bucketKeys []string
for bucket := range report.Report.BucketStats {
if len(bucket) <= bucketMaxLength && len(bucket) > bucketColLength {
bucketColLength = len(bucket)
}
bucketKeys = append(bucketKeys, bucket)
}
sort.Strings(bucketKeys)
dspOrder := []col{colGreen} // Header
for i := 0; i < len(report.Report.BucketStats); i++ {
dspOrder = append(dspOrder, colGrey)
}
var printColors []*color.Color
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
cellText := make([][]string, len(report.Report.BucketStats)+1) // 1 for the header
tbl := console.NewTable(printColors, []bool{false, false, false}, 0)
bucketTitle := fmt.Sprintf("%-16v", "Bucket")
cellText[0] = []string{
bucketTitle,
"Configured Max Bandwidth",
"Current Bandwidth",
}
tbl.HeaderRowSeparator = true
index := 1
for _, bucket := range bucketKeys {
values := report.Report.BucketStats[bucket]
if len(bucket) > bucketMaxLength {
bucket = bucket[:bucketMaxLength] + ".."
}
var mul uint64
mul = 1
if bits {
mul = 8
}
limit := humanize.Bytes(uint64(values.LimitInBytesPerSecond) * mul)
current := humanize.Bytes(uint64(values.CurrentBandwidthInBytesPerSecond) * mul)
if iec {
limit = humanize.IBytes(uint64(values.LimitInBytesPerSecond)*mul) + "/sec"
current = humanize.IBytes(uint64(values.CurrentBandwidthInBytesPerSecond)*mul) + "/sec"
}
if bits {
limit = strings.ToLower(limit) + "/sec"
current = strings.ToLower(current) + "/sec"
}
if values.LimitInBytesPerSecond == 0 {
limit = "N/A" // N/A means cluster bandwidth is not configured
}
cellText[index] = []string{
bucket,
limit,
current,
}
index++
}
if len(report.Report.BucketStats) > 0 {
err := tbl.DisplayTable(cellText)
if err != nil {
console.Error(err)
}
}
}
func checkAdminBwInfoSyntax(ctx *cli.Context) {
u := ctx.String("unit")
if u != "bi" &&
u != "b" &&
u != "Bi" &&
u != "B" &&
u != "" {
cli.ShowCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
}
if len(ctx.Args()) > 1 || len(ctx.Args()) == 0 {
cli.ShowCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
}
}
func mainAdminBwInfo(ctx *cli.Context) {
checkAdminBwInfoSyntax(ctx)
aliasURL, bucket := getAliasAndBucket(ctx)
client := getClient(aliasURL)
reportCh := client.GetBucketBandwidth(globalContext, bucket)
firstPrint := true
bandwidthUnitsString := ctx.String("unit")
for {
select {
case report := <-reportCh:
if len(report.Report.BucketStats) == 0 {
continue
}
if report.Err != nil {
if strings.Contains(report.Err.Error(), "EOF") {
continue
}
console.Error(report.Err)
}
printBandwidth(report, firstPrint, bandwidthUnitsString == "bi" || bandwidthUnitsString == "b",
bandwidthUnitsString == "bi" || bandwidthUnitsString == "Bi")
firstPrint = false
case <-globalContext.Done():
return
}
}
}
func printBandwidth(report madmin.Report, firstPrint bool, bits bool, iec bool) {
rewindLines := len(report.Report.BucketStats) + 4
if firstPrint {
rewindLines = 0
}
if globalJSON {
reportJSON, e := json.MarshalIndent(report, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON")
console.Println(string(reportJSON))
time.Sleep(1 * time.Second)
return
}
if len(report.Report.BucketStats) > 0 {
console.RewindLines(rewindLines)
// For the next iteration, rewind lines
printTable(report, bits, iec)
}
time.Sleep(1 * time.Second)
}
-250
View File
@@ -1,250 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"path"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/pkg/console"
)
var adminBucketRemoteEditFlags = []cli.Flag{
cli.StringFlag{
Name: "arn",
Usage: "ARN of target",
},
cli.StringFlag{
Name: "sync",
Usage: "enable synchronous replication for this target. Valid values are enable,disable.Defaults to disable if unset",
},
cli.StringFlag{
Name: "proxy",
Usage: "enable proxying in active-active replication. Valid values are enable,disable.By default proxying is enabled.",
},
cli.StringFlag{
Name: "bandwidth",
Usage: "Set bandwidth limit in bits per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
},
cli.UintFlag{
Name: "healthcheck-seconds",
Usage: "health check duration in seconds",
Value: 60,
},
cli.StringFlag{
Name: "path",
Value: "auto",
Usage: "bucket path lookup supported by the server. Valid options are '[on,off,auto]'",
},
}
var adminBucketRemoteEditCmd = cli.Command{
Name: "edit",
Usage: "edit remote target",
Action: mainAdminBucketRemoteEdit,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: append(globalFlags, adminBucketRemoteEditFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET --arn arn
TARGET:
Also called as alias/sourcebucketname
DEST_BUCKET:
Also called as remote target bucket.
DEST_URL:
Also called as remote endpoint.
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Edit credentials for existing remote target with arn where a remote target has been configured between sourcebucket on sitea to targetbucket on siteb.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} sitea/sourcebucket \
https://foobar:newpassword@minio.siteb.example.com/targetbucket \
--arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
{{.EnableHistory}}
2. Edit remote target for sourceBucket on sitea with specified ARN to disable proxying and enable synchronous replication
{{.Prompt}} {{.HelpName}} sitea/sourcebucket --sync "enable" --proxy "disable"
--arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
`,
}
// checkAdminBucketRemoteEditSyntax - validate all the passed arguments
func checkAdminBucketRemoteEditSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr > 2 || argsNr == 0 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if !ctx.IsSet("arn") {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "--arn flag needs to be set")
}
}
// modifyRemoteTarget - modifies the dest credentials or updates sync , disable-proxy settings
func modifyRemoteTarget(cli *cli.Context, targets []madmin.BucketTarget) (*madmin.BucketTarget, []madmin.TargetUpdateType) {
args := cli.Args()
foundIdx := -1
arn := cli.String("arn")
for i, t := range targets {
if t.Arn == arn {
foundIdx = i
break
}
}
if foundIdx < 0 {
fatalIf(errInvalidArgument().Trace(args...), "Unable to edit remote target - `"+arn+"` not found")
}
var ops []madmin.TargetUpdateType
bktTarget := targets[foundIdx].Clone()
if cli.IsSet("sync") {
syncState := strings.ToLower(cli.String("sync"))
switch syncState {
case "enable", "disable":
bktTarget.ReplicationSync = syncState == "enable"
ops = append(ops, madmin.SyncUpdateType)
default:
fatalIf(errInvalidArgument().Trace(args...), "--sync can be either [enable|disable]")
}
}
if cli.IsSet("proxy") {
proxyState := strings.ToLower(cli.String("proxy"))
switch proxyState {
case "enable", "disable":
bktTarget.DisableProxy = proxyState == "disable"
ops = append(ops, madmin.ProxyUpdateType)
default:
fatalIf(errInvalidArgument().Trace(args...), "--proxy can be either [enable|disable]")
}
}
if len(args) == 2 {
_, sourceBucket := url2Alias(args[0])
tgtURL := args[1]
accessKey, secretKey, u := extractCredentialURL(tgtURL)
var tgtBucket string
if u.Path != "" {
tgtBucket = path.Clean(u.Path[1:])
}
if e := s3utils.CheckValidBucketName(tgtBucket); e != nil {
fatalIf(probe.NewError(e).Trace(tgtURL), "Invalid target bucket specified")
}
secure := u.Scheme == "https"
host := u.Host
if u.Port() == "" {
port := 80
if secure {
port = 443
}
host = host + ":" + strconv.Itoa(port)
}
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
creds := &madmin.Credentials{AccessKey: accessKey, SecretKey: secretKey}
if host != bktTarget.Endpoint {
fatalIf(errInvalidArgument().Trace(args...), "configured Endpoint `"+host+"` does not match "+bktTarget.Endpoint+"` for this ARN `"+bktTarget.Arn+"`")
}
if tgtBucket != bktTarget.TargetBucket {
fatalIf(errInvalidArgument().Trace(args...), "configured remote target bucket `"+tgtBucket+"` does not match "+bktTarget.TargetBucket+"` for this ARN `"+bktTarget.Arn+"`")
}
if sourceBucket != bktTarget.SourceBucket {
fatalIf(errInvalidArgument().Trace(args...), "configured source bucket `"+sourceBucket+"` does not match "+bktTarget.SourceBucket+"` for this ARN `"+bktTarget.Arn+"`")
}
bktTarget.TargetBucket = tgtBucket
bktTarget.Secure = secure
bktTarget.Credentials = creds
bktTarget.Endpoint = host
ops = append(ops, madmin.CredentialsUpdateType)
}
if cli.IsSet("bandwidth") {
bandwidthStr := cli.String("bandwidth")
bandwidth, err := getBandwidthInBytes(bandwidthStr)
if err != nil {
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
}
bktTarget.BandwidthLimit = int64(bandwidth)
ops = append(ops, madmin.BandwidthLimitUpdateType)
}
if cli.IsSet("healthcheck-seconds") {
bktTarget.HealthCheckDuration = time.Duration(cli.Uint("healthcheck-seconds")) * time.Second
ops = append(ops, madmin.HealthCheckDurationUpdateType)
}
if cli.IsSet("path") {
bktTarget.Path = cli.String("path")
ops = append(ops, madmin.PathUpdateType)
}
return &bktTarget, ops
}
// mainAdminBucketRemoteEdit is the handle for "mc admin bucket remote edit" command.
func mainAdminBucketRemoteEdit(ctx *cli.Context) error {
checkAdminBucketRemoteEditSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
_, sourceBucket := url2Alias(args[0])
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, "")
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch remote target.")
bktTarget, ops := modifyRemoteTarget(ctx, targets)
arn, e := client.UpdateRemoteTarget(globalContext, bktTarget, ops...)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to update remote target `"+bktTarget.Endpoint+"` from `"+bktTarget.SourceBucket+"` -> `"+bktTarget.TargetBucket+"`")
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
TargetURL: bktTarget.URL().String(),
TargetBucket: bktTarget.TargetBucket,
AccessKey: bktTarget.Credentials.AccessKey,
SourceBucket: bktTarget.SourceBucket,
RemoteARN: arn,
})
return nil
}
-164
View File
@@ -1,164 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"path/filepath"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBucketRemoteListFlags = []cli.Flag{
cli.StringFlag{
Name: "service",
Usage: "type of service. valid options are '[replication]'",
},
}
var adminBucketRemoteListCmd = cli.Command{
Name: "ls",
Usage: "list remote target ARN(s)",
Action: mainAdminBucketRemoteList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteListFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get remote bucket target for replication on MinIO server for bucket 'srcbucket'.
{{.Prompt}} {{.HelpName}} myminio/srcbucket --service "replication"
2. List all remote bucket target(s) on MinIO server for bucket 'srcbucket'.
{{.Prompt}} {{.HelpName}} myminio/srcbucket
3. List all remote bucket target(s) on MinIO tenant.
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminBucketRemoteListSyntax - validate all the passed arguments
func checkAdminBucketRemoteListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminBucketRemoteList is the handle for "mc admin bucket remote list" command.
func mainAdminBucketRemoteList(ctx *cli.Context) error {
checkAdminBucketRemoteListSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("RemoteListMessage", color.New(color.Bold, color.FgHiGreen))
console.SetColor("RemoteListEmpty", color.New(color.FgYellow))
console.SetColor("SourceBucket", color.New(color.FgYellow))
console.SetColor("TargetBucket", color.New(color.FgYellow))
console.SetColor("TargetURL", color.New(color.FgHiWhite))
console.SetColor("ARN", color.New(color.FgCyan))
console.SetColor("Arrow", color.New(color.FgHiWhite))
console.SetColor("SyncLabel", color.New(color.FgHiYellow))
console.SetColor("ProxyLabel", color.New(color.FgHiYellow))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL = filepath.Clean(aliasedURL)
_, sourceBucket := url2Alias(aliasedURL)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, ctx.String("service"))
fatalIf(probe.NewError(e).Trace(args...), "Unable to list remote target")
printRemotes(ctx, aliasedURL, targets)
return nil
}
func printRemotes(ctx *cli.Context, urlStr string, targets []madmin.BucketTarget) {
maxURLLen := 10
maxTgtLen := 6
maxSrcLen := 6
maxArnLen := 3
if !globalJSON {
if len(targets) == 0 {
console.Print(console.Colorize("RemoteListEmpty", fmt.Sprintf("No remote targets found for `%s`. \n", urlStr)))
return
}
for _, t := range targets {
l := len(t.Endpoint)
if l > maxURLLen {
maxURLLen = l
}
if len(t.TargetBucket) > maxTgtLen {
maxTgtLen = len(t.TargetBucket)
}
if len(t.SourceBucket) > maxSrcLen {
maxSrcLen = len(t.SourceBucket)
}
if len(t.Arn) > maxArnLen {
maxArnLen = len(t.Arn)
}
}
if maxURLLen > 0 {
console.Println(console.Colorize("RemoteListMessage", fmt.Sprintf("%-*.*s %-*.*s->%-*.*s %-*.*s %s %s", maxURLLen+8, maxURLLen+8, "Remote URL", maxSrcLen, maxSrcLen, "Source", maxTgtLen, maxTgtLen, "Target", maxArnLen, maxArnLen, "ARN", "SYNC", "PROXY")))
}
}
for _, target := range targets {
targetURL := target.URL().String()
if !globalJSON {
if maxURLLen > 0 {
targetURL = fmt.Sprintf("%-*.*s", maxURLLen+8, maxURLLen+8, target.URL().String())
}
if maxTgtLen > 0 {
target.TargetBucket = fmt.Sprintf("%-*.*s", maxTgtLen, maxTgtLen, target.TargetBucket)
}
if maxSrcLen > 0 {
target.SourceBucket = fmt.Sprintf("%-*.*s", maxSrcLen, maxSrcLen, target.SourceBucket)
}
if maxArnLen > 0 {
target.Arn = fmt.Sprintf("%-*.*s", maxArnLen, maxArnLen, target.Arn)
}
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
AccessKey: target.Credentials.AccessKey,
TargetBucket: target.TargetBucket,
TargetURL: targetURL,
SourceBucket: target.SourceBucket,
RemoteARN: target.Arn,
ServiceType: string(target.Type),
ReplicationSync: target.ReplicationSync,
Bandwidth: target.BandwidthLimit,
Proxy: !target.DisableProxy,
ResetID: target.ResetID,
ResetBefore: target.ResetBeforeDate,
})
}
}
-45
View File
@@ -1,45 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminBucketRemoteSubcommands = []cli.Command{
adminBucketRemoteAddCmd,
adminBucketRemoteEditCmd,
adminBucketRemoteListCmd,
adminBucketRemoteRmCmd,
adminBwInfoCmd,
}
var adminBucketRemoteCmd = cli.Command{
Name: "remote",
Usage: "configure remote target buckets",
Action: mainadminBucketRemote,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminBucketRemoteSubcommands,
HideHelpCommand: true,
}
// mainadminBucketRemote is the handle for "mc admin bucket remote" command.
func mainadminBucketRemote(ctx *cli.Context) error {
commandNotFound(ctx, adminBucketRemoteSubcommands)
return nil
// Sub-commands like "add", "ls", "rm" have their own main.
}
-93
View File
@@ -1,93 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBucketRemoteRmFlags = []cli.Flag{
cli.StringFlag{
Name: "arn",
Usage: "ARN to be removed",
},
}
var adminBucketRemoteRmCmd = cli.Command{
Name: "rm",
Usage: "remove configured remote target",
Action: mainAdminBucketRemoteRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteRmFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove existing remote target with arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
for bucket srcbucket on MinIO server.
{{.Prompt}} {{.HelpName}} myminio/srcbucket --arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
`,
}
// checkAdminBucketRemoteRemoveSyntax - validate all the passed arguments
func checkAdminBucketRemoteRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminBucketRemoteRemove is the handle for "mc admin bucket remote rm" command.
func mainAdminBucketRemoteRemove(ctx *cli.Context) error {
checkAdminBucketRemoteRemoveSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr.Trace(aliasedURL), "Unable to initialize admin connection.")
_, sourceBucket := url2Alias(args[0])
if sourceBucket == "" {
fatalIf(errInvalidArgument(), "Source bucket not specified in `"+args[0]+"`.")
}
arn := ctx.String("arn")
if arn == "" {
fatalIf(errInvalidArgument(), "ARN needs to be specified.")
}
fatalIf(probe.NewError(client.RemoveRemoteTarget(globalContext, sourceBucket, arn)).Trace(args...), "Unable to remove remote target")
printMsg(RemoteMessage{
op: ctx.Command.Name,
SourceBucket: sourceBucket,
RemoteARN: arn,
})
return nil
}
+24 -29
View File
@@ -1,42 +1,37 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* 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 adminBucketSubcommands = []cli.Command{
adminBucketRemoteCmd,
adminBucketQuotaCmd,
}
var adminBucketCmd = cli.Command{
Name: "bucket",
Usage: "manage buckets defined in the MinIO server",
Action: mainAdminBucket,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminBucketSubcommands,
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 {
commandNotFound(ctx, adminBucketSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "quota", "remote" have their own main.
// Sub-commands like "quota", "usage" have their own main.
}
+23 -24
View File
@@ -1,35 +1,33 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
var adminConfigExportCmd = cli.Command{
Name: "export",
Usage: "export all config keys to STDOUT",
Before: setGlobalsFromContext,
Action: mainAdminConfigExport,
OnUsageError: onUsageError,
Flags: globalFlags,
Name: "export",
Usage: "export all config keys to STDOUT",
Before: initBeforeRunningCmd,
Action: mainAdminConfigExport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -73,6 +71,7 @@ func checkAdminConfigExportSyntax(ctx *cli.Context) {
}
func mainAdminConfigExport(ctx *cli.Context) error {
checkAdminConfigExportSyntax(ctx)
// Export the alias parameter from cli
@@ -85,7 +84,7 @@ func mainAdminConfigExport(ctx *cli.Context) error {
// Call get config API
buf, e := client.GetConfig(globalContext)
fatalIf(probe.NewError(e), "Unable to get server config")
fatalIf(probe.NewError(e), "Cannot get server config")
// Print
printMsg(configExportMessage{
+32 -50
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2017-2019 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
@@ -21,18 +20,16 @@ import (
"strings"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigGet,
OnUsageError: onUsageError,
Flags: globalFlags,
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigGet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -59,14 +56,13 @@ EXAMPLES:
// configGetMessage container to hold locks information.
type configGetMessage struct {
Status string `json:"status"`
Value *madmin.Target `json:"value"`
value []byte
Status string `json:"status"`
Value []byte `json:"value"`
}
// String colorized service status message.
func (u configGetMessage) String() string {
return string(u.value)
return string(u.Value)
}
// JSON jsonified service status Message message.
@@ -86,6 +82,7 @@ func checkAdminConfigGetSyntax(ctx *cli.Context) {
}
func mainAdminConfigGet(ctx *cli.Context) error {
checkAdminConfigGetSyntax(ctx)
// Get the alias parameter from cli
@@ -99,7 +96,7 @@ func mainAdminConfigGet(ctx *cli.Context) error {
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, "", "", false)
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
printMsg(configHelpMessage{
@@ -110,29 +107,14 @@ func mainAdminConfigGet(ctx *cli.Context) error {
return nil
}
subSys := strings.Join(args.Tail(), " ")
// Call get config API
buf, e := client.GetConfigKV(globalContext, subSys)
fatalIf(probe.NewError(e), "Unable to get server '%s' config", args.Tail())
buf, e := client.GetConfigKV(globalContext, strings.Join(args.Tail(), " "))
fatalIf(probe.NewError(e), "Cannot get server '%s' config", args.Tail())
if globalJSON {
hr, e := client.HelpConfigKV(globalContext, subSys, "", false)
fatalIf(probe.NewError(e), "Unable to get help for "+subSys+" the sub-system")
tgt, e := madmin.ParseSubSysTarget(buf, hr)
fatalIf(probe.NewError(e), "Unable to parse sub-system target "+subSys)
printMsg(configGetMessage{
Value: tgt,
value: buf,
})
} else {
// Print
printMsg(configGetMessage{
value: buf,
})
}
// Print
printMsg(configGetMessage{
Value: buf,
})
return nil
}
+18 -19
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -23,9 +22,9 @@ import (
"text/template"
"github.com/fatih/color"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
// HelpTmpl template used by all sub-systems
@@ -67,7 +66,7 @@ func (u configHelpMessage) String() string {
} else {
e = HelpEnvTemplate.Execute(w, u.Value)
}
fatalIf(probe.NewError(e), "Unable to initialize template writer")
fatalIf(probe.NewError(e), "Cannot initialize template writer")
w.Flush()
+26 -27
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -24,9 +23,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var historyListFlags = []cli.Flag{
@@ -42,12 +41,11 @@ var historyListFlags = []cli.Flag{
}
var adminConfigHistoryCmd = cli.Command{
Name: "history",
Usage: "show all historic configuration changes",
Before: setGlobalsFromContext,
Action: mainAdminConfigHistory,
OnUsageError: onUsageError,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
Name: "history",
Usage: "show all historic configuration changes",
Before: initBeforeRunningCmd,
Action: mainAdminConfigHistory,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -91,7 +89,7 @@ func (u configHistoryMessage) String() string {
var s strings.Builder
w := tabwriter.NewWriter(&s, 1, 8, 2, ' ', 0)
e := HistoryTemplate.Execute(w, u.Entries)
fatalIf(probe.NewError(e), "Unable to initialize template writer")
fatalIf(probe.NewError(e), "Cannot initialize template writer")
w.Flush()
return s.String()
@@ -114,6 +112,7 @@ func checkAdminConfigHistorySyntax(ctx *cli.Context) {
}
func mainAdminConfigHistory(ctx *cli.Context) error {
checkAdminConfigHistorySyntax(ctx)
console.SetColor("ConfigHistoryMessageRestoreID", color.New(color.Bold))
@@ -128,7 +127,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
if ctx.IsSet("clear") {
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Unable to clear server configuration.")
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Cannot clear server configuration.")
// Print
printMsg(configHistoryMessage{})
@@ -136,7 +135,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
}
chEntries, e := client.ListConfigHistoryKV(globalContext, ctx.Int("count"))
fatalIf(probe.NewError(e), "Unable to list server history configuration.")
fatalIf(probe.NewError(e), "Cannot list server history configuration.")
hentries := make([]historyEntry, len(chEntries))
for i, chEntry := range chEntries {
+24 -25
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -23,18 +22,17 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminConfigImportCmd = cli.Command{
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: setGlobalsFromContext,
Action: mainAdminConfigImport,
OnUsageError: onUsageError,
Flags: globalFlags,
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: initBeforeRunningCmd,
Action: mainAdminConfigImport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -83,6 +81,7 @@ func checkAdminConfigImportSyntax(ctx *cli.Context) {
}
func mainAdminConfigImport(ctx *cli.Context) error {
checkAdminConfigImportSyntax(ctx)
// Set color preference of command outputs
@@ -97,7 +96,7 @@ func mainAdminConfigImport(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call set config API
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Unable to set server config")
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Cannot set server config")
// Print
printMsg(configImportMessage{
+28 -33
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -23,9 +22,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminConfigEnvFlags = []cli.Flag{
@@ -36,12 +35,11 @@ var adminConfigEnvFlags = []cli.Flag{
}
var adminConfigResetCmd = cli.Command{
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigReset,
OnUsageError: onUsageError,
Flags: append(adminConfigEnvFlags, globalFlags...),
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigReset,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -61,7 +59,6 @@ EXAMPLES:
type configResetMessage struct {
Status string `json:"status"`
targetAlias string
restart bool
}
// String colorized service status message.
@@ -69,10 +66,8 @@ func (u configResetMessage) String() (msg string) {
msg += console.Colorize("ResetConfigSuccess",
"Key is successfully reset.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
if u.restart {
msg += console.Colorize("ResetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
}
msg += console.Colorize("ResetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
return
}
@@ -94,6 +89,7 @@ func checkAdminConfigResetSyntax(ctx *cli.Context) {
// main config set function
func mainAdminConfigReset(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigResetSyntax(ctx)
@@ -112,7 +108,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
printMsg(configHelpMessage{
@@ -125,13 +121,12 @@ func mainAdminConfigReset(ctx *cli.Context) error {
// Call reset config API
input := strings.Join(args.Tail(), " ")
restart, e := client.DelConfigKV(globalContext, input)
fatalIf(probe.NewError(e), "Unable to reset '%s' on the server", input)
fatalIf(probe.NewError(client.DelConfigKV(globalContext, input)),
"Cannot reset '%s' on the server", input)
// Print set config result
printMsg(configResetMessage{
targetAlias: aliasedURL,
restart: restart,
})
return nil
+24 -25
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -22,18 +21,17 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminConfigRestoreCmd = cli.Command{
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: setGlobalsFromContext,
Action: mainAdminConfigRestore,
OnUsageError: onUsageError,
Flags: globalFlags,
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: initBeforeRunningCmd,
Action: mainAdminConfigRestore,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -82,6 +80,7 @@ func checkAdminConfigRestoreSyntax(ctx *cli.Context) {
}
func mainAdminConfigRestore(ctx *cli.Context) error {
checkAdminConfigRestoreSyntax(ctx)
console.SetColor("ConfigRestoreMessage", color.New(color.FgGreen))
@@ -95,7 +94,7 @@ func mainAdminConfigRestore(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call get config API
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Unable to restore server configuration.")
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Cannot restore server configuration.")
// Print
printMsg(configRestoreMessage{
+31 -39
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2017-2019 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
@@ -23,19 +22,18 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "interactively set a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigSet,
OnUsageError: onUsageError,
Flags: append(adminConfigEnvFlags, globalFlags...),
Name: "set",
Usage: "interactively set a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigSet,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -51,9 +49,6 @@ EXAMPLES:
2. Change region name for the MinIO server to 'us-west-1'.
{{.Prompt}} {{.HelpName}} myminio/ region name=us-west-1
3. Change healing settings on a distributed MinIO server setup.
{{.Prompt}} {{.HelpName}} mydist/ heal max_delay=300ms max_io=50
`,
}
@@ -61,18 +56,15 @@ EXAMPLES:
type configSetMessage struct {
Status string `json:"status"`
targetAlias string
restart bool
}
// String colorized service status message.
func (u configSetMessage) String() (msg string) {
msg += console.Colorize("SetConfigSuccess",
"Successfully applied new settings.")
if u.restart {
suggestion := color.RedString("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("\nPlease restart your server '%s'.", suggestion))
}
"Setting new key has been successful.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
return
}
@@ -94,6 +86,7 @@ func checkAdminConfigSetSyntax(ctx *cli.Context) {
// main config set function
func mainAdminConfigSet(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigSetSyntax(ctx)
@@ -113,7 +106,7 @@ func mainAdminConfigSet(ctx *cli.Context) error {
if !strings.Contains(input, madmin.KvSeparator) {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
printMsg(configHelpMessage{
@@ -126,13 +119,12 @@ func mainAdminConfigSet(ctx *cli.Context) error {
}
// Call set config API
restart, e := client.SetConfigKV(globalContext, input)
fatalIf(probe.NewError(e), "Unable to set '%s' to server", input)
fatalIf(probe.NewError(client.SetConfigKV(globalContext, input)),
"Cannot set '%s' to server", input)
// Print set config result
printMsg(configSetMessage{
targetAlias: aliasedURL,
restart: restart,
})
return nil
+29 -33
View File
@@ -1,47 +1,43 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2017-2019 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 adminConfigSubcommands = []cli.Command{
adminConfigGetCmd,
adminConfigSetCmd,
adminConfigResetCmd,
adminConfigHistoryCmd,
adminConfigRestoreCmd,
adminConfigExportCmd,
adminConfigImportCmd,
}
var adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminConfigSubcommands,
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
adminConfigSetCmd,
adminConfigResetCmd,
adminConfigHistoryCmd,
adminConfigRestoreCmd,
adminConfigExportCmd,
adminConfigImportCmd,
},
HideHelpCommand: true,
}
// mainAdminConfig is the handle for "mc admin config" command.
func mainAdminConfig(ctx *cli.Context) error {
commandNotFound(ctx, adminConfigSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "get", "set" have their own main.
}
+24 -28
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -25,10 +24,10 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
const logTimeFormat string = "15:04:05 MST 01/02/2006"
@@ -50,8 +49,7 @@ var adminConsoleCmd = cli.Command{
Name: "console",
Usage: "show console logs for MinIO server",
Action: mainAdminConsole,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminConsoleFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -83,19 +81,17 @@ func checkAdminLogSyntax(ctx *cli.Context) {
// Extend madmin.LogInfo to add String() and JSON() methods
type logMessage struct {
Status string `json:"status"`
madmin.LogInfo
}
// JSON - jsonify loginfo
func (l logMessage) JSON() string {
l.Status = "success"
logJSON, err := json.MarshalIndent(&l, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
return string(logJSON)
}
}
func getLogTime(lt string) string {
tm, err := time.Parse(time.RFC3339Nano, lt)
if err != nil {
@@ -107,7 +103,7 @@ func getLogTime(lt string) string {
// String - return colorized loginfo as string.
func (l logMessage) String() string {
var hostStr string
b := &strings.Builder{}
var b = &strings.Builder{}
if l.NodeName != "" {
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
}
@@ -196,7 +192,7 @@ func mainAdminConsole(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
@@ -207,13 +203,13 @@ func mainAdminConsole(ctx *cli.Context) error {
logCh := client.GetLogs(ctxt, node, limit, logType)
for logInfo := range logCh {
if logInfo.Err != nil {
fatalIf(probe.NewError(logInfo.Err), "Unable to listen to console logs")
fatalIf(probe.NewError(logInfo.Err), "Cannot listen to console logs")
}
// drop nodeName from output if specified as cli arg
if node != "" {
logInfo.NodeName = ""
}
printMsg(logMessage{LogInfo: logInfo})
printMsg(logMessage{logInfo})
}
return nil
}
+24 -26
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -23,19 +22,18 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminGroupAddCmd = cli.Command{
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -133,7 +131,7 @@ func mainAdminGroupAdd(ctx *cli.Context) error {
Members: members,
IsRemove: false,
}
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Unable to add new group")
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Cannot add new group")
printMsg(groupMessage{
op: "add",
+20 -22
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -22,12 +21,11 @@ import (
)
var adminGroupDisableCmd = cli.Command{
Name: "disable",
Usage: "disable a group",
Action: mainAdminGroupEnableDisable,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "disable",
Usage: "Disable a group",
Action: mainAdminGroupEnableDisable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+22 -24
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -22,18 +21,17 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminGroupEnableCmd = cli.Command{
Name: "enable",
Usage: "enable a group",
Action: mainAdminGroupEnableDisable,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "enable",
Usage: "Enable a group",
Action: mainAdminGroupEnableDisable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+21 -23
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -21,16 +20,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminGroupInfoCmd = cli.Command{
Name: "info",
Usage: "display group info",
Action: mainAdminGroupInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "info",
Usage: "display group info",
Action: mainAdminGroupInfo,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+21 -23
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -21,16 +20,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminGroupListCmd = cli.Command{
Name: "list",
Usage: "display list of groups",
Action: mainAdminGroupList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "list",
Usage: "display list of groups",
Action: mainAdminGroupList,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+22 -24
View File
@@ -1,37 +1,35 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminGroupRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+28 -32
View File
@@ -1,46 +1,42 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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 adminGroupSubcommands = []cli.Command{
adminGroupAddCmd,
adminGroupRemoveCmd,
adminGroupInfoCmd,
adminGroupListCmd,
adminGroupEnableCmd,
adminGroupDisableCmd,
}
var adminGroupCmd = cli.Command{
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminGroupSubcommands,
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Flags: globalFlags,
Subcommands: []cli.Command{
adminGroupAddCmd,
adminGroupRemoveCmd,
adminGroupInfoCmd,
adminGroupListCmd,
adminGroupEnableCmd,
adminGroupDisableCmd,
},
HideHelpCommand: true,
}
// mainAdminGroup is the handle for "mc admin config" command.
func mainAdminGroup(ctx *cli.Context) error {
commandNotFound(ctx, adminGroupSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "get", "set" have their own main.
}
+17 -23
View File
@@ -1,26 +1,25 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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"
"github.com/minio/madmin-go"
"github.com/minio/minio/pkg/madmin"
)
type hri struct {
@@ -43,16 +42,11 @@ func (h hri) getObjectHCCChange() (b, a col, err error) {
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
if err != nil {
err = fmt.Errorf("%w: surplusShardsBeforeHeal: %d, parityShards: %d",
err, surplusShardsBeforeHeal, parityShards)
return
}
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
if err != nil {
err = fmt.Errorf("%w: surplusShardsBeforeHeal: %d, parityShards: %d",
err, surplusShardsAfterHeal, parityShards)
}
return
}
// getReplicatedFileHCCChange - fetches health color code for metadata
+26 -24
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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
@@ -26,10 +25,10 @@ import (
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
const (
@@ -260,12 +259,11 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
} `json:"after"`
Size int64 `json:"size"`
}
makeHR := func(h *hri) (r healRec) {
makeHR := func(h *hri) (r healRec, err error) {
r.Status = "success"
r.Type, r.Name = h.getHRTypeAndName()
var b, a col
var err error
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
b, a, err = h.getReplicatedFileHCCChange()
@@ -276,7 +274,7 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
b, a, err = h.getObjectHCCChange()
}
if err != nil {
r.Error = err.Error()
return r, err
}
r.Before.Color = strings.ToLower(string(b))
r.After.Color = strings.ToLower(string(a))
@@ -286,12 +284,16 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
r.Before.Offline, r.After.Offline = h.GetOfflineCounts()
r.Before.Drives = h.Before.Drives
r.After.Drives = h.After.Drives
return r
return r, nil
}
for _, item := range s.Items {
h := newHRI(&item)
jsonBytes, err := json.MarshalIndent(makeHR(h), "", " ")
r, err := makeHR(h)
if err != nil {
return err
}
jsonBytes, err := json.MarshalIndent(r, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
console.Println(string(jsonBytes))
}
+78 -484
View File
@@ -1,37 +1,33 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2017, 2018 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"
"net/url"
"path/filepath"
"sort"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
const (
@@ -59,24 +55,19 @@ var adminHealFlags = []cli.Flag{
},
cli.BoolFlag{
Name: "force-stop, s",
Usage: "force stop a running heal sequence",
Usage: "Force stop a running heal sequence",
},
cli.BoolFlag{
Name: "remove",
Usage: "remove dangling objects in heal sequence",
},
cli.StringFlag{
Name: "storage-class",
Usage: "show server/disks failure tolerance with the given storage class",
},
}
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "heal disks, buckets and objects on MinIO server",
Action: mainAdminHeal,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -88,14 +79,34 @@ USAGE:
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
SCAN MODES:
normal (default): Heal objects which are missing on one or more disks.
deep : Heal objects which are missing or with silent data corruption on one or more disks.
EXAMPLES:
1. Monitor healing status on a running server at alias 'myminio':
{{.Prompt}} {{.HelpName}} myminio/
...
...
Summary:
=======
No ongoing active healing.
1. To format newly replaced disks in a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio
2. Heal 'testbucket' in a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio/testbucket/
3. Heal all objects under 'dir' prefix
{{.Prompt}} {{.HelpName}} --recursive myminio/testbucket/dir/
4. Issue a dry-run heal operation to inspect objects health but not heal them
{{.Prompt}} {{.HelpName}} --dry-run myminio
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
{{.Prompt}} {{.HelpName}} --recursive --dry-run myminio/testbucket/dir/
6. Force start a running heal sequence (meaning it will force kill the running heal sequence and start a new one)
{{.Prompt}} {{.HelpName}} --force-start myminio/testbucket/dir/
7. Force stop a running heal sequence (meaning it will force kill the running heal sequence)
{{.Prompt}} {{.HelpName}} --force-stop myminio/testbucket/dir/
8. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
{{.Prompt}} {{.HelpName}} --dry-run myminio/testbucket/dir/
`,
}
@@ -131,445 +142,37 @@ func (s stopHealMessage) JSON() string {
return string(stopHealJSONBytes)
}
// verboseBackgroundHealStatusMessage is container for stop heal success and failure messages.
type verboseBackgroundHealStatusMessage struct {
Status string `json:"status"`
HealInfo madmin.BgHealState
// Specify storage class to show servers/disks tolerance
ToleranceForSC string `json:"-"`
}
type setIndex struct {
pool, set int
}
type healingStatus struct {
started time.Time
totalObjects uint64
totalHealed uint64
}
// Estimation of when the healing will finish
func (h healingStatus) ETA() time.Time {
if !h.started.IsZero() && h.totalObjects > h.totalHealed {
objScanSpeed := float64(time.Now().UTC().Sub(h.started)) / float64(h.totalHealed)
remainingDuration := float64(h.totalObjects-h.totalHealed) * objScanSpeed
return time.Now().UTC().Add(time.Duration(remainingDuration))
}
return time.Time{}
}
type poolInfo struct {
tolerance int
endpoints []string
}
type diskInfo struct {
set setIndex
path string
state string
healing bool
usedSpace, totalSpace uint64
}
type setInfo struct {
healingStatus healingStatus
totalDisks int
incapableDisks int
}
type serverInfo struct {
pool int
disks []diskInfo
}
func (s serverInfo) onlineDisksForSet(index setIndex) (setFound bool, count int) {
for _, disk := range s.disks {
if disk.set != index {
continue
}
setFound = true
if disk.state == "ok" && !disk.healing {
count++
}
}
return
}
// Get all disks from set statuses
func getAllDisks(sets []madmin.SetStatus) []madmin.Disk {
var disks []madmin.Disk
for _, set := range sets {
disks = append(disks, set.Disks...)
}
return disks
}
// Get all pools id from all disks
func getPoolsIndexes(disks []madmin.Disk) []int {
m := make(map[int]struct{})
for _, d := range disks {
m[d.PoolIndex] = struct{}{}
}
var pools []int
for pool := range m {
pools = append(pools, pool)
}
sort.Ints(pools)
return pools
}
// Generate sets info from disks
func generateSetsStatus(disks []madmin.Disk) map[setIndex]setInfo {
m := make(map[setIndex]setInfo)
for _, d := range disks {
idx := setIndex{pool: d.PoolIndex, set: d.SetIndex}
setSt, ok := m[idx]
if !ok {
setSt = setInfo{}
}
setSt.totalDisks++
if d.State != "ok" || d.Healing {
setSt.incapableDisks++
}
if d.Healing && d.HealInfo != nil {
setSt.healingStatus.started = d.HealInfo.Started
setSt.healingStatus.totalObjects = d.HealInfo.ObjectsTotalCount
setSt.healingStatus.totalHealed = d.HealInfo.ObjectsHealed
}
m[idx] = setSt
}
return m
}
// Return a map of server endpoints and the corresponding status
func generateServersStatus(disks []madmin.Disk) map[string]serverInfo {
m := make(map[string]serverInfo)
for _, d := range disks {
u, err := url.Parse(d.Endpoint)
if err != nil {
continue
}
endpoint := u.Host
if endpoint == "" {
endpoint = "local-pool" + humanize.Ordinal(d.PoolIndex+1)
}
serverSt, ok := m[endpoint]
if !ok {
serverSt = serverInfo{
pool: d.PoolIndex,
}
}
setIndex := setIndex{pool: d.PoolIndex, set: d.SetIndex}
serverSt.disks = append(serverSt.disks, diskInfo{
set: setIndex,
path: u.Path,
state: d.State,
healing: d.Healing,
usedSpace: d.UsedSpace,
totalSpace: d.TotalSpace,
})
m[endpoint] = serverSt
}
return m
}
// Return the list of endpoints of a given pool index
func computePoolEndpoints(pool int, serversStatus map[string]serverInfo) []string {
var endpoints []string
for endpoint, server := range serversStatus {
if server.pool != pool {
continue
}
endpoints = append(endpoints, endpoint)
}
return endpoints
}
// Compute the tolerance of each node in a given pool
func computePoolTolerance(pool, parity int, setsStatus map[setIndex]setInfo, serversStatus map[string]serverInfo) int {
var (
onlineDisksPerSet = make(map[setIndex]int)
tolerancePerSet = make(map[setIndex]int)
)
for set, setStatus := range setsStatus {
if set.pool != pool {
continue
}
onlineDisksPerSet[set] = setStatus.totalDisks - setStatus.incapableDisks
tolerancePerSet[set] = 0
for _, server := range serversStatus {
if server.pool != pool {
continue
}
canShutdown := true
setFound, count := server.onlineDisksForSet(set)
if !setFound {
continue
}
minDisks := setStatus.totalDisks - parity
if onlineDisksPerSet[set]-count < minDisks {
canShutdown = false
}
if canShutdown {
tolerancePerSet[set]++
onlineDisksPerSet[set] -= count
} else {
break
}
}
}
minServerTolerance := len(serversStatus)
for _, tolerance := range tolerancePerSet {
if tolerance < minServerTolerance {
minServerTolerance = tolerance
}
}
return minServerTolerance
}
// Extract offline nodes from offline full path endpoints
func getOfflineNodes(endpoints []string) map[string]struct{} {
offlineNodes := make(map[string]struct{})
for _, endpoint := range endpoints {
offlineNodes[endpoint] = struct{}{}
}
return offlineNodes
}
// String colorized to show background heal status message.
func (s verboseBackgroundHealStatusMessage) String() string {
var msg strings.Builder
parity, showTolerance := s.HealInfo.SCParity[s.ToleranceForSC]
offlineEndpoints := getOfflineNodes(s.HealInfo.OfflineEndpoints)
allDisks := getAllDisks(s.HealInfo.Sets)
pools := getPoolsIndexes(allDisks)
setsStatus := generateSetsStatus(allDisks)
serversStatus := generateServersStatus(allDisks)
poolsInfo := make(map[int]poolInfo)
for _, pool := range pools {
tolerance := computePoolTolerance(pool, parity, setsStatus, serversStatus)
endpoints := computePoolEndpoints(pool, serversStatus)
poolsInfo[pool] = poolInfo{tolerance: tolerance, endpoints: endpoints}
}
distributed := len(serversStatus) > 1
plural := ""
if distributed {
plural = "s"
}
fmt.Fprintf(&msg, "Server%s status:\n", plural)
fmt.Fprintf(&msg, "==============\n")
for _, pool := range pools {
fmt.Fprintf(&msg, "Pool %s:\n", humanize.Ordinal(pool+1))
// Sort servers in this pool by name
orderedEndpoints := make([]string, len(poolsInfo[pool].endpoints))
copy(orderedEndpoints, poolsInfo[pool].endpoints)
sort.Strings(orderedEndpoints)
for _, endpoint := range orderedEndpoints {
// Print offline status if node is offline
_, ok := offlineEndpoints[endpoint]
if ok {
stateText := console.Colorize("NodeFailed", "OFFLINE")
fmt.Fprintf(&msg, fmt.Sprintf(" %s: %s\n", endpoint, stateText))
continue
}
serverStatus := serversStatus[endpoint]
switch {
case showTolerance:
serverHeader := " %s: (Tolerance: %d server(s))\n"
fmt.Fprintf(&msg, fmt.Sprintf(serverHeader, endpoint, poolsInfo[serverStatus.pool].tolerance))
default:
serverHeader := " %s:\n"
fmt.Fprintf(&msg, fmt.Sprintf(serverHeader, endpoint))
}
for _, d := range serverStatus.disks {
if d.set.pool != pool {
continue
}
stateText := ""
switch {
case d.state == "ok" && d.healing:
stateText = console.Colorize("DiskHealing", "HEALING")
case d.state == "ok":
stateText = console.Colorize("DiskOK", "OK")
default:
stateText = console.Colorize("DiskFailed", d.state)
}
fmt.Fprintf(&msg, " + %s : %s\n", d.path, stateText)
if d.healing {
estimationText := "Calculating..."
if eta := setsStatus[d.set].healingStatus.ETA(); !eta.IsZero() {
estimationText = humanize.RelTime(time.Now().UTC(), eta, "", "")
}
fmt.Fprintf(&msg, " |__ Estimated: %s\n", estimationText)
}
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.usedSpace), humanize.IBytes(d.totalSpace))
if showTolerance {
fmt.Fprintf(&msg, " |__ Tolerance: %d disk(s)\n", parity-setsStatus[d.set].incapableDisks)
}
}
fmt.Fprintf(&msg, "\n")
}
}
if showTolerance {
fmt.Fprintf(&msg, "\n")
fmt.Fprintf(&msg, "Server Failure Tolerance:\n")
fmt.Fprintf(&msg, "========================\n")
for i, pool := range poolsInfo {
fmt.Fprintf(&msg, "Pool %s:\n", humanize.Ordinal(i+1))
fmt.Fprintf(&msg, " Tolerance : %d server(s)\n", pool.tolerance)
fmt.Fprintf(&msg, " Nodes :")
for _, endpoint := range pool.endpoints {
fmt.Fprintf(&msg, " %s", endpoint)
}
fmt.Fprintf(&msg, "\n")
}
}
summary := shortBackgroundHealStatusMessage{HealInfo: s.HealInfo}
fmt.Fprintf(&msg, "\n")
fmt.Fprintf(&msg, "Summary:\n")
fmt.Fprintf(&msg, "=======\n")
fmt.Fprintf(&msg, summary.String())
fmt.Fprintf(&msg, "\n")
return msg.String()
}
// JSON jsonified stop heal message.
func (s verboseBackgroundHealStatusMessage) JSON() string {
healJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(healJSONBytes)
}
// shortBackgroundHealStatusMessage is container for stop heal success and failure messages.
type shortBackgroundHealStatusMessage struct {
// backgroundHealStatusMessage is container for stop heal success and failure messages.
type backgroundHealStatusMessage struct {
Status string `json:"status"`
HealInfo madmin.BgHealState
}
// String colorized to show background heal status message.
func (s shortBackgroundHealStatusMessage) String() string {
healPrettyMsg := ""
var (
totalItems uint64
totalBytes uint64
itemsHealed uint64
bytesHealed uint64
startedAt time.Time
func (s backgroundHealStatusMessage) String() string {
dot := console.Colorize("Dot", " ● ")
// The addition of Elapsed time of each parallel healing operation
accumulatedElapsedTime time.Duration
)
healPrettyMsg := console.Colorize("HealBackgroundTitle", "Background healing status:\n")
healPrettyMsg += dot + fmt.Sprintf("%s item(s) scanned in total\n",
console.Colorize("HealBackground", s.HealInfo.ScannedItemsCount))
type setInfo struct {
pool, set int
}
dedup := make(map[setInfo]struct{})
for _, set := range s.HealInfo.Sets {
for _, disk := range set.Disks {
if disk.HealInfo != nil {
// Avoid counting two disks beloning to the same pool/set
diskLocation := setInfo{pool: disk.PoolIndex, set: disk.SetIndex}
_, found := dedup[diskLocation]
if found {
continue
}
dedup[diskLocation] = struct{}{}
// Approximate values
totalItems += disk.HealInfo.ObjectsTotalCount
totalBytes += disk.HealInfo.ObjectsTotalSize
itemsHealed += disk.HealInfo.ItemsHealed
bytesHealed += disk.HealInfo.BytesDone
if !disk.HealInfo.Started.IsZero() && !disk.HealInfo.Started.Before(startedAt) {
startedAt = disk.HealInfo.Started
}
if !disk.HealInfo.Started.IsZero() && !disk.HealInfo.LastUpdate.IsZero() {
accumulatedElapsedTime += disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started)
}
}
}
lastHealingTime := dot + "Never executed"
if !s.HealInfo.LastHealActivity.IsZero() {
lastHealingTime = dot + "Completed " + timeDurationToHumanizedDuration(time.Since(s.HealInfo.LastHealActivity)).StringShort() + " ago"
}
healPrettyMsg += console.Colorize("HealBackground", lastHealingTime) + "\n"
now := time.Now()
for _, mrf := range s.HealInfo.MRF {
totalItems += mrf.TotalItems
totalBytes += mrf.TotalBytes
bytesHealed += mrf.BytesHealed
itemsHealed += mrf.ItemsHealed
if !mrf.Started.IsZero() {
if startedAt.IsZero() || mrf.Started.Before(startedAt) {
startedAt = mrf.Started
}
accumulatedElapsedTime += now.Sub(mrf.Started)
}
}
if startedAt.IsZero() && itemsHealed == 0 {
healPrettyMsg += "No active healing in progress."
return healPrettyMsg
}
if totalItems > 0 && totalBytes > 0 {
// Objects healed information
itemsPct := 100 * float64(itemsHealed) / float64(totalItems)
bytesPct := 100 * float64(bytesHealed) / float64(totalBytes)
healPrettyMsg += fmt.Sprintf("Objects Healed: %s/%s (%s), %s/%s (%s)\n",
humanize.Comma(int64(itemsHealed)), humanize.Comma(int64(totalItems)), humanize.CommafWithDigits(itemsPct, 1)+"%%",
humanize.Bytes(bytesHealed), humanize.Bytes(totalBytes), humanize.CommafWithDigits(bytesPct, 1)+"%%")
} else {
healPrettyMsg += fmt.Sprintf("Objects Healed: %s, %s\n", humanize.Comma(int64(itemsHealed)), humanize.Bytes(bytesHealed))
}
if accumulatedElapsedTime > 0 {
bytesHealedPerSec := float64(uint64(time.Second)*bytesHealed) / float64(accumulatedElapsedTime)
itemsHealedPerSec := float64(uint64(time.Second)*itemsHealed) / float64(accumulatedElapsedTime)
healPrettyMsg += fmt.Sprintf("Heal rate: %d obj/s, %s/s\n", int64(itemsHealedPerSec), humanize.IBytes(uint64(bytesHealedPerSec)))
}
if totalItems > 0 && totalBytes > 0 && !startedAt.IsZero() {
// Estimation completion
avgTimePerObject := float64(accumulatedElapsedTime) / float64(itemsHealed)
estimatedDuration := time.Duration(avgTimePerObject * float64(totalItems))
estimatedFinishTime := startedAt.Add(estimatedDuration)
healPrettyMsg += fmt.Sprintf("Estimated Completion: %s\n", humanize.RelTime(now, estimatedFinishTime, "", ""))
if !s.HealInfo.NextHealRound.IsZero() && s.HealInfo.NextHealRound.After(now) {
nextHealingRound := timeDurationToHumanizedDuration(s.HealInfo.NextHealRound.Sub(now)).StringShort()
healPrettyMsg += dot + fmt.Sprintf("Next scheduled in %s\n", console.Colorize("HealBackground", nextHealingRound))
}
return healPrettyMsg
}
// JSON jsonified stop heal message.
func (s shortBackgroundHealStatusMessage) JSON() string {
func (s backgroundHealStatusMessage) JSON() string {
healJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -586,6 +189,7 @@ func transformScanArg(scanArg string) madmin.HealScanMode {
// mainAdminHeal - the entry function of heal command
func mainAdminHeal(ctx *cli.Context) error {
// Check for command syntax
checkAdminHealSyntax(ctx)
@@ -600,15 +204,10 @@ func mainAdminHeal(ctx *cli.Context) error {
console.SetColor("HealUpdateUI", color.New(color.FgYellow, color.Bold))
console.SetColor("HealStopped", color.New(color.FgGreen, color.Bold))
console.SetColor("DiskHealing", color.New(color.FgYellow, color.Bold))
console.SetColor("DiskOK", color.New(color.FgGreen, color.Bold))
console.SetColor("DiskFailed", color.New(color.FgRed, color.Bold))
console.SetColor("NodeFailed", color.New(color.FgRed, color.Bold))
// Create a new MinIO Admin Client
adminClnt, err := newAdminClient(aliasedURL)
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
@@ -622,27 +221,22 @@ func mainAdminHeal(ctx *cli.Context) error {
fatalIf(err.Trace(clnt.GetURL().String()), "Unable to create client for URL ", aliasedURL)
return nil
}
// Return the background heal status when the user
// doesn't pass a bucket or --recursive flag.
if bucket == "" && !ctx.Bool("recursive") {
bgHealStatus, berr := adminClnt.BackgroundHealStatus(globalContext)
fatalIf(probe.NewError(berr), "Failed to get the status of the background heal.")
printMsg(verboseBackgroundHealStatusMessage{
Status: "success",
HealInfo: bgHealStatus,
ToleranceForSC: strings.ToUpper(ctx.String("storage-class")),
})
return nil
}
for content := range clnt.List(globalContext, ListOptions{Recursive: false, ShowDir: 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
}
}
// Return the background heal status when the user
// doesn't pass a bucket or --recursive flag.
if bucket == "" && !ctx.Bool("recursive") {
bgHealStatus, berr := client.BackgroundHealStatus(globalContext)
fatalIf(probe.NewError(berr), "Failed to get the status of the background heal.")
printMsg(backgroundHealStatusMessage{Status: "success", HealInfo: bgHealStatus})
return nil
}
opts := madmin.HealOpts{
ScanMode: transformScanArg(ctx.String("scan")),
Remove: ctx.Bool("remove"),
@@ -653,19 +247,19 @@ func mainAdminHeal(ctx *cli.Context) error {
forceStart := ctx.Bool("force-start")
forceStop := ctx.Bool("force-stop")
if forceStop {
_, _, herr := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
_, _, herr := client.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
fatalIf(probe.NewError(herr), "Failed to stop heal sequence.")
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
return nil
}
healStart, _, herr := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
healStart, _, herr := client.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
fatalIf(probe.NewError(herr), "Failed to start heal sequence.")
ui := uiData{
Bucket: bucket,
Prefix: prefix,
Client: adminClnt,
Client: client,
ClientToken: healStart.ClientToken,
ForceStart: forceStart,
HealOpts: &opts,
+37 -87
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -21,7 +20,6 @@ import (
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
@@ -30,19 +28,18 @@ import (
"github.com/dustin/go-humanize/english"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -81,12 +78,12 @@ type clusterStruct struct {
func (u clusterStruct) String() (msg string) {
// Check cluster level "Status" field for error
if u.Status == "error" {
fatal(probe.NewError(errors.New(u.Error)), "Unable to get service status")
fatal(probe.NewError(errors.New(u.Error)), "Cannot get service status")
}
// If nothing has been collected, error out
if u.Info.Servers == nil {
fatal(probe.NewError(errors.New("Unable to get service status")), "")
fatal(probe.NewError(errors.New("Cannot get service status")), "")
}
// Initialization
@@ -96,7 +93,6 @@ func (u clusterStruct) String() (msg string) {
// Color palette initialization
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
console.SetColor("InfoWarning", color.New(color.FgYellow, color.Bold))
// MinIO server type default
backendType := "Unknown"
@@ -112,15 +108,6 @@ func (u clusterStruct) String() (msg string) {
}
}
coloredDot := console.Colorize("Info", dot)
if madmin.ItemState(u.Info.Mode) == madmin.ItemInitializing {
coloredDot = console.Colorize("InfoWarning", dot)
}
sort.Slice(u.Info.Servers, func(i, j int) bool {
return u.Info.Servers[i].Endpoint < u.Info.Servers[j].Endpoint
})
// Loop through each server and put together info for each one
for _, srv := range u.Info.Servers {
// Check if MinIO server is offline ("Mode" field),
@@ -128,40 +115,13 @@ func (u clusterStruct) String() (msg string) {
if srv.State == "offline" {
// "PrintB" is color blue in console library package
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", srv.Endpoint))
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", "offline"))
if backendType != "FS" {
// Info about drives on a server, only available for non-FS types
var OffDisks int
var OnDisks int
var dispNoOfDisks string
for _, disk := range srv.Disks {
switch disk.State {
case madmin.DriveStateOk:
fallthrough
case madmin.DriveStateUnformatted:
OnDisks++
default:
OffDisks++
}
}
totalDisksPerServer := OnDisks + OffDisks
totalOnlineDisksCluster += OnDisks
totalOfflineDisksCluster += OffDisks
dispNoOfDisks = strconv.Itoa(OnDisks) + "/" + strconv.Itoa(totalDisksPerServer)
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize("InfoFail", "OK "))
}
msg += "\n"
msg += fmt.Sprintf(" Uptime: %s\n\n", console.Colorize("InfoFail", "offline"))
// Continue to the next server
continue
}
// Print server title
msg += fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("PrintB", srv.Endpoint))
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), console.Colorize("PrintB", srv.Endpoint))
// Uptime
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("Info",
@@ -175,20 +135,16 @@ func (u clusterStruct) String() (msg string) {
msg += fmt.Sprintf(" Version: %s\n", version)
// Network info, only available for non-FS types
connectionAlive := 0
totalNodes := len(srv.Network)
var connectionAlive int
totalNodes := strconv.Itoa(len(srv.Network))
if srv.Network != nil {
for _, v := range srv.Network {
if v == "online" {
connectionAlive++
}
}
clr := "Info"
if connectionAlive != totalNodes {
clr = "InfoWarning"
}
displayNwInfo := strconv.Itoa(connectionAlive) + "/" + strconv.Itoa(totalNodes)
msg += fmt.Sprintf(" Network: %s %s\n", displayNwInfo, console.Colorize(clr, "OK "))
displayNwInfo := strconv.Itoa(connectionAlive) + "/" + totalNodes
msg += fmt.Sprintf(" Network: %s %s\n", displayNwInfo, console.Colorize("Info", "OK "))
}
if backendType != "FS" {
@@ -197,12 +153,9 @@ func (u clusterStruct) String() (msg string) {
var OnDisks int
var dispNoOfDisks string
for _, disk := range srv.Disks {
switch disk.State {
case madmin.DriveStateOk:
fallthrough
case madmin.DriveStateUnformatted:
if disk.State == "ok" {
OnDisks++
default:
} else {
OffDisks++
}
}
@@ -210,12 +163,9 @@ func (u clusterStruct) String() (msg string) {
totalDisksPerServer := OnDisks + OffDisks
totalOnlineDisksCluster += OnDisks
totalOfflineDisksCluster += OffDisks
clr := "Info"
if OnDisks != totalDisksPerServer {
clr = "InfoWarning"
}
dispNoOfDisks = strconv.Itoa(OnDisks) + "/" + strconv.Itoa(totalDisksPerServer)
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize(clr, "OK "))
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize("Info", "OK "))
}
@@ -224,7 +174,7 @@ func (u clusterStruct) String() (msg string) {
// Summary on used space, total no of buckets and
// total no of objects at the Cluster level
usedTotal := humanize.IBytes(u.Info.Usage.Size)
usedTotal := humanize.IBytes(uint64(u.Info.Usage.Size))
if u.Info.Buckets.Count > 0 {
msg += fmt.Sprintf("%s Used, %s, %s\n", usedTotal,
english.Plural(int(u.Info.Buckets.Count), "Bucket", ""),
@@ -281,7 +231,7 @@ func mainAdminInfo(ctx *cli.Context) error {
clusterInfo.Error = ""
}
clusterInfo.Info = admInfo
printMsg(clusterInfo)
printMsg(clusterStruct(clusterInfo))
return nil
}
-175
View File
@@ -1,175 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/secure-io/sio-go"
)
var adminInspectFlags = []cli.Flag{
cli.BoolFlag{
Name: "encrypt",
Usage: "Encrypt content with one time key for confidential data",
},
}
var adminInspectCmd = cli.Command{
Name: "inspect",
Usage: "inspect files on MinIO server",
Action: mainAdminInspect,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminInspectFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
`,
}
func checkAdminInspectSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "inspect", 1) // last argument is exit code
}
}
// mainAdminHeal - the entry function of heal command
func mainAdminInspect(ctx *cli.Context) error {
// Check for command syntax
checkAdminInspectSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
encrypt := ctx.Bool("encrypt")
console.SetColor("File", color.New(color.FgWhite, color.Bold))
console.SetColor("Key", color.New(color.FgHiRed, color.Bold))
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
// Compute bucket and object from the aliased URL
aliasedURL = filepath.ToSlash(aliasedURL)
splits := splitStr(aliasedURL, "/", 3)
bucket, prefix := splits[1], splits[2]
key, r, ierr := client.Inspect(context.Background(), madmin.InspectOptions{Volume: bucket, File: prefix})
fatalIf(probe.NewError(ierr).Trace(aliasedURL), "Unable to inspect file.")
// Create profile zip file
tmpFile, e := ioutil.TempFile("", "mc-inspect-")
fatalIf(probe.NewError(e), "Unable to download file data.")
ext := "enc"
if !encrypt {
ext = "zip"
r = decryptInspect(key, r)
}
// Copy zip content to target download file
_, e = io.Copy(tmpFile, r)
fatalIf(probe.NewError(e), "Unable to download file data.")
// Close everything
r.Close()
tmpFile.Close()
// Create an id that is also crc.
var id [4]byte
binary.LittleEndian.PutUint32(id[:], crc32.ChecksumIEEE(key[:]))
// We use 4 bytes of the 32 bytes to identify they file.
downloadPath := fmt.Sprintf("inspect.%s.%s", hex.EncodeToString(id[:]), ext)
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
fatalIf(probe.NewError(e), "Unable to create a backup of "+downloadPath)
} else {
if !os.IsNotExist(e) {
fatal(probe.NewError(e), "Unable to download file data.")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to download file data.")
hexKey := hex.EncodeToString(id[:]) + hex.EncodeToString(key[:])
if !globalJSON {
if !encrypt {
console.Infof("File data successfully downloaded as %s\n", console.Colorize("File", downloadPath))
return nil
}
console.Infof("Encrypted file data successfully downloaded as %s\n", console.Colorize("File", downloadPath))
console.Infof("Decryption key: %s\n\n", console.Colorize("Key", hexKey))
console.Info("The decryption key will ONLY be shown here. It cannot be recovered.\n")
console.Info("The encrypted file can safely be shared without the decryption key.\n")
console.Info("Even with the decryption key, data stored with encryption cannot be accessed.\n")
return nil
}
v := struct {
File string `json:"file"`
Key string `json:"key,omitempty"`
}{
File: downloadPath,
Key: hexKey,
}
if !encrypt {
v.Key = ""
}
b, e := json.Marshal(v)
fatalIf(probe.NewError(e), "Unable to serialize data")
console.Println(string(b))
return nil
}
func decryptInspect(key [32]byte, r io.Reader) io.ReadCloser {
stream, err := sio.AES_256_GCM.Stream(key[:])
fatalIf(probe.NewError(err), "Unable to initiate decryption")
// Zero nonce, we only use each key once, and 32 bytes is plenty.
nonce := make([]byte, stream.NonceSize())
return ioutil.NopCloser(stream.DecryptReader(r, nonce, nil))
}
-70
View File
@@ -1,70 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"os"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
)
var adminKMSCreateKeyCmd = cli.Command{
Name: "create",
Usage: "creates a new master key at the KMS",
Action: mainAdminKMSCreateKey,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET [KEY_NAME]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Create a new master key named 'my-key' default master key.
$ {{.HelpName}} play my-key
`,
}
// adminKMSCreateKeyCmd is the handler for the "mc admin kms key create" command.
func mainAdminKMSCreateKey(ctx *cli.Context) error {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "create", 1) // last argument is exit code
}
client, err := newAdminClient(ctx.Args().Get(0))
fatalIf(err, "Cannot get a configured admin connection.")
keyID := ctx.Args().Get(1)
e := client.CreateKey(globalContext, keyID)
fatalIf(probe.NewError(e), "Failed to create master key")
if terminal.IsTerminal(int(os.Stdout.Fd())) {
console.Println(color.GreenString(fmt.Sprintf("Created master key `%s` successfully", keyID)))
}
return nil
}
+36 -62
View File
@@ -1,39 +1,35 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* 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"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminKMSKeyStatusCmd = cli.Command{
Name: "status",
Usage: "request status information for a KMS master key",
Action: mainAdminKMSKeyStatus,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "status",
Usage: "request status information for a KMS master key",
Action: mainAdminKMSKeyStatus,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -47,7 +43,7 @@ EXAMPLES:
1. Get default master key and its status from a MinIO server/cluster.
$ {{.HelpName}} play
2. Get the status of one particular master key from a MinIO server/cluster.
$ {{.HelpName}} play my-master-key
$ {{.HelpName}} play my-master-key
`,
}
@@ -57,11 +53,8 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
console.SetColor("StatusSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("StatusError", color.New(color.FgRed, color.Bold))
client, err := newAdminClient(ctx.Args().Get(0))
fatalIf(err, "Unable to get a configured admin connection.")
fatalIf(err, "Cannot get a configured admin connection.")
var keyID string
if len(ctx.Args()) == 2 {
@@ -70,48 +63,29 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
status, e := client.GetKeyStatus(globalContext, keyID)
fatalIf(probe.NewError(e), "Failed to get status information")
printMsg(kmsKeyStatusMsg{
KeyID: status.KeyID,
Encryption: status.EncryptionErr == "",
Decryption: status.DecryptionErr == "",
EncryptionErr: status.EncryptionErr,
DecryptionErr: status.DecryptionErr,
})
printMsg(kmsKeyStatusMsg(*status))
return nil
}
type kmsKeyStatusMsg struct {
KeyID string `json:"keyId"`
Encryption bool `json:"encryption"`
Decryption bool `json:"decryption"`
EncryptionErr string `json:"encryptionError,omitempty"`
DecryptionErr string `json:"decryptionError,omitempty"`
Status string `json:"status"`
}
func (s kmsKeyStatusMsg) JSON() string {
s.Status = "success"
if !s.Encryption && !s.Decryption {
s.Status = "error"
}
kmsBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(kmsBytes)
}
type kmsKeyStatusMsg madmin.KMSKeyStatus
func (s kmsKeyStatusMsg) String() string {
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
if s.Encryption {
msg += " - Encryption " + console.Colorize("StatusSuccess", "✔") + "\n"
if s.EncryptionErr == "" {
msg = fmt.Sprintf("%s %s", msg, "\t • Encryption ✔\n")
} else {
msg += fmt.Sprintf(" - Encryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.EncryptionErr)
return fmt.Sprintf("%s \t • Encryption failed: %s\n", msg, s.EncryptionErr)
}
if s.Decryption {
msg += " - Decryption " + console.Colorize("StatusSuccess", "✔") + "\n"
if s.DecryptionErr == "" {
msg = fmt.Sprintf("%s %s", msg, "\t • Decryption ✔\n")
} else {
msg += fmt.Sprintf(" - Decryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.DecryptionErr)
return fmt.Sprintf("%s \t • Decryption failed: %s\n", msg, s.DecryptionErr)
}
return msg
}
func (s kmsKeyStatusMsg) JSON() string {
const fmtStr = `{"key-id":"%s","encryption-error":"%s","decryption-error":"%s"}`
return fmt.Sprintf(fmtStr, s.KeyID, s.EncryptionErr, s.DecryptionErr)
}
+23 -28
View File
@@ -1,41 +1,36 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* 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 adminKMSKeySubcommands = []cli.Command{
adminKMSCreateKeyCmd,
adminKMSKeyStatusCmd,
}
var adminKMSKeyCmd = cli.Command{
Name: "key",
Usage: "manage KMS master keys: Request key status information",
Action: mainAdminKMSKey,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminKMSKeySubcommands,
Name: "key",
Usage: "Manage KMS master keys: Request key status information",
Action: mainAdminKMSKey,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyStatusCmd,
},
HideHelpCommand: true,
}
// mainAdminKMSKey is the handle for the "mc admin kms key" command.
func mainAdminKMSKey(ctx *cli.Context) error {
commandNotFound(ctx, adminKMSKeySubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+23 -27
View File
@@ -1,40 +1,36 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* 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 adminKMSSubcommands = []cli.Command{
adminKMSKeyCmd,
}
var adminKMSCmd = cli.Command{
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminKMSSubcommands,
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyCmd,
},
HideHelpCommand: true,
}
// mainAdminKMS is the handle for the "mc admin kms" command.
func mainAdminKMS(ctx *cli.Context) error {
commandNotFound(ctx, adminKMSSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+37 -44
View File
@@ -1,25 +1,26 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2016, 2017 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 adminFlags = []cli.Flag{}
var (
adminFlags = []cli.Flag{}
)
const (
// dot represents a list item, for eg. server status - online (green) or offline (red)
@@ -28,45 +29,37 @@ const (
check = "✔"
)
var adminCmdSubcommands = []cli.Command{
adminServiceCmd,
adminServerUpdateCmd,
adminInfoCmd,
adminInspectCmd,
adminUserCmd,
adminGroupCmd,
adminPolicyCmd,
adminReplicateCmd,
adminConfigCmd,
adminHealCmd,
adminProfileCmd,
adminTopCmd,
adminTraceCmd,
adminConsoleCmd,
adminPrometheusCmd,
adminKMSCmd,
adminHealthCmd(),
adminSubnetCmd,
adminBucketCmd,
adminTierCmd,
adminSpeedtestCmd,
}
var adminCmd = cli.Command{
Name: "admin",
Usage: "manage MinIO servers",
Action: mainAdmin,
Subcommands: adminCmdSubcommands,
HideHelpCommand: true,
Before: setGlobalsFromContext,
Flags: append(adminFlags, globalFlags...),
Subcommands: []cli.Command{
adminServiceCmd,
adminServerUpdateCmd,
adminInfoCmd,
adminUserCmd,
adminGroupCmd,
adminPolicyCmd,
adminConfigCmd,
adminHealCmd,
adminProfileCmd,
adminTopCmd,
adminTraceCmd,
adminConsoleCmd,
adminPrometheusCmd,
adminKMSCmd,
adminOBDCmd,
adminBucketCmd,
},
}
const dateTimeFormatFilename = "2006-01-02T15-04-05.999999-07-00"
// mainAdmin is the handle for "mc admin" command.
func mainAdmin(ctx *cli.Context) error {
commandNotFound(ctx, adminCmdSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "service", "heal", "top" have their own main.
}
+418
View File
@@ -0,0 +1,418 @@
/*
* 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 (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/fatih/color"
"github.com/klauspost/compress/gzip"
"github.com/minio/cli"
cjson "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 adminOBDFlags = []cli.Flag{
OBDDataTypeFlag{
Name: "tests",
Usage: "choose OBD tests to run [" + options.String() + "]",
Value: nil,
EnvVar: "MC_OBD_DATA",
Hidden: true,
},
cli.DurationFlag{
Name: "deadline",
Usage: "maximum duration that OBD tests should be allowed to run",
Value: 3600 * time.Second,
EnvVar: "MC_OBD_DEADLINE",
},
}
var adminOBDCmd = cli.Command{
Name: "obd",
Usage: "run on-board diagnostics",
Action: mainAdminOBD,
Before: initBeforeRunningCmd,
Flags: append(adminOBDFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server information of the 'play' MinIO server.
{{.Prompt}} {{.HelpName}} play/
`,
}
type clusterOBDStruct struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Info madmin.OBDInfo `json:"obdInfo,omitempty"`
}
func (u clusterOBDStruct) String() string {
u.Status = ""
data, err := json.Marshal(u)
if err != nil {
fatalIf(probe.NewError(err), "unable to marshal into JSON.")
}
return string(data)
}
// JSON jsonifies service status message.
func (u clusterOBDStruct) JSON() string {
statusJSONBytes, e := json.MarshalIndent(u, " ", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminInfoSyntax - validate arguments passed by a user
func checkAdminOBDSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "obd", 1) // last argument is exit code
}
}
//compress and tar obd output
func tarGZ(c clusterOBDStruct, alias string) error {
filename := fmt.Sprintf("%s-obd_%s.json.gz", filepath.Clean(alias), time.Now().Format("20060102150405"))
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return err
}
defer f.Close()
defer func() {
fmt.Println("OBD data saved to", filename)
}()
gzWriter := gzip.NewWriter(f)
defer gzWriter.Close()
enc := json.NewEncoder(gzWriter)
if err := enc.Encode(c); err != nil {
return err
}
warningMsgBoundary := "*********************************************************************************"
warning := warnText(" WARNING!!")
warningContents := infoText(` ** THIS FILE MAY CONTAIN SENSITIVE INFORMATION ABOUT YOUR ENVIRONMENT **
** PLEASE INSPECT CONTENTS BEFORE SHARING IT ON ANY PUBLIC FORUM **`)
warningMsgHeader := infoText(warningMsgBoundary)
warningMsgTrailer := infoText(warningMsgBoundary)
fmt.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
return nil
}
func infoText(s string) string {
console.SetColor("INFO", color.New(color.FgGreen, color.Bold))
return console.Colorize("INFO", s)
}
func greenText(s string) string {
console.SetColor("GREEN", color.New(color.FgGreen))
return console.Colorize("GREEN", s)
}
func warnText(s string) string {
console.SetColor("WARN", color.New(color.FgRed, color.Bold))
return console.Colorize("WARN", s)
}
func mainAdminOBD(ctx *cli.Context) error {
checkAdminOBDSyntax(ctx)
// 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.")
spinners := []string{"/", "|", "\\", "--", "|"}
cont, cancel := context.WithCancel(globalContext)
defer cancel()
startSpinner := func(s string) func() {
ctx, cancel := context.WithCancel(cont)
printText := func(t string, sp string, rewind int) {
console.RewindLines(rewind)
dot := infoText(dot)
t = fmt.Sprintf("%s ...", t)
t = greenText(t)
sp = infoText(sp)
toPrint := fmt.Sprintf("%s %s %s ", dot, t, sp)
fmt.Printf("%s\n", toPrint)
}
i := 0
sp := func() string {
i = i + 1
i = i % len(spinners)
return spinners[i]
}
done := make(chan bool)
doneToggle := false
go func() {
printText(s, sp(), 0)
for {
<-time.After(500 * time.Millisecond) //2 fps
if ctx.Err() != nil {
printText(s, check, 1)
done <- true
return
}
printText(s, sp(), 1)
}
}()
return func() {
cancel()
if !doneToggle {
<-done
os.Stdout.Sync()
doneToggle = true
}
}
}
spinner := func(resource string) func(bool) bool {
var spinStopper func()
done := false
if globalJSON {
return func(bool) bool {
return true
}
}
return func(cond bool) bool {
if done {
return done
}
if spinStopper == nil {
spinStopper = startSpinner(resource)
}
if cond {
spinStopper()
done = true
}
return done
}
}
clusterOBDInfo := clusterOBDStruct{}
admin := spinner("Admin Info")
cpu := spinner("CPU")
diskHw := spinner("Disk Hardware")
osInfo := spinner("Os Info")
mem := spinner("Mem Info")
process := spinner("Process Info")
config := spinner("Config")
drive := spinner("Drive")
net := spinner("Net")
progress := func(info madmin.OBDInfo) bool {
return admin(len(info.Minio.Info.Servers) > 0) &&
cpu(len(info.Sys.CPUInfo) > 0) &&
diskHw(len(info.Sys.DiskHwInfo) > 0) &&
osInfo(len(info.Sys.OsInfo) > 0) &&
mem(len(info.Sys.MemInfo) > 0) &&
process(len(info.Sys.ProcInfo) > 0) &&
config(info.Minio.Config != nil) &&
drive(len(info.Perf.DriveInfo) > 0) &&
net(len(info.Perf.Net) > 1)
}
// Fetch info of all servers (cluster or single server)
obdChan := client.ServerOBDInfo(cont, options, ctx.Duration("deadline"))
for adminOBDInfo := range obdChan {
if adminOBDInfo.Error != "" {
clusterOBDInfo.Status = "Error"
clusterOBDInfo.Error = adminOBDInfo.Error
clusterOBDInfo.Info.Error = ""
clusterOBDInfo.Info.Minio.Info = madmin.InfoMessage{}
break
}
clusterOBDInfo.Status = "Success"
clusterOBDInfo.Info = adminOBDInfo
progress(adminOBDInfo)
}
// If MinIO is not a global distXL cluster, net will never stop spinning.
// add this extra check to ensure that doesn't happen
if clusterOBDInfo.Error == "" && !progress(clusterOBDInfo.Info) {
net(true)
}
if globalJSON {
jsonBytes, err := cjson.MarshalIndent(clusterOBDInfo, "", " ")
if err != nil {
return err
}
fmt.Println(string(jsonBytes))
return nil
}
if clusterOBDInfo.Error != "" {
fmt.Println(warnText("Error obtaining obd information:"), clusterOBDInfo.Error)
return nil
}
return tarGZ(clusterOBDInfo, aliasedURL)
}
// OBDDataTypeSlice is a typed list of OBD tests
type OBDDataTypeSlice []madmin.OBDDataType
// Set - sets the flag to the given value
func (d *OBDDataTypeSlice) Set(value string) error {
for _, v := range strings.Split(value, ",") {
if obdData, ok := madmin.OBDDataTypesMap[strings.Trim(v, " ")]; ok {
*d = append(*d, obdData)
} else {
return fmt.Errorf("valid options include %s", options.String())
}
}
return nil
}
// String - returns the string representation of the OBD datatypes
func (d *OBDDataTypeSlice) String() string {
val := ""
for _, obdData := range *d {
formatStr := "%s"
if val != "" {
formatStr = fmt.Sprintf("%s,%%s", formatStr)
} else {
formatStr = fmt.Sprintf("%s%%s", formatStr)
}
val = fmt.Sprintf(formatStr, val, string(obdData))
}
return val
}
// Value - returns the value
func (d *OBDDataTypeSlice) Value() []madmin.OBDDataType {
return *d
}
// Get - returns the value
func (d *OBDDataTypeSlice) Get() interface{} {
return *d
}
// OBDDataTypeFlag is a typed flag to represent OBD datatypes
type OBDDataTypeFlag struct {
Name string
Usage string
EnvVar string
Hidden bool
Value *OBDDataTypeSlice
}
// String - returns the string to be shown in the help message
func (f OBDDataTypeFlag) String() string {
return fmt.Sprintf("--%s %s", f.Name, f.Usage)
}
// GetName - returns the name of the flag
func (f OBDDataTypeFlag) GetName() string {
return f.Name
}
// GetOBDDataTypeSlice - returns the list of set OBD tests
func GetOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
generic := c.Generic(name)
if generic == nil {
return nil
}
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
return obdData
}
return nil
}
// GetGlobalOBDDataTypeSlice - returns the list of set OBD tests set globally
func GetGlobalOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
generic := c.GlobalGeneric(name)
if generic == nil {
return nil
}
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
return obdData
}
return nil
}
// Apply - applies the flag
func (f OBDDataTypeFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError - applies with error
func (f OBDDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
newVal := &OBDDataTypeSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
if err := newVal.Set(s); err != nil {
return fmt.Errorf("could not parse %s as OBD datatype value for flag %s: %s", envVal, f.Name, err)
}
}
f.Value = newVal
break
}
}
}
for _, name := range strings.Split(f.Name, ",") {
name = strings.Trim(name, " ")
if f.Value == nil {
f.Value = &OBDDataTypeSlice{}
}
set.Var(f.Value, name, f.Usage)
}
return nil
}
var options = OBDDataTypeSlice(madmin.OBDDataTypesList)
+37 -46
View File
@@ -1,41 +1,40 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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 (
"bytes"
"fmt"
"io/ioutil"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
iampolicy "github.com/minio/minio/pkg/iam/policy"
)
var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -69,27 +68,16 @@ type userPolicyMessage struct {
op string
Status string `json:"status"`
Policy string `json:"policy,omitempty"`
PolicyInfo madmin.PolicyInfo `json:"policyInfo,omitempty"`
PolicyJSON *iampolicy.Policy `json:"policyJSON,omitempty"`
UserOrGroup string `json:"userOrGroup,omitempty"`
IsGroup bool `json:"isGroup"`
}
func (u userPolicyMessage) accountType() string {
switch u.op {
case "set", "unset", "update":
if u.IsGroup {
return "group"
}
return "user"
}
return ""
}
func (u userPolicyMessage) String() string {
switch u.op {
case "info":
buf, err := json.MarshalIndent(u.PolicyInfo, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
buf, e := json.MarshalIndent(u.PolicyJSON, "", " ")
fatalIf(probe.NewError(e), "Unable to parse policy")
return string(buf)
case "list":
policyFieldMaxLen := 20
@@ -101,14 +89,14 @@ func (u userPolicyMessage) String() string {
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
case "add":
return console.Colorize("PolicyMessage", "Added policy `"+u.Policy+"` successfully.")
case "set", "unset":
case "set":
fragment := "user"
if u.IsGroup {
fragment = "group"
}
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy `%s` is %s on %s `%s`", u.Policy, u.op, u.accountType(), u.UserOrGroup))
case "update":
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy `%s` is added to %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
fmt.Sprintf("Policy %s is set on %s `%s`", u.Policy, fragment, u.UserOrGroup))
}
return ""
}
@@ -137,7 +125,10 @@ func mainAdminPolicyAdd(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), policy)).Trace(args...), "Unable to add new policy")
iamp, e := iampolicy.ParseConfig(bytes.NewReader(policy))
fatalIf(probe.NewError(e).Trace(args...), "Unable to parse the input policy")
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), iamp)).Trace(args...), "Unable to add new policy")
printMsg(userPolicyMessage{
op: "add",
+35 -49
View File
@@ -1,37 +1,36 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminPolicyInfoCmd = cli.Command{
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -57,23 +56,6 @@ func checkAdminPolicyInfoSyntax(ctx *cli.Context) {
}
}
func getPolicyInfo(client *madmin.AdminClient, policyName string) (*madmin.PolicyInfo, error) {
pinfo, e := client.InfoCannedPolicyV2(globalContext, policyName)
if e != nil {
return nil, e
}
if pinfo.PolicyName == "" {
// Likely server only supports the older version.
pinfo.Policy, e = client.InfoCannedPolicy(globalContext, policyName)
if e != nil {
return nil, e
}
pinfo.PolicyName = policyName
}
return pinfo, nil
}
// mainAdminPolicyInfo is the handler for "mc admin policy info" command.
func mainAdminPolicyInfo(ctx *cli.Context) error {
checkAdminPolicyInfoSyntax(ctx)
@@ -90,14 +72,18 @@ func mainAdminPolicyInfo(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection")
pinfo, e := getPolicyInfo(client, policyName)
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch policy")
printMsg(userPolicyMessage{
op: "info",
Policy: policyName,
PolicyInfo: *pinfo,
})
policies, e := client.ListCannedPolicies(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
iamp, ok := policies[policyName]
if ok {
printMsg(userPolicyMessage{
op: "info",
Policy: policyName,
PolicyJSON: iamp,
})
} else {
fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Unable to display policy")
}
return nil
}
+22 -24
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018-2019 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
@@ -21,16 +20,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminPolicyListCmd = cli.Command{
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -69,7 +67,7 @@ func mainAdminPolicyList(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
policies, e := client.ListCannedPolicies(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to list policy")
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
for k := range policies {
printMsg(userPolicyMessage{
+22 -24
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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
@@ -21,16 +20,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -70,7 +68,7 @@ func mainAdminPolicyRemove(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Unable to remove policy")
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Cannot remove policy")
printMsg(userPolicyMessage{
op: "remove",
+31 -28
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -24,16 +23,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminPolicySetCmd = cli.Command{
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -55,7 +53,9 @@ EXAMPLES:
`,
}
var errBadUserGroupArg = errors.New("Last argument must be of the form user=xx or group=xx")
var (
errBadUserGroupArg = errors.New("Last argument must be of the form user=xx or group=xx")
)
func checkAdminPolicySetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
@@ -64,9 +64,11 @@ func checkAdminPolicySetSyntax(ctx *cli.Context) {
}
func parseEntityArg(arg string) (userOrGroup string, isGroup bool, err error) {
parts := strings.SplitN(arg, "=", 2)
parts := strings.Split(arg, "=")
switch {
case len(parts) != 2 || parts[1] == "":
case len(parts) != 2:
fallthrough
case parts[1] == "":
err = errBadUserGroupArg
case strings.ToLower(parts[0]) == "user":
userOrGroup = parts[1]
@@ -91,7 +93,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policyName := strings.TrimSpace(args.Get(1))
policyName := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
@@ -102,6 +104,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetPolicy(globalContext, policyName, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "set",
@@ -110,7 +113,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to set the policy")
fatalIf(probe.NewError(e), "Cannot set the policy")
}
return nil
}
-137
View File
@@ -1,137 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicyUnsetCmd = cli.Command{
Name: "unset",
Usage: "unset an IAM policy for a user or group",
Action: mainAdminPolicyUnset,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Unset the "diagnostics" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
2. Set the "diagnostics" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
`,
}
func checkAdminPolicyUnsetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "unset", 1) // last argument is exit code
}
}
func removeCannedPolicies(existingPolicies, policiesToRemove string) (string, error) {
policiesToRemove = strings.TrimSpace(policiesToRemove)
if policiesToRemove == "" {
return "", errors.New("empty policy name is not supported")
}
filteredPolicies := strings.Split(existingPolicies, ",")
for _, p1 := range strings.Split(policiesToRemove, ",") {
found := false
for i, p2 := range filteredPolicies {
if p1 == p2 {
found = true
filteredPolicies = append(filteredPolicies[:i], filteredPolicies[i+1:]...)
break
}
}
if !found {
return "", fmt.Errorf("policy `%s` not found", p1)
}
}
return strings.Join(filteredPolicies, ","), nil
}
// mainAdminPolicyUnset is the handler for "mc admin policy unset" command.
func mainAdminPolicyUnset(ctx *cli.Context) error {
checkAdminPolicyUnsetSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
console.SetColor("Policy", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policiesToUnset := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
var existingPolicies string
if !isGroup {
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
existingPolicies = userInfo.PolicyName
} else {
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
existingPolicies = groupInfo.Policy
}
newPolicies, e := removeCannedPolicies(existingPolicies, policiesToUnset)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to unset the policy")
}
e = client.SetPolicy(globalContext, newPolicies, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "unset",
Policy: policiesToUnset,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to unset the policy")
}
return nil
}
-142
View File
@@ -1,142 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicyUpdateCmd = cli.Command{
Name: "update",
Usage: "Attach new IAM policy to a user or group",
Action: mainAdminPolicyUpdate,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add the "diagnostics" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
2. add the "diagnostics" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
`,
}
func checkAdminPolicyUpdateSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "update", 1) // last argument is exit code
}
}
func updateCannedPolicies(existingPolicies, policiesToAdd string) (string, error) {
policiesToAdd = strings.TrimSpace(policiesToAdd)
if policiesToAdd == "" {
return "", errors.New("empty policy name is unsupported")
}
var updatedPolicies []string
if existingPolicies != "" {
updatedPolicies = strings.Split(existingPolicies, ",")
}
for _, p1 := range strings.Split(policiesToAdd, ",") {
found := false
p1 = strings.TrimSpace(p1)
for _, p2 := range updatedPolicies {
if p1 == p2 {
found = true
break
}
}
if found {
return "", fmt.Errorf("policy `%s` already exists", p1)
}
updatedPolicies = append(updatedPolicies, p1)
}
return strings.Join(updatedPolicies, ","), nil
}
// mainAdminPolicyUpdate is the handler for "mc admin policy update" command.
func mainAdminPolicyUpdate(ctx *cli.Context) error {
checkAdminPolicyUpdateSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
console.SetColor("Policy", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policiesToAdd := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
var existingPolicies string
if !isGroup {
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
existingPolicies = userInfo.PolicyName
} else {
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
existingPolicies = groupInfo.Policy
}
updatedPolicies, e := updateCannedPolicies(existingPolicies, policiesToAdd)
if err != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to update the policy")
}
e = client.SetPolicy(globalContext, updatedPolicies, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "update",
Policy: policiesToAdd,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to unset the policy")
}
return nil
}
+27 -33
View File
@@ -1,47 +1,41 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018-2019 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 adminPolicySubcommands = []cli.Command{
adminPolicyAddCmd,
adminPolicyRemoveCmd,
adminPolicyListCmd,
adminPolicyInfoCmd,
adminPolicySetCmd,
adminPolicyUnsetCmd,
adminPolicyUpdateCmd,
}
var adminPolicyCmd = cli.Command{
Name: "policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminPolicySubcommands,
Name: "policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Flags: globalFlags,
Subcommands: []cli.Command{
adminPolicyAddCmd,
adminPolicyRemoveCmd,
adminPolicyListCmd,
adminPolicyInfoCmd,
adminPolicySetCmd,
},
HideHelpCommand: true,
}
// mainAdminPolicy is the handle for "mc admin policy" command.
func mainAdminPolicy(ctx *cli.Context) error {
commandNotFound(ctx, adminPolicySubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "get", "set" have their own main.
}
+21 -23
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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
@@ -21,17 +20,17 @@ import (
"strings"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/set"
"github.com/minio/pkg/console"
"github.com/minio/minio-go/v6/pkg/set"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminProfileStartFlags = []cli.Flag{
cli.StringFlag{
Name: "type",
Usage: "start profiler type, possible values are 'cpu', 'mem', 'block', 'mutex', 'trace', 'threads' and 'goroutines'",
Value: "cpu,mem,block,goroutines",
Value: "cpu,mem,block",
},
}
@@ -39,8 +38,7 @@ var adminProfileStartCmd = cli.Command{
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminProfileStartFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -111,7 +109,7 @@ func mainAdminProfileStart(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
+18 -20
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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
@@ -25,15 +24,14 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminProfileStopCmd = cli.Command{
Name: "stop",
Usage: "stop and download profile data",
Action: mainAdminProfileStop,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -96,7 +94,7 @@ func mainAdminProfileStop(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
+24 -29
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018-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
@@ -21,24 +20,20 @@ import (
"github.com/minio/cli"
)
var adminProfileSubcommands = []cli.Command{
adminProfileStartCmd,
adminProfileStopCmd,
}
var adminProfileCmd = cli.Command{
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminProfileSubcommands,
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
Flags: globalFlags,
Subcommands: []cli.Command{
adminProfileStartCmd,
adminProfileStopCmd,
},
HideHelpCommand: true,
}
// mainAdminProfile is the handle for "mc admin profile" command.
func mainAdminProfile(ctx *cli.Context) error {
commandNotFound(ctx, adminProfileSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+37 -47
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -25,32 +24,24 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
jwtgo "github.com/golang-jwt/jwt"
json "github.com/minio/colorjson"
jwtgo "github.com/dgrijalva/jwt-go"
json "github.com/minio/mc/pkg/colorjson"
yaml "gopkg.in/yaml.v2"
)
const (
defaultJobName = "minio-job"
defaultMetricsPath = "/minio/v2/metrics/cluster"
defaultMetricsPath = "/minio/prometheus/metrics"
)
var prometheusFlags = []cli.Flag{
cli.BoolFlag{
Name: "public",
Usage: "disable bearer token generation for scrape_configs",
},
}
var adminPrometheusGenerateCmd = cli.Command{
Name: "generate",
Usage: "generates prometheus config",
Action: mainAdminPrometheusGenerate,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(prometheusFlags, globalFlags...),
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -113,7 +104,7 @@ func (t StatConfig) JSON() string {
// ScrapeConfig configures a scraping unit for Prometheus.
type ScrapeConfig struct {
JobName string `yaml:"job_name" json:"jobName"`
BearerToken string `yaml:"bearer_token,omitempty" json:"bearerToken,omitempty"`
BearerToken string `yaml:"bearer_token" json:"bearerToken"`
MetricsPath string `yaml:"metrics_path,omitempty" json:"metricsPath"`
Scheme string `yaml:"scheme,omitempty" json:"scheme"`
StaticConfigs []StatConfig `yaml:"static_configs,omitempty" json:"staticConfigs"`
@@ -159,26 +150,24 @@ func generatePrometheusConfig(ctx *cli.Context) error {
return nil
}
u, e := url.Parse(hostConfig.URL)
if e != nil {
return e
u, err := url.Parse(hostConfig.URL)
if err != nil {
return err
}
if !ctx.Bool("public") {
jwt := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.StandardClaims{
ExpiresAt: UTCNow().Add(defaultPrometheusJWTExpiry).Unix(),
Subject: hostConfig.AccessKey,
Issuer: "prometheus",
})
jwt := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.StandardClaims{
ExpiresAt: UTCNow().Add(defaultPrometheusJWTExpiry).Unix(),
Subject: hostConfig.AccessKey,
Issuer: "prometheus",
})
token, e := jwt.SignedString([]byte(hostConfig.SecretKey))
if e != nil {
return e
}
// Setting the values
defaultConfig.ScrapeConfigs[0].BearerToken = token
token, err := jwt.SignedString([]byte(hostConfig.SecretKey))
if err != nil {
return err
}
// Setting the values
defaultConfig.ScrapeConfigs[0].BearerToken = token
defaultConfig.ScrapeConfigs[0].Scheme = u.Scheme
defaultConfig.ScrapeConfigs[0].StaticConfigs[0].Targets[0] = u.Host
@@ -189,6 +178,7 @@ func generatePrometheusConfig(ctx *cli.Context) error {
// mainAdminPrometheus is the handle for "mc admin prometheus generate" sub-command.
func mainAdminPrometheusGenerate(ctx *cli.Context) error {
console.SetColor("yaml", color.New(color.FgGreen))
checkAdminPrometheusSyntax(ctx)
+19 -23
View File
@@ -1,36 +1,32 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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 adminPrometheusSubcommands = []cli.Command{
adminPrometheusGenerateCmd,
}
var adminPrometheusCmd = cli.Command{
Name: "prometheus",
Usage: "manages prometheus config",
Action: mainAdminPrometheus,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: adminPrometheusSubcommands,
Subcommands: []cli.Command{
adminPrometheusGenerateCmd,
},
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -45,6 +41,6 @@ FLAGS:
// mainAdminPrometheus is the handle for "mc admin prometheus" command.
func mainAdminPrometheus(ctx *cli.Context) error {
commandNotFound(ctx, adminPrometheusSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
-115
View File
@@ -1,115 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateAddCmd = cli.Command{
Name: "add",
Usage: "add one or more sites for replication",
Action: mainAdminReplicateAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS1 ALIAS2 [ALIAS3...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add a site for cluster-level replication:
{{.Prompt}} {{.HelpName}} minio1 minio2
`,
}
type successMessage madmin.ReplicateAddStatus
func (m successMessage) JSON() string {
bs, e := json.MarshalIndent(madmin.ReplicateAddStatus(m), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (m successMessage) String() string {
v := madmin.ReplicateAddStatus(m)
messages := []string{v.Status}
if v.ErrDetail != "" {
messages = append(messages, v.ErrDetail)
}
if v.InitialSyncErrorMessage != "" {
messages = append(messages, v.InitialSyncErrorMessage)
}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
func mainAdminReplicateAdd(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr < 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need at least two arguments to add command.")
}
}
console.SetColor("UserMessage", color.New(color.FgGreen))
// 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.")
ps := make([]madmin.PeerSite, 0, len(ctx.Args()))
for _, clusterName := range ctx.Args() {
admClient, err := newAdminClient(clusterName)
fatalIf(err, "unable to initialize admin connection")
ak, sk := admClient.GetAccessAndSecretKey()
ps = append(ps, madmin.PeerSite{
Name: clusterName,
Endpoint: admClient.GetEndpointURL().String(),
AccessKey: ak,
SecretKey: sk,
})
}
res, e := client.SiteReplicationAdd(globalContext, ps)
fatalIf(probe.NewError(e).Trace(args...), "Unable to add sites for replication")
printMsg(successMessage(res))
return nil
}
-108
View File
@@ -1,108 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateInfoCmd = cli.Command{
Name: "info",
Usage: "get site replication information",
Action: mainAdminReplicationInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS1
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get Site Replication information:
{{.Prompt}} {{.HelpName}} minio1
`,
}
type srInfo madmin.SiteReplicationInfo
func (i srInfo) JSON() string {
bs, e := json.MarshalIndent(madmin.SiteReplicationInfo(i), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i srInfo) String() string {
var messages []string
info := madmin.SiteReplicationInfo(i)
if info.Enabled {
messages = []string{
"SiteReplication: on",
fmt.Sprintf("ServiceAccountAccessKey: %s", info.ServiceAccountAccessKey),
"SiteReplicationMembers:",
}
for _, peer := range info.Sites {
messages = append(messages, fmt.Sprintf(" Name: %s, Endpoint: %s, DeploymentID: %s", peer.Name, peer.Endpoint, peer.DeploymentID))
}
} else {
messages = []string{"SiteReplication: off"}
}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
func mainAdminReplicationInfo(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need exactly one alias argument.")
}
}
console.SetColor("UserMessage", color.New(color.FgGreen))
// 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.")
info, e := client.SiteReplicationInfo(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get cluster replication information")
printMsg(srInfo(info))
return nil
}
-274
View File
@@ -1,274 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"sort"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateStatusCmd = cli.Command{
Name: "status",
Usage: "display site replication status",
Action: mainAdminReplicationStatus,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display Site Replication status:
{{.Prompt}} {{.HelpName}} minio1
`,
}
type srStatus madmin.SRStatusInfo
func (i srStatus) JSON() string {
bs, e := json.MarshalIndent(madmin.SRStatusInfo(i), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i srStatus) String() string {
var messages []string
// Color palette initialization
console.SetColor("Summary", color.New(color.FgWhite, color.Bold))
console.SetColor("SummaryHdr", color.New(color.FgCyan, color.Bold))
console.SetColor("SummaryDtl", color.New(color.FgGreen, color.Bold))
coloredDot := console.Colorize("Status", dot)
info := madmin.SRStatusInfo(i)
if !info.Enabled {
messages = []string{"SiteReplication: off"}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
messages = append(messages, console.Colorize("SummaryHdr", "Sites:"))
for _, peer := range info.Sites {
messages = append(messages, console.Colorize("SummaryDtl", fmt.Sprintf("Name: %s, Endpoint: %s, DeploymentID: %s", peer.Name, peer.Endpoint, peer.DeploymentID)))
}
messages = append(messages, console.Colorize("Summary", fmt.Sprintf("Unique entries across sites: %d Buckets, %d Policies, %d Users, %d Groups", info.MaxBuckets, info.MaxPolicies, info.MaxUsers, info.MaxGroups))+"\n")
nameIDMap := make(map[string]string)
var siteNames []string
for dID := range info.StatsSummary {
sname := strings.ToTitle(info.Sites[dID].Name)
siteNames = append(siteNames, sname)
nameIDMap[sname] = dID
}
sort.Strings(siteNames)
rowLegend := []string{"Buckets", "Policies", "Users", "Groups"}
legendHdr := []string{"Site"}
legendFields := []Field{{"Entity", 15}}
detailFields := make([][]Field, len(rowLegend))
for _, sname := range siteNames {
legendHdr = append(legendHdr, sname)
legendFields = append(legendFields, Field{"sname", 15})
}
messages = append(messages,
console.Colorize("SummaryHdr", fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("Summary", "Site replication status"))))
siteHdr := console.Colorize("SummaryHdr", newPrettyTable(" | ",
legendFields...,
).buildRow(legendHdr...))
messages = append(messages, siteHdr)
var buckets, policies, users, groups []string
for i, row := range rowLegend {
detailFields[i] = make([]Field, len(siteNames)+1)
detailFields[i][0] = Field{"Entity", 15}
switch i {
case 0:
buckets = append(buckets, row)
case 1:
policies = append(policies, row)
case 2:
users = append(users, row)
default:
groups = append(groups, row)
}
}
rows := make([]string, 4)
fieldLen := 15
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := info.StatsSummary[dID]
var theme, msgStr string
for i := range rowLegend {
switch i {
case 0:
theme, msgStr = colorizedStatus(ss.ReplicatedBuckets, ss.TotalBucketsCount)
buckets = append(buckets, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
case 1:
theme, msgStr = colorizedStatus(ss.ReplicatedIAMPolicies, ss.TotalIAMPoliciesCount)
policies = append(policies, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
case 2:
theme, msgStr = colorizedStatus(ss.ReplicatedUsers, ss.TotalUsersCount)
users = append(users, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
case 3:
theme, msgStr = colorizedStatus(ss.ReplicatedGroups, ss.TotalGroupsCount)
groups = append(groups, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
}
}
}
for i := range rowLegend {
switch i {
case 0:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(buckets...)
case 1:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(policies...)
case 2:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(users...)
case 3:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(groups...)
}
}
messages = append(messages, rows...)
messages = append(messages, "\n")
messages = append(messages,
console.Colorize("SummaryHdr", fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("Summary", "Bucket metadata replication Summary"))))
messages = append(messages, siteHdr)
rowLegend = []string{"Retention", "Encryption", "Tags", "Policy"}
detailFields = make([][]Field, len(rowLegend))
var retention, encryption, tags, bpolicies []string
for i, row := range rowLegend {
detailFields[i] = make([]Field, len(siteNames)+1)
detailFields[i][0] = Field{"Entity", 15}
switch i {
case 0:
retention = append(retention, row)
case 1:
encryption = append(encryption, row)
case 2:
tags = append(tags, row)
default:
bpolicies = append(bpolicies, row)
}
}
rows = make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := info.StatsSummary[dID]
var theme, msgStr string
for i := range rowLegend {
switch i {
case 0:
theme, msgStr = colorizedStatus(ss.ReplicatedLockConfig, ss.TotalLockConfigCount)
retention = append(retention, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
case 1:
theme, msgStr = colorizedStatus(ss.ReplicatedSSEConfig, ss.TotalSSEConfigCount)
encryption = append(encryption, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
case 2:
theme, msgStr = colorizedStatus(ss.ReplicatedTags, ss.TotalTagsCount)
tags = append(tags, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
case 3:
theme, msgStr = colorizedStatus(ss.ReplicatedBucketPolicies, ss.TotalBucketPoliciesCount)
bpolicies = append(bpolicies, msgStr)
detailFields[i][j+1] = Field{theme, fieldLen}
}
}
}
for i := range rowLegend {
switch i {
case 0:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(retention...)
case 1:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(encryption...)
case 2:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(tags...)
case 3:
rows[i] = newPrettyTable(" | ",
detailFields[i]...).buildRow(bpolicies...)
}
}
messages = append(messages, rows...)
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
func mainAdminReplicationStatus(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need exactly one alias argument.")
}
}
console.SetColor("UserMessage", color.New(color.FgGreen))
// 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.")
info, e := client.SRStatusInfo(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get cluster replication information")
printMsg(srStatus(info))
return nil
}
// returns theme and colorized status text
func colorizedStatus(cnt, total int) (string, string) {
if cnt == total && cnt == 0 {
return "Entity", ""
}
status := fmt.Sprintf("%d/%d OK", cnt, total)
return "Entity", fmt.Sprintf("%-15s", status)
}
-42
View File
@@ -1,42 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminReplicateSubcommands = []cli.Command{
adminReplicateAddCmd,
// adminReplicateDisableCmd,
adminReplicateInfoCmd,
adminReplicateStatusCmd,
}
var adminReplicateCmd = cli.Command{
Name: "replicate",
Usage: "manage MinIO site replication",
Action: mainAdminReplicate,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminReplicateSubcommands,
HideHelpCommand: true,
}
func mainAdminReplicate(ctx *cli.Context) error {
commandNotFound(ctx, adminReplicateSubcommands)
return nil
}
+40 -64
View File
@@ -1,41 +1,37 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2016 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 (
"context"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "restart",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -59,7 +55,7 @@ type serviceRestartCommand struct {
// String colorized service restart command message.
func (s serviceRestartCommand) String() string {
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`. Type Ctrl-C to quit or wait to follow the status of the restart process.")
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`.")
}
// JSON jsonified service restart command message.
@@ -80,7 +76,7 @@ type serviceRestartMessage struct {
// String colorized service restart message.
func (s serviceRestartMessage) String() string {
if s.Err == nil {
return console.Colorize("ServiceRestart", "\nRestarted `"+s.ServerURL+"` successfully.")
return console.Colorize("ServiceRestart", "Restarted `"+s.ServerURL+"` successfully.")
}
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
}
@@ -95,18 +91,17 @@ func (s serviceRestartMessage) JSON() string {
// checkAdminServiceRestartSyntax - validate all the passed arguments
func checkAdminServiceRestartSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "restart", 1) // last argument is exit code
}
}
func mainAdminServiceRestart(ctx *cli.Context) error {
// Validate serivce restart syntax.
checkAdminServiceRestartSyntax(ctx)
// Set color.
console.SetColor("ServiceOffline", color.New(color.FgRed, color.Bold))
console.SetColor("ServiceInitializing", color.New(color.FgYellow, color.Bold))
console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold))
console.SetColor("FailedServiceRestart", color.New(color.FgRed, color.Bold))
@@ -118,44 +113,25 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Restart the specified MinIO server
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Unable to restart the server.")
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Cannot restart the server.")
// Success..
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
coloring := color.New(color.FgRed)
mark := "..."
// Max. time taken by the server to shutdown is 5 seconds.
// This can happen when there are lot of s3 requests pending when the server
// receives a restart command.
// Sleep for 6 seconds and then check if the server is online.
time.Sleep(6 * time.Second)
// Print restart progress
printProgress := func() {
if !globalQuiet && !globalJSON {
coloring.Printf(mark)
}
// Fetch the service status of the specified MinIO server
_, e := client.ServerInfo(globalContext)
if e != nil {
printMsg(serviceRestartMessage{Status: "failure", Err: e, ServerURL: aliasedURL})
} else {
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
}
printProgress()
mark = "."
for {
select {
case <-globalContext.Done():
return globalContext.Err()
case <-time.NewTimer(3 * time.Second).C:
ctx, cancel := context.WithTimeout(globalContext, 1*time.Second)
// Fetch the service status of the specified MinIO server
info, e := client.ServerInfo(ctx)
cancel()
switch {
case e == nil && info.Mode == string(madmin.ItemOnline):
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
return nil
case err == nil && info.Mode == string(madmin.ItemInitializing):
coloring = color.New(color.FgYellow)
mark = "!"
fallthrough
default:
printProgress()
}
}
}
return nil
}
+23 -24
View File
@@ -1,37 +1,35 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018-2019 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/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -74,6 +72,7 @@ func checkAdminServiceStopSyntax(ctx *cli.Context) {
}
func mainAdminServiceStop(ctx *cli.Context) error {
// Validate serivce stop syntax.
checkAdminServiceStopSyntax(ctx)
+20 -24
View File
@@ -1,42 +1,38 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2016, 2017, 2018 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 adminServiceSubcommands = []cli.Command{
adminServiceRestartCmd,
adminServiceStopCmd,
}
var adminServiceCmd = cli.Command{
Name: "service",
Usage: "restart and stop all MinIO servers",
Action: mainAdminService,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: adminServiceSubcommands,
Subcommands: []cli.Command{
adminServiceRestartCmd,
adminServiceStopCmd,
},
}
// mainAdmin is the handle for "mc admin service" command.
func mainAdminService(ctx *cli.Context) error {
commandNotFound(ctx, adminServiceSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "status", "restart" have their own main.
}
-251
View File
@@ -1,251 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"time"
"github.com/briandowns/spinner"
humanize "github.com/dustin/go-humanize"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
)
var adminSpeedtestFlags = []cli.Flag{
cli.StringFlag{
Name: "duration",
Usage: "duration the entire speedtests are run",
Value: "10s",
},
cli.StringFlag{
Name: "size",
Usage: "size of the object used for uploads/downloads",
Value: "64MiB",
},
cli.IntFlag{
Name: "concurrent",
Usage: "number of concurrent requests per server",
Value: 32,
},
cli.BoolFlag{
Name: "verbose, v",
Usage: "Show per-server stats",
},
}
var adminSpeedtestCmd = cli.Command{
Name: "speedtest",
Usage: "Run server side speed test",
Action: mainAdminSpeedtest,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminSpeedtestFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Run speedtest with autotuning the concurrency to figure out the maximum throughput and iops values:
{{.Prompt}} {{.HelpName}} myminio/
2. Run speedtest for 20 seconds with object size of 128MiB, 32 concurrent requests per server:
{{.Prompt}} {{.HelpName}} myminio/ --duration 20s --size 128MiB --concurrent 32
`,
}
type speedTestResult madmin.SpeedTestResult
func (s speedTestResult) String() (msg string) {
msg += fmt.Sprintf("\nMinIO %s, %d servers, %d drives\n", s.Version, s.Servers, s.Disks)
var errorReturned bool
for _, node := range s.PUTStats.Servers {
if node.Err != "" {
errorReturned = true
break
}
}
for _, node := range s.GETStats.Servers {
if node.Err != "" {
errorReturned = true
break
}
}
// When no error is found and yet without results, this means the speedtest duration is too short
if !errorReturned && (s.PUTStats.ThroughputPerSec == 0 || s.GETStats.ThroughputPerSec == 0) {
msg += "\n"
msg += "No results found for this speedtest iteration. Try increasing --duration flag."
msg += "\n"
return
}
msg += fmt.Sprintf("PUT: %s/s, %s objs/s\n", humanize.IBytes(s.PUTStats.ThroughputPerSec), humanize.Comma(int64(s.PUTStats.ObjectsPerSec)))
if globalSpeedTestVerbose {
for _, node := range s.PUTStats.Servers {
msg += fmt.Sprintf(" * %s: %s/s %s objs/s", node.Endpoint, humanize.IBytes(node.ThroughputPerSec), humanize.Comma(int64(node.ObjectsPerSec)))
if node.Err != "" {
msg += " error: " + node.Err
}
msg += "\n"
}
}
if globalSpeedTestVerbose {
msg += "\n"
}
msg += fmt.Sprintf("GET: %s/s, %s objs/s\n", humanize.IBytes(s.GETStats.ThroughputPerSec), humanize.Comma(int64(s.GETStats.ObjectsPerSec)))
if globalSpeedTestVerbose {
for _, node := range s.GETStats.Servers {
msg += fmt.Sprintf(" * %s: %s/s %s objs/s", node.Endpoint, humanize.IBytes(node.ThroughputPerSec), humanize.Comma(int64(node.ObjectsPerSec)))
if node.Err != "" {
msg += " error: " + node.Err
}
msg += "\n"
}
}
return msg
}
func (s speedTestResult) JSON() string {
JSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(JSONBytes)
}
var globalSpeedTestVerbose bool
func mainAdminSpeedtest(ctx *cli.Context) error {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "speedtest", 1) // last argument is exit code
}
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
client, perr := newAdminClient(aliasedURL)
if perr != nil {
fatalIf(perr.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
duration, e := time.ParseDuration(ctx.String("duration"))
if e != nil {
fatalIf(probe.NewError(e), "Unable to parse duration")
return nil
}
if duration <= 0 {
fatalIf(errInvalidArgument(), "duration cannot be 0 or negative")
return nil
}
size, e := humanize.ParseBytes(ctx.String("size"))
if e != nil {
fatalIf(probe.NewError(e), "Unable to parse object size")
return nil
}
if size < 0 {
fatalIf(errInvalidArgument(), "size is expected to be atleast 0 bytes")
return nil
}
concurrent := ctx.Int("concurrent")
if concurrent <= 0 {
fatalIf(errInvalidArgument(), "concurrency cannot be '0' or negative")
return nil
}
globalSpeedTestVerbose = ctx.Bool("verbose")
// Turn-off autotuning only when "concurrent" is specified
// in all other scenarios keep auto-tuning on.
autotune := !ctx.IsSet("concurrent")
resultCh, err := client.Speedtest(ctxt, madmin.SpeedtestOpts{
Size: int(size),
Duration: duration,
Concurrency: concurrent,
Autotune: autotune,
})
fatalIf(probe.NewError(err), "Failed to execute speedtest")
spinnerCh, s := startSpinner()
var result madmin.SpeedTestResult
for result = range resultCh {
select {
case spinnerCh <- struct{}{}:
default:
}
if result.Version == "" {
continue
}
if !globalJSON {
s.Stop()
close(spinnerCh)
fmt.Printf("(With %s object size, %d concurrency) PUT: %s/s GET: %s/s\n", humanize.IBytes(uint64(result.Size)), result.Concurrent, humanize.IBytes(result.PUTStats.ThroughputPerSec), humanize.IBytes(result.GETStats.ThroughputPerSec))
spinnerCh, s = startSpinner()
}
}
if result.Version != "" {
s.Stop()
close(spinnerCh)
printMsg(speedTestResult(result))
}
return nil
}
func startSpinner() (chan struct{}, *spinner.Spinner) {
ch := make(chan struct{}, 1)
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
firstTimeDelay := true
go func() {
for {
if !globalJSON {
s.Suffix = " Running speedtest"
if firstTimeDelay {
// First time delay is a work around for the case where after the last server response
// we don't endup printing a redundant "Running speedtest" line. Because of the sleep here
// the program would have printed results and exited.
time.Sleep(100 * time.Millisecond)
firstTimeDelay = false
}
_, ok := <-ch
if !ok {
return
}
s.Start()
time.Sleep(500 * time.Millisecond)
s.Stop()
}
}
}()
return ch, s
}
-671
View File
@@ -1,671 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
gojson "encoding/json"
"errors"
"flag"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/fatih/color"
"github.com/klauspost/compress/gzip"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/tidwall/gjson"
)
var adminHealthFlags = append([]cli.Flag{
HealthDataTypeFlag{
Name: "test",
Usage: "choose specific health report(s) to run [" + fullOptions.String() + "]",
Value: nil,
EnvVar: "MC_HEALTH_TEST,MC_OBD_TEST",
Hidden: true,
},
cli.DurationFlag{
Name: "deadline",
Usage: "maximum duration MinIO health report should be allowed to run",
Value: 1 * time.Hour,
Hidden: true,
EnvVar: "MC_HEALTH_DEADLINE,MC_OBD_DEADLINE",
},
cli.StringFlag{
Name: "license",
Usage: "SUBNET license key",
Hidden: true, // deprecated dec 2021
},
cli.IntFlag{
Name: "schedule",
Usage: "schedule automatic upload of MinIO health report(s) to SUBNET based on number of days (e.g. --schedule 2 is every 2 days)",
Value: 0,
},
cli.BoolFlag{
Name: "full",
Usage: "include long running health report(s) (takes longer to generate the report)",
Hidden: false,
},
}, subnetCommonFlags...)
var adminSubnetHealthCmd = cli.Command{
Name: "health",
Usage: "generate MinIO health report for SUBNET",
OnUsageError: onUsageError,
Action: mainSubnetHealth,
Before: setGlobalsFromContext,
Flags: append(adminHealthFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Upload MinIO health report for 'play' (https://play.min.io by default) to SUBNET
{{.Prompt}} {{.HelpName}} play
2. Upload MinIO health report for alias 'play' (https://play.min.io by default) to SUBNET proxying via https://192.168.1.3:3128
{{.Prompt}} {{.HelpName}} play --subnet-proxy https://192.168.1.3:3128
3. Schedule periodic upload of MinIO health report for alias 'play' (https://play.min.io by default) to SUBNET every 2 days
{{.Prompt}} {{.HelpName}} play --schedule 2
4. Generate MinIO health report for alias 'play' (https://play.min.io by default) save and upload to SUBNET manually
{{.Prompt}} {{.HelpName}} play --airgap
`,
}
// checkAdminHealthSyntax - validate arguments passed by a user
func checkAdminHealthSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "health", 1) // last argument is exit code
}
}
// compress and tar MinIO health output
func tarGZ(healthInfo interface{}, version string, filename string, showMessages bool) error {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0o666)
if err != nil {
return err
}
defer f.Close()
gzWriter := gzip.NewWriter(f)
defer gzWriter.Close()
enc := gojson.NewEncoder(gzWriter)
header := struct {
Version string `json:"version"`
}{Version: version}
if err := enc.Encode(header); err != nil {
return err
}
if err := enc.Encode(healthInfo); err != nil {
return err
}
if showMessages {
warningMsgBoundary := "*********************************************************************************"
warning := warnText(" WARNING!!")
warningContents := infoText(` ** THIS FILE MAY CONTAIN SENSITIVE INFORMATION ABOUT YOUR ENVIRONMENT **
** PLEASE INSPECT CONTENTS BEFORE SHARING IT ON ANY PUBLIC FORUM **`)
warningMsgHeader := infoText(warningMsgBoundary)
warningMsgTrailer := infoText(warningMsgBoundary)
console.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
console.Infoln("MinIO health report saved at", filename)
}
return nil
}
func infoText(s string) string {
console.SetColor("INFO", color.New(color.FgGreen, color.Bold))
return console.Colorize("INFO", s)
}
func greenText(s string) string {
console.SetColor("GREEN", color.New(color.FgGreen))
return console.Colorize("GREEN", s)
}
func warnText(s string) string {
console.SetColor("WARN", color.New(color.FgRed, color.Bold))
return console.Colorize("WARN", s)
}
func mainSubnetHealth(ctx *cli.Context) error {
checkAdminHealthSyntax(ctx)
// Get the alias parameter from cli
aliasedURL := ctx.Args().Get(0)
alias, _ := url2Alias(aliasedURL)
license, schedule, name, offline := fetchSubnetUploadFlags(ctx)
// license should be provided for us to reach subnet
// if `--offline` is provided do not need to reach out.
uploadToSubnet := !offline
if uploadToSubnet {
fatalIf(checkURLReachable(subnetBaseURL()).Trace(aliasedURL), "Unable to reach %s to upload MinIO health report, please use --airgap to upload manually", subnetBaseURL())
}
uploadPeriodically := schedule != 0
e := validateFlags(uploadToSubnet, uploadPeriodically, name)
fatalIf(probe.NewError(e), "unable to parse input values")
// Create a new MinIO Admin Client
client := getClient(aliasedURL)
if len(name) == 0 {
name = alias
}
// Main execution
execAdminHealth(ctx, client, alias, license, name, uploadToSubnet)
if uploadToSubnet && uploadPeriodically {
// Periodic upload to subnet
for {
sleepDuration := time.Hour * 24 * time.Duration(schedule)
console.Infoln("Waiting for", sleepDuration, "before running health diagnostics again.")
time.Sleep(sleepDuration)
execAdminHealth(ctx, client, alias, license, name, uploadToSubnet)
}
}
return nil
}
func fetchSubnetUploadFlags(ctx *cli.Context) (string, int, string, bool) {
// license info to upload to subnet.
license := ctx.String("license")
// non-zero schedule means that health diagnostics
// are to be run periodically and uploaded to subnet
schedule := ctx.Int("schedule")
// If set (along with --license), this will be passed to
// subnet as the name of the cluster
name := ctx.String("name")
// If set, the MinIO health file will not be uploaded
// to subnet and will only be saved locally.
offline := ctx.Bool("airgap") || ctx.Bool("offline")
return license, schedule, name, offline
}
func validateFlags(uploadToSubnet bool, uploadPeriodically bool, name string) error {
if uploadToSubnet {
if globalJSON {
return errors.New("--json and --license should not be passed together")
}
return nil
}
if globalDevMode {
return errors.New("--dev is not applicable in airgap mode")
}
if uploadPeriodically {
return errors.New("--schedule is applicable only when --license is also passed")
}
if len(name) > 0 {
return errors.New("--name is applicable only when --license is also passed")
}
return nil
}
func execAdminHealth(ctx *cli.Context, client *madmin.AdminClient, alias string, license string, clusterName string, uploadToSubnet bool) {
var reqURL string
var headers map[string]string
filename := fmt.Sprintf("%s-health_%s.json.gz", filepath.Clean(alias), UTCNow().Format("20060102150405"))
if uploadToSubnet {
// Retrieve subnet credentials (login/license) beforehand as
// it can take a long time to fetch the health information
reqURL, headers = prepareHealthUploadURL(alias, clusterName, filename, license)
}
healthInfo, version, e := fetchServerHealthInfo(ctx, client)
fatalIf(probe.NewError(e), "Unable to fetch health information.")
if globalJSON {
switch version {
case madmin.HealthInfoVersion0:
printMsg(healthInfo.(madmin.HealthInfoV0))
case madmin.HealthInfoVersion:
printMsg(healthInfo.(madmin.HealthInfo))
}
return
}
e = tarGZ(healthInfo, version, filename, !uploadToSubnet)
fatalIf(probe.NewError(e), "Unable to save MinIO health report")
if uploadToSubnet {
e = uploadHealthReport(alias, filename, reqURL, headers)
fatalIf(probe.NewError(e), "Unable to upload MinIO health report to SUBNET portal")
}
}
func prepareHealthUploadURL(alias string, clusterName string, filename string, license string) (string, map[string]string) {
if len(clusterName) == 0 {
clusterName = alias
}
apiKey := ""
if len(license) == 0 {
apiKey = getSubnetAPIKeyFromConfig(alias)
if len(apiKey) == 0 {
license = getSubnetLicenseFromConfig(alias)
}
}
uploadURL := subnetHealthUploadURL()
reqURL, headers, e := subnetURLWithAuth(uploadURL, apiKey, license)
fatalIf(probe.NewError(e).Trace(uploadURL), "Unable to fetch SUBNET authentication")
reqURL = fmt.Sprintf("%s&clustername=%s&filename=%s", reqURL, clusterName, filename)
return reqURL, headers
}
func uploadHealthReport(alias string, filename string, reqURL string, headers map[string]string) error {
req, e := subnetUploadReq(reqURL, filename)
if e != nil {
return e
}
resp, e := subnetReqDo(req, headers)
if e != nil {
return e
}
extractAndSaveAPIKey(alias, resp)
// Delete the report after successful upload
os.Remove(filename)
msg := "MinIO health report was successfully uploaded to SUBNET."
clusterURL, _ := url.PathUnescape(gjson.Get(resp, "cluster_url").String())
if len(clusterURL) > 0 {
msg += fmt.Sprintf(" Please click here to view our analysis: %s", clusterURL)
}
console.Infoln(msg)
return nil
}
func subnetUploadReq(url string, filename string) (*http.Request, error) {
file, e := os.Open(filename)
if e != nil {
return nil, e
}
defer file.Close()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
part, e := writer.CreateFormFile("file", filepath.Base(file.Name()))
if e != nil {
return nil, e
}
if _, e = io.Copy(part, file); e != nil {
return nil, e
}
writer.Close()
r, e := http.NewRequest(http.MethodPost, url, &body)
if e != nil {
return nil, e
}
r.Header.Add("Content-Type", writer.FormDataContentType())
return r, nil
}
func fetchServerHealthInfo(ctx *cli.Context, client *madmin.AdminClient) (interface{}, string, error) {
opts := GetHealthDataTypeSlice(ctx, "test")
if len(*opts) == 0 {
full := ctx.Bool("full")
if full {
opts = &fullOptions
} else {
opts = &liteOptions
}
}
optsMap := make(map[madmin.HealthDataType]struct{})
for _, opt := range *opts {
optsMap[opt] = struct{}{}
}
spinners := []string{"/", "|", "\\", "--", "|"}
cont, cancel := context.WithCancel(globalContext)
defer cancel()
startSpinner := func(s string) func() {
ctx, cancel := context.WithCancel(cont)
printText := func(t string, sp string, rewind int) {
console.RewindLines(rewind)
dot := infoText(dot)
t = fmt.Sprintf("%s ...", t)
t = greenText(t)
sp = infoText(sp)
toPrint := fmt.Sprintf("%s %s %s ", dot, t, sp)
console.Printf("%s\n", toPrint)
}
i := 0
sp := func() string {
i = i + 1
i = i % len(spinners)
return spinners[i]
}
done := make(chan bool)
doneToggle := false
go func() {
printText(s, sp(), 0)
for {
time.Sleep(500 * time.Millisecond) // 2 fps
if ctx.Err() != nil {
printText(s, check, 1)
done <- true
return
}
printText(s, sp(), 1)
}
}()
return func() {
cancel()
if !doneToggle {
<-done
os.Stdout.Sync()
doneToggle = true
}
}
}
spinner := func(resource string, opt madmin.HealthDataType) func(bool) bool {
var spinStopper func()
done := false
_, ok := optsMap[opt] // check if option is enabled
if globalJSON || !ok {
return func(bool) bool {
return true
}
}
return func(cond bool) bool {
if done {
return done
}
if spinStopper == nil {
spinStopper = startSpinner(resource)
}
if cond {
done = true
spinStopper()
}
return done
}
}
admin := spinner("Admin Info", madmin.HealthDataTypeMinioInfo)
cpu := spinner("CPU Info", madmin.HealthDataTypeSysCPU)
diskHw := spinner("Disk Info", madmin.HealthDataTypeSysDriveHw)
osInfo := spinner("OS Info", madmin.HealthDataTypeSysOsInfo)
mem := spinner("Mem Info", madmin.HealthDataTypeSysMem)
process := spinner("Process Info", madmin.HealthDataTypeSysLoad)
config := spinner("Server Config", madmin.HealthDataTypeMinioConfig)
drive := spinner("Drive Test", madmin.HealthDataTypePerfDrive)
net := spinner("Network Test", madmin.HealthDataTypePerfNet)
syserr := spinner("System Errors", madmin.HealthDataTypeSysErrors)
syssrv := spinner("System Services", madmin.HealthDataTypeSysServices)
sysconfig := spinner("System Config", madmin.HealthDataTypeSysConfig)
progressV0 := func(info madmin.HealthInfoV0) {
noOfServers := len(info.Sys.CPUInfo)
_ = admin(len(info.Minio.Info.Servers) > 0) &&
cpu(len(info.Sys.CPUInfo) > 0) &&
diskHw(len(info.Sys.DiskHwInfo) > 0) &&
osInfo(len(info.Sys.OsInfo) > 0) &&
mem(len(info.Sys.MemInfo) > 0) &&
process(len(info.Sys.ProcInfo) > 0) &&
config(info.Minio.Config != nil) &&
drive(len(info.Perf.DriveInfo) > 0) &&
net(noOfServers == 1 || (len(info.Perf.Net) > 1 && len(info.Perf.NetParallel.Addr) > 0))
}
progress := func(info madmin.HealthInfo) {
noOfServers := len(info.Sys.CPUInfo)
_ = cpu(len(info.Sys.CPUInfo) > 0) &&
diskHw(len(info.Sys.Partitions) > 0) &&
osInfo(len(info.Sys.OSInfo) > 0) &&
mem(len(info.Sys.MemInfo) > 0) &&
process(len(info.Sys.ProcInfo) > 0) &&
config(info.Minio.Config.Config != nil) &&
drive(len(info.Perf.Drives) > 0) &&
net(noOfServers == 1 || (len(info.Perf.Net) > 1 && len(info.Perf.NetParallel.Addr) > 0)) &&
syserr(len(info.Sys.SysErrs) > 0) &&
syssrv(len(info.Sys.SysServices) > 0) &&
sysconfig(len(info.Sys.SysConfig) > 0) &&
admin(len(info.Minio.Info.Servers) > 0)
}
var err error
// Fetch info of all servers (cluster or single server)
resp, version, err := client.ServerHealthInfo(cont, *opts, ctx.Duration("deadline"))
if err != nil {
cancel()
return nil, "", err
}
var healthInfo interface{}
decoder := json.NewDecoder(resp.Body)
switch version {
case madmin.HealthInfoVersion0:
info := madmin.HealthInfoV0{}
for {
if err = decoder.Decode(&info); err != nil {
if errors.Is(err, io.EOF) {
err = nil
}
break
}
progressV0(info)
}
// Old minio versions don't return the MinIO info in
// response of the healthinfo api. So fetch it separately
minioInfo, err := client.ServerInfo(globalContext)
if err != nil {
info.Minio.Error = err.Error()
} else {
info.Minio.Info = minioInfo
}
healthInfo = MapHealthInfoToV1(info, nil)
version = madmin.HealthInfoVersion1
case madmin.HealthInfoVersion:
info := madmin.HealthInfo{}
for {
if err = decoder.Decode(&info); err != nil {
if errors.Is(err, io.EOF) {
err = nil
}
break
}
progress(info)
}
healthInfo = info
}
// cancel the context if obdChan has returned.
cancel()
return healthInfo, version, err
}
// HealthDataTypeSlice is a typed list of health tests
type HealthDataTypeSlice []madmin.HealthDataType
// Set - sets the flag to the given value
func (d *HealthDataTypeSlice) Set(value string) error {
for _, v := range strings.Split(value, ",") {
if obdData, ok := madmin.HealthDataTypesMap[strings.Trim(v, " ")]; ok {
*d = append(*d, obdData)
} else {
return fmt.Errorf("valid options include %s", fullOptions.String())
}
}
return nil
}
// String - returns the string representation of the health datatypes
func (d *HealthDataTypeSlice) String() string {
val := ""
for _, obdData := range *d {
formatStr := "%s"
if val != "" {
formatStr = fmt.Sprintf("%s,%%s", formatStr)
} else {
formatStr = fmt.Sprintf("%s%%s", formatStr)
}
val = fmt.Sprintf(formatStr, val, string(obdData))
}
return val
}
// Value - returns the value
func (d *HealthDataTypeSlice) Value() []madmin.HealthDataType {
return *d
}
// Get - returns the value
func (d *HealthDataTypeSlice) Get() interface{} {
return *d
}
// HealthDataTypeFlag is a typed flag to represent health datatypes
type HealthDataTypeFlag struct {
Name string
Usage string
EnvVar string
Hidden bool
Value *HealthDataTypeSlice
}
// String - returns the string to be shown in the help message
func (f HealthDataTypeFlag) String() string {
return cli.FlagStringer(f)
}
// GetName - returns the name of the flag
func (f HealthDataTypeFlag) GetName() string {
return f.Name
}
// GetHealthDataTypeSlice - returns the list of set health tests
func GetHealthDataTypeSlice(c *cli.Context, name string) *HealthDataTypeSlice {
generic := c.Generic(name)
if generic == nil {
return nil
}
return generic.(*HealthDataTypeSlice)
}
// GetGlobalHealthDataTypeSlice - returns the list of set health tests set globally
func GetGlobalHealthDataTypeSlice(c *cli.Context, name string) *HealthDataTypeSlice {
generic := c.GlobalGeneric(name)
if generic == nil {
return nil
}
return generic.(*HealthDataTypeSlice)
}
// Apply - applies the flag
func (f HealthDataTypeFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError - applies with error
func (f HealthDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
newVal := &HealthDataTypeSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
if err := newVal.Set(s); err != nil {
return fmt.Errorf("could not parse %s as health datatype value for flag %s: %s", envVal, f.Name, err)
}
}
f.Value = newVal
break
}
}
}
for _, name := range strings.Split(f.Name, ",") {
name = strings.Trim(name, " ")
if f.Value == nil {
f.Value = &HealthDataTypeSlice{}
}
set.Var(f.Value, name, f.Usage)
}
return nil
}
var (
liteOptions = HealthDataTypeSlice(madmin.HealthDataTypesLite)
fullOptions = HealthDataTypeSlice(madmin.HealthDataTypesList)
)
-177
View File
@@ -1,177 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/google/uuid"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminSubnetRegisterCmd = cli.Command{
Name: "register",
Usage: "Register the MinIO Cluster with SUBNET",
OnUsageError: onUsageError,
Action: mainAdminRegister,
Before: setGlobalsFromContext,
Flags: append(subnetCommonFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Register MinIO cluster at alias 'play' on SUBNET, using alias as the cluster name.
{{.Prompt}} {{.HelpName}} play
2. Register MinIO cluster at alias 'play' on SUBNET, using the name "play-cluster".
{{.Prompt}} {{.HelpName}} play --name play-cluster
3. Register MinIO cluster at alias 'play' on SUBNET, using the proxy https://192.168.1.3:3128
{{.Prompt}} {{.HelpName}} play --subnet-proxy https://192.168.1.3:3128
`,
}
// checkAdminRegisterSyntax - validate arguments passed by a user
func checkAdminRegisterSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "register", 1) // last argument is exit code
}
}
// ClusterRegistrationReq - JSON payload of the subnet api for cluster registration
// Contains a registration token created by base64 encoding of the registration info
type ClusterRegistrationReq struct {
Token string `json:"token"`
}
// ClusterRegistrationInfo - Information stored in the cluster registration token
type ClusterRegistrationInfo struct {
DeploymentID string `json:"deployment_id"`
ClusterName string `json:"cluster_name"`
UsedCapacity uint64 `json:"used_capacity"`
Info ClusterInfo `json:"info"`
}
// ClusterInfo - The "info" sub-node of the cluster registration information struct
// Intended to be extensible i.e. more fields will be added as and when required
type ClusterInfo struct {
MinioVersion string `json:"minio_version"`
NoOfServerPools int `json:"no_of_server_pools"`
NoOfServers int `json:"no_of_servers"`
NoOfDrives int `json:"no_of_drives"`
NoOfBuckets uint64 `json:"no_of_buckets"`
NoOfObjects uint64 `json:"no_of_objects"`
TotalDriveSpace uint64 `json:"total_drive_space"`
UsedDriveSpace uint64 `json:"used_drive_space"`
}
// SubnetLoginReq - JSON payload of the SUBNET login api
type SubnetLoginReq struct {
Username string `json:"username"`
Password string `json:"password"`
}
// SubnetMFAReq - JSON payload of the SUBNET mfa api
type SubnetMFAReq struct {
Username string `json:"username"`
OTP string `json:"otp"`
Token string `json:"token"`
}
func mainAdminRegister(ctx *cli.Context) error {
checkAdminRegisterSyntax(ctx)
// Get the alias parameter from cli
aliasedURL := ctx.Args().Get(0)
alias, _ := url2Alias(aliasedURL)
offline := ctx.Bool("airgap") || ctx.Bool("offline")
if !offline {
fatalIf(checkURLReachable(subnetBaseURL()).Trace(aliasedURL), "Unable to reach %s register", subnetBaseURL())
}
// Create a new MinIO Admin Client
client := getClient(aliasedURL)
// Fetch info of all servers (cluster or single server)
admInfo, e := client.ServerInfo(globalContext)
fatalIf(probe.NewError(e), "Unable to fetch cluster info")
clusterName := ctx.String("name")
if len(clusterName) == 0 {
clusterName = alias
} else {
if offline {
fatalIf(errInvalidArgument(), "'--name' is not allowed in airgapped mode")
}
}
regInfo := getClusterRegInfo(admInfo, clusterName)
if offline {
registerOffline(regInfo, alias)
} else {
registerOnline(regInfo, alias, clusterName)
}
console.Infoln(fmt.Sprintln("Cluster", clusterName, "successfully registered on SUBNET."))
return nil
}
func registerOffline(clusterRegInfo ClusterRegistrationInfo, alias string) {
regToken, e := generateRegToken(clusterRegInfo)
fatalIf(probe.NewError(e), "Unable to generate registration token")
subnetRegisterPageURL := "https://subnet.min.io/cluster/register"
fmt.Print(`Step 1: Use the following token to register your cluster at ` + subnetRegisterPageURL + `
` + regToken + `
Step 2: Enter the API key generated by SUBNET: `)
reader := bufio.NewReader(os.Stdin)
apiKey, e := reader.ReadString('\n')
fatalIf(probe.NewError(e), "Error in reading API key")
apiKey = strings.TrimSpace(apiKey)
if len(apiKey) > 0 {
_, e := uuid.Parse(apiKey)
fatalIf(probe.NewError(e), "Invalid API key specified:")
setSubnetAPIKeyConfig(alias, apiKey)
} else {
console.Fatalln("Invalid API key specified. Please run the command again with a valid SUBNET API key to complete registration.")
}
}
func registerOnline(clusterRegInfo ClusterRegistrationInfo, alias string, clusterName string) {
resp, e := registerClusterOnSubnet(alias, clusterRegInfo)
fatalIf(probe.NewError(e), "Could not register cluster with SUBNET:")
extractAndSaveAPIKey(alias, resp)
}
-50
View File
@@ -1,50 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var subnetHealthSubcommands = []cli.Command{
adminSubnetHealthCmd,
adminSubnetRegisterCmd,
}
var adminSubnetCmd = cli.Command{
Name: "subnet",
Usage: "Subnet related commands",
Action: mainAdminSubnet,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: subnetHealthSubcommands,
HideHelpCommand: true,
}
// mainAdminSubnet is the handle for "mc admin subnet" command.
func mainAdminSubnet(ctx *cli.Context) error {
commandNotFound(ctx, subnetHealthSubcommands)
return nil
// Sub-commands like "health", "register" have their own main.
}
func adminHealthCmd() cli.Command {
cmd := adminSubnetHealthCmd
cmd.Hidden = true
return cmd
}
-357
View File
@@ -1,357 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"io/ioutil"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
madmin "github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminTierAddFlags = []cli.Flag{
cli.StringFlag{
Name: "endpoint",
Value: "",
Usage: "remote tier endpoint. e.g https://s3.amazonaws.com",
},
cli.StringFlag{
Name: "region",
Value: "",
Usage: "remote tier region. e.g us-west-2",
},
cli.StringFlag{
Name: "access-key",
Value: "",
Usage: "AWS S3 or compatible object storage access-key",
},
cli.StringFlag{
Name: "secret-key",
Value: "",
Usage: "AWS S3 or compatible object storage secret-key",
},
cli.BoolFlag{
Name: "use-aws-role",
Usage: "use AWS S3 role",
},
cli.StringFlag{
Name: "account-name",
Value: "",
Usage: "Azure Blob Storage account name",
},
cli.StringFlag{
Name: "account-key",
Value: "",
Usage: "Azure Blob Storage account key",
},
cli.StringFlag{
Name: "credentials-file",
Value: "",
Usage: "path to Google Cloud Storage credentials file",
},
cli.StringFlag{
Name: "bucket",
Value: "",
Usage: "remote tier bucket",
},
cli.StringFlag{
Name: "prefix",
Value: "",
Usage: "remote tier prefix",
},
cli.StringFlag{
Name: "storage-class",
Value: "",
Usage: "remote tier storage-class",
},
}
var adminTierAddCmd = cli.Command{
Name: "add",
Usage: "add a new remote tier target",
Action: mainAdminTierAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminTierAddFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TIER_TYPE TARGET NAME [TIER_FLAGS]
NAME:
Name of remote tier target. e.g WARM-TIER
TIER_TYPE:
Cloud storage backend where objects specified by bucket lifecycle configuration can be transitioned to.
Supported values are s3, azure and gcs.
TIER_FLAGS:
Tier type specific flags.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Configure a new remote tier which transitions objects to a bucket in Azure Blob Storage.
{{.Prompt}} {{.HelpName}} azure myminio AZTIER --account-name foobar --account-key foobar123 --region us-east-1 --bucket testbucket --prefix testprefix/
2. Configure a new remote tier which transitions objects to a bucket in AWS S3 with STANDARD storage class.
{{.Prompt}} {{.HelpName}} s3 myminio S3TIER --endpoint https://s3.amazonaws.com --access-key foobar \
--secret-key foobar123 --region us-east-1 --bucket testbucket --prefix testprefix/ --storage-class "STANDARD"
3. Configure a new remote tier which transitions objects to a bucket in Google Cloud Storage.
{{.Prompt}} {{.HelpName}} s3 myminio GCSTIER --credentials-file /path/to/credentials.json --region us-east-1 --bucket testbucket --prefix testprefix/
4. Configure a new remote tier which transitions objects to a bucket in AWS S3 with STANDARD storage class using aws role.
{{.Prompt}} {{.HelpName}} s3 myminio S3TIER --endpoint https://s3.amazonaws.com --use-aws-role \
--region us-east-1 --bucket testbucket --prefix testprefix/ --storage-class "STANDARD"
`,
}
// checkAdminTierAddSyntax validates all the positional arguments
func checkAdminTierAddSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 3 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr > 3 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for tier add command.")
}
}
const (
s3Standard = "STANDARD"
s3ReducedRedundancy = "REDUCED_REDUNDANCY"
)
// fetchTierConfig returns a TierConfig given a tierName, a tierType and ctx to
// lookup command-line flags from. It exits with non-zero error code if any of
// the flags contain invalid values.
func fetchTierConfig(ctx *cli.Context, tierName string, tierType madmin.TierType) *madmin.TierConfig {
switch tierType {
case madmin.S3:
accessKey := ctx.String("access-key")
secretKey := ctx.String("secret-key")
useAwsRole := ctx.IsSet("use-aws-role")
if accessKey == "" && secretKey == "" && !useAwsRole {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("%s remote tier requires access credentials or AWS role", tierType))
}
if (accessKey != "" || secretKey != "") && useAwsRole {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("%s remote tier requires access credentials", tierType))
}
bucket := ctx.String("bucket")
if bucket == "" {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("%s remote tier requires target bucket", tierType))
}
s3Opts := []madmin.S3Options{}
prefix := ctx.String("prefix")
if prefix != "" {
s3Opts = append(s3Opts, madmin.S3Prefix(prefix))
}
endpoint := ctx.String("endpoint")
if endpoint != "" {
s3Opts = append(s3Opts, madmin.S3Endpoint(endpoint))
}
region := ctx.String("region")
if region != "" {
s3Opts = append(s3Opts, madmin.S3Region(region))
}
s3SC := ctx.String("storage-class")
if s3SC != "" {
if s3SC != s3Standard && s3SC != s3ReducedRedundancy {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("unsupported storage-class type %s", s3SC))
}
s3Opts = append(s3Opts, madmin.S3StorageClass(s3SC))
}
if ctx.IsSet("use-aws-role") {
s3Opts = append(s3Opts, madmin.S3AWSRole())
}
s3Cfg, err := madmin.NewTierS3(tierName, accessKey, secretKey, bucket, s3Opts...)
if err != nil {
fatalIf(probe.NewError(err), "Invalid configuration for AWS S3 compatible remote tier")
}
return s3Cfg
case madmin.Azure:
accountName := ctx.String("account-name")
accountKey := ctx.String("account-key")
if accountName == "" || accountKey == "" {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("%s remote tier requires access credentials", tierType))
}
bucket := ctx.String("bucket")
if bucket == "" {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("%s remote tier requires target bucket", tierType))
}
azOpts := []madmin.AzureOptions{}
endpoint := ctx.String("endpoint")
if endpoint != "" {
azOpts = append(azOpts, madmin.AzureEndpoint(endpoint))
}
region := ctx.String("region")
if region != "" {
azOpts = append(azOpts, madmin.AzureRegion(region))
}
prefix := ctx.String("prefix")
if prefix != "" {
azOpts = append(azOpts, madmin.AzurePrefix(prefix))
}
azCfg, err := madmin.NewTierAzure(tierName, accountName, accountKey, bucket, azOpts...)
if err != nil {
fatalIf(probe.NewError(err), "Invalid configuration for Azure Blob Storage remote tier")
}
return azCfg
case madmin.GCS:
bucket := ctx.String("bucket")
if bucket == "" {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("%s remote requires target bucket", tierType))
}
gcsOpts := []madmin.GCSOptions{}
prefix := ctx.String("prefix")
if prefix != "" {
gcsOpts = append(gcsOpts, madmin.GCSPrefix(prefix))
}
region := ctx.String("region")
if region != "" {
gcsOpts = append(gcsOpts, madmin.GCSRegion(region))
}
credsPath := ctx.String("credentials-file")
credsBytes, err := ioutil.ReadFile(credsPath)
if err != nil {
fatalIf(probe.NewError(err), "Failed to read credentials file")
}
gcsCfg, err := madmin.NewTierGCS(tierName, credsBytes, bucket, gcsOpts...)
if err != nil {
fatalIf(probe.NewError(err), "Invalid configuration for Google Cloud Storage remote tier")
}
return gcsCfg
}
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Invalid remote tier type %s", tierType))
return nil
}
type tierMessage struct {
op string
Status string `json:"status"`
TierName string `json:"tierName"`
TierType string `json:"tierType"`
Endpoint string `json:"tierEndpoint"`
Bucket string `json:"bucket"`
Prefix string `json:"prefix,omitempty"`
Region string `json:"region,omitempty"`
TierParams map[string]string `json:"tierParams,omitempty"`
}
// String returns string representation of msg
func (msg *tierMessage) String() string {
switch msg.op {
case "add":
addMsg := fmt.Sprintf("Added remote tier %s of type %s", msg.TierName, msg.TierType)
return console.Colorize("TierMessage", addMsg)
case "ls":
// nothing to do here; ls has its own type to use with printMsg
case "rm":
rmMsg := fmt.Sprintf("Removed remote tier %s", msg.TierName)
return console.Colorize("TierMessage", rmMsg)
case "edit":
editMsg := fmt.Sprintf("Updated remote tier %s", msg.TierName)
return console.Colorize("TierMessage", editMsg)
}
return ""
}
// JSON returns json encoded msg
func (msg *tierMessage) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(msg, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// SetTierConfig sets TierConfig related fields
func (msg *tierMessage) SetTierConfig(sCfg *madmin.TierConfig) {
msg.TierName = sCfg.Name
msg.TierType = sCfg.Type.String()
msg.Endpoint = sCfg.Endpoint()
msg.Bucket = sCfg.Bucket()
msg.Prefix = sCfg.Prefix()
msg.Region = sCfg.Region()
switch sCfg.Type {
case madmin.S3:
msg.TierParams = map[string]string{
"storageClass": sCfg.S3.StorageClass,
}
}
}
func mainAdminTierAdd(ctx *cli.Context) error {
checkAdminTierAddSyntax(ctx)
console.SetColor("TierMessage", color.New(color.FgGreen))
args := ctx.Args()
tierTypeStr := args.Get(0)
tierType, err := madmin.NewTierType(tierTypeStr)
fatalIf(probe.NewError(err), "Unsupported tier type")
aliasedURL := args.Get(1)
tierName := args.Get(2)
if tierName == "" {
fatalIf(errInvalidArgument(), "Tier name can't be empty")
}
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
tCfg := fetchTierConfig(ctx, strings.ToUpper(tierName), tierType)
if err = client.AddTier(globalContext, tCfg); err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Unable to configure remote tier target")
}
msg := &tierMessage{
op: "add",
Status: "success",
}
msg.SetTierConfig(tCfg)
printMsg(msg)
return nil
}
-149
View File
@@ -1,149 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"io/ioutil"
"github.com/fatih/color"
"github.com/minio/cli"
madmin "github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminTierEditFlags = []cli.Flag{
cli.StringFlag{
Name: "access-key",
Value: "",
Usage: "AWS S3 or compatible object storage access-key",
},
cli.StringFlag{
Name: "secret-key",
Value: "",
Usage: "AWS S3 or compatible object storage secret-key",
},
cli.BoolFlag{
Name: "use-aws-role",
Usage: "use AWS S3 role",
},
cli.StringFlag{
Name: "account-key",
Value: "",
Usage: "Azure Blob Storage account key",
},
cli.StringFlag{
Name: "credentials-file",
Value: "",
Usage: "path to Google Cloud Storage credentials file",
},
}
var adminTierEditCmd = cli.Command{
Name: "edit",
Usage: "edits a remote tier",
Action: mainAdminTierEdit,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminTierEditFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET NAME
NAME:
Name of remote tier. e.g WARM-TIER
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Update credentials for an existing Azure Blob Storage remote tier.
{{.Prompt}} {{.HelpName}} myminio AZTIER --account-key foobar-new123
2. Update credentials for an existing AWS S3 compatible remote tier.
{{.Prompt}} {{.HelpName}} myminio S3TIER --access-key foobar-new --secret-key foobar-new123
3. Update credentials for an existing Google Cloud Storage remote tier.
{{.Prompt}} {{.HelpName}} myminio GCSTIER --credentials-file /path/to/credentials.json
`,
}
// checkAdminTierEditSyntax - validate all the postitional arguments
func checkAdminTierEditSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 2 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr > 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for tier-edit subcommand.")
}
}
func mainAdminTierEdit(ctx *cli.Context) error {
checkAdminTierEditSyntax(ctx)
console.SetColor("TierMessage", color.New(color.FgGreen))
args := ctx.Args()
aliasedURL := args.Get(0)
tierName := args.Get(1)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
var creds madmin.TierCreds
accessKey := ctx.String("access-key")
secretKey := ctx.String("secret-key")
accountKey := ctx.String("account-key")
credsPath := ctx.String("credentials-file")
useAwsRole := ctx.IsSet("use-aws-role")
switch {
case accessKey != "" && secretKey != "" && !useAwsRole: // S3 tier
creds.AccessKey = accessKey
creds.SecretKey = secretKey
case useAwsRole:
creds.AWSRole = true
case accountKey != "": // Azure tier
creds.SecretKey = accountKey
case credsPath != "": // GCS tier
credsBytes, err := ioutil.ReadFile(credsPath)
if err != nil {
fatalIf(probe.NewError(err), "Failed to read credentials file")
}
creds.CredsJSON = credsBytes
default:
fatalIf(errInvalidArgument().Trace(args.Tail()...), "Insufficient credential information supplied to update remote tier target credentials")
}
if err := client.EditTier(globalContext, tierName, creds); err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Unable to edit remote tier")
}
printMsg(&tierMessage{
op: "edit",
Status: "success",
TierName: tierName,
})
return nil
}
-225
View File
@@ -1,225 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"strconv"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminTierInfoCmd = cli.Command{
Name: "info",
Usage: "Displays per-tier statistics of all tier targets",
Action: mainAdminTierInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Prints per-tier statistics of all remote tier targets configured in myminio
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminTierInfoSyntax - validate all the passed arguments
func checkAdminTierInfoSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 1 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr > 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for tier-info subcommand.")
}
}
type tierInfoRowHdr int
const (
tierInfoNameHdr tierInfoRowHdr = iota
tierInfoAPIHdr
tierInfoTypeHdr
tierInfoUsageHdr
tierInfoObjectsHdr
tierInfoVersionsHdr
)
var tierInfoRowNames = []string{
"Tier Name",
"API",
"Type",
"Usage",
"Objects",
"Versions",
}
var tierInfoColorScheme = []*color.Color{
color.New(color.FgYellow),
color.New(color.FgCyan),
color.New(color.FgCyan),
color.New(color.FgHiWhite),
color.New(color.FgHiWhite),
color.New(color.FgHiWhite),
}
type tierInfos []madmin.TierInfo
func (t tierInfos) NumRows() int {
return len([]madmin.TierInfo(t))
}
func (t tierInfos) NumCols() int {
return len(tierInfoRowNames)
}
func (t tierInfos) EmptyMessage() string {
return "No remote tiers configured."
}
func (t tierInfos) MarshalJSON() ([]byte, error) {
type tierInfo struct {
Name string
API string
Type string
Stats madmin.TierStats
}
ts := make([]tierInfo, 0, len(t))
for _, tInfo := range t {
ts = append(ts, tierInfo{
Name: tInfo.Name,
API: tierInfoAPI(tInfo.Type),
Type: tierInfoType(tInfo.Type),
Stats: tInfo.Stats,
})
}
return json.Marshal(ts)
}
func tierInfoAPI(tierType string) string {
switch tierType {
case madmin.S3.String(), madmin.GCS.String():
return tierType
case madmin.Azure.String():
return "blob"
case "internal":
return madmin.S3.String()
default:
return "unknown"
}
}
func tierInfoType(tierType string) string {
if tierType == "internal" {
return "hot"
}
return "warm"
}
func (t tierInfos) ToRow(i int, ls []int) []string {
row := make([]string, len(tierInfoRowNames))
if i == -1 {
copy(row, tierInfoRowNames)
} else {
tierInfo := t[i]
row[tierInfoNameHdr] = tierInfo.Name
row[tierInfoAPIHdr] = tierInfoAPI(tierInfo.Type)
row[tierInfoTypeHdr] = tierInfoType(tierInfo.Type)
row[tierInfoUsageHdr] = humanize.IBytes(tierInfo.Stats.TotalSize)
row[tierInfoObjectsHdr] = strconv.Itoa(tierInfo.Stats.NumObjects)
row[tierInfoVersionsHdr] = strconv.Itoa(tierInfo.Stats.NumVersions)
}
// update ls to accommodate this row's values
for i := range tierInfoRowNames {
if ls[i] < len(row[i]) {
ls[i] = len(row[i])
}
}
return row
}
func mainAdminTierInfo(ctx *cli.Context) error {
checkAdminTierInfoSyntax(ctx)
for i, color := range tierInfoColorScheme {
console.SetColor(tierInfoRowNames[i], color)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
var msg tierInfoMessage
tInfos, err := client.TierStats(globalContext)
if err != nil {
msg = tierInfoMessage{
Status: "error",
Context: ctx,
Error: err.Error(),
}
} else {
msg = tierInfoMessage{
Status: "success",
Context: ctx,
TierInfos: tierInfos(tInfos),
}
}
printMsg(&msg)
return nil
}
type tierInfoMessage struct {
Status string `json:"status"`
Context *cli.Context `json:"-"`
TierInfos tierInfos `json:"tiers,omitempty"`
Error string `json:"error,omitempty"`
}
// String method returns a tabular listing of remote tier configurations.
func (msg *tierInfoMessage) String() string {
if msg.Status == "error" {
fatal(probe.NewError(errors.New(msg.Error)), "Unable to get tier statistics")
}
return toTable(msg.TierInfos)
}
// JSON method returns JSON encoding of msg.
func (msg *tierInfoMessage) JSON() string {
b, _ := json.Marshal(msg)
return string(b)
}
-42
View File
@@ -1,42 +0,0 @@
package cmd
import "fmt"
type tabulator interface {
ToRow(i int, lengths []int) []string // returns row representation i-th element in collection, modifies lengths s.t it contains maximum column widths incl this row.
NumRows() int
NumCols() int
EmptyMessage() string
}
func toTable(tbl tabulator) string {
if tbl.NumRows() == 0 {
return tbl.EmptyMessage()
}
const tableSeparator = "|"
rows, cols := getRowsAndCols(tbl)
table := newPrettyTable(tableSeparator, cols...)
var contents string
for _, row := range rows {
contents += fmt.Sprintf("%s\n", table.buildRow(row...))
}
return contents
}
func getRowsAndCols(tbl tabulator) ([][]string, []Field) {
rows := make([][]string, 0, tbl.NumRows()+1)
lengths := make([]int, tbl.NumCols())
rows = append(rows, tbl.ToRow(-1, lengths))
for i := 0; i < tbl.NumRows(); i++ {
rows = append(rows, tbl.ToRow(i, lengths))
}
cols := make([]Field, tbl.NumCols())
for i, hdr := range rows[0] {
cols[i] = Field{
colorTheme: hdr,
maxLen: lengths[i] + 2,
}
}
return rows, cols
}
-192
View File
@@ -1,192 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
madmin "github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminTierListCmd = cli.Command{
Name: "ls",
Usage: "lists remote tier targets",
Action: mainAdminTierList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List remote tier targets configured in myminio
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminTierListSyntax - validate all the passed arguments
func checkAdminTierListSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 1 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr > 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for tier-ls subcommand.")
}
}
type tierLSRowHdr int
const (
tierLSNameHdr tierLSRowHdr = iota
tierLSTypeHdr
tierLSEndpointHdr
tierLSBucketHdr
tierLSPrefixHdr
tierLSRegionHdr
tierLSStorageClassHdr
)
var tierLSRowNames = []string{
"Name",
"Type",
"Endpoint",
"Bucket",
"Prefix",
"Region",
"Storage-Class",
}
var tierLSColorScheme = []*color.Color{
color.New(color.FgYellow),
color.New(color.FgCyan),
color.New(color.FgGreen),
color.New(color.FgHiWhite),
color.New(color.FgHiWhite),
color.New(color.FgHiWhite),
color.New(color.FgCyan),
}
func storageClass(t *madmin.TierConfig) string {
switch t.Type {
case madmin.S3:
return t.S3.StorageClass
case madmin.Azure:
return t.Azure.StorageClass
case madmin.GCS:
return t.GCS.StorageClass
default:
return ""
}
}
type tierLS []*madmin.TierConfig
func (t tierLS) NumRows() int {
return len(([]*madmin.TierConfig)(t))
}
func (t tierLS) NumCols() int {
return len(tierLSRowNames)
}
func (t tierLS) EmptyMessage() string {
return "No remote tier has been configured"
}
func (t tierLS) ToRow(i int, ls []int) []string {
row := make([]string, len(tierLSRowNames))
if i == -1 {
copy(row, tierLSRowNames)
} else {
tc := t[i]
row[tierLSNameHdr] = tc.Name
row[tierLSTypeHdr] = tc.Type.String()
row[tierLSEndpointHdr] = tc.Endpoint()
row[tierLSBucketHdr] = tc.Bucket()
row[tierLSPrefixHdr] = tc.Prefix()
row[tierLSRegionHdr] = tc.Region()
row[tierLSStorageClassHdr] = storageClass(tc)
}
// update ls to accommodate this row's values
for i := range tierLSRowNames {
if ls[i] < len(row[i]) {
ls[i] = len(row[i])
}
}
return row
}
var _ tabulator = (tierLS)(nil)
type tierListMessage struct {
Status string `json:"status"`
Context *cli.Context `json:"-"`
Tiers []*madmin.TierConfig `json:"tiers"`
}
// String method returns a tabular listing of remote tier configurations.
func (msg *tierListMessage) String() string {
return toTable(tierLS(msg.Tiers))
}
// JSON method returns JSON encoding of msg.
func (msg *tierListMessage) JSON() string {
b, _ := json.Marshal(msg)
return string(b)
}
func mainAdminTierList(ctx *cli.Context) error {
checkAdminTierListSyntax(ctx)
for i, color := range tierLSColorScheme {
console.SetColor(tierLSRowNames[i], color)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
tiers, err := client.ListTiers(globalContext)
if err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Unable to list configured remote tier targets")
}
printMsg(&tierListMessage{
Status: "success",
Context: ctx,
Tiers: tiers,
})
return nil
}
-44
View File
@@ -1,44 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminTierSubCommands = []cli.Command{
adminTierAddCmd,
adminTierListCmd,
adminTierEditCmd,
adminTierInfoCmd,
}
var adminTierCmd = cli.Command{
Name: "tier",
Usage: "manage remote tier targets for ILM transition",
Action: mainAdminTier,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminTierSubCommands,
HideHelpCommand: true,
}
// mainAdminTier is the handle for "mc admin tier" command.
func mainAdminTier(ctx *cli.Context) error {
commandNotFound(ctx, adminTierSubCommands)
return nil
// Sub-commands like "add", "ls" and "edit" have their own main.
}
+35 -50
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -23,32 +22,18 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var topLocksFlag = []cli.Flag{
cli.BoolFlag{
Name: "stale",
Usage: "list stale locks",
},
cli.IntFlag{
Name: "count",
Usage: "number of top locks",
Hidden: true,
Value: 10,
},
}
var adminTopLocksCmd = cli.Command{
Name: "locks",
Usage: "get a list of the 10 oldest locks on a MinIO cluster.",
Before: setGlobalsFromContext,
Action: mainAdminTopLocks,
OnUsageError: onUsageError,
Flags: append(globalFlags, topLocksFlag...),
Name: "locks",
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
Before: initBeforeRunningCmd,
Action: mainAdminTopLocks,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -87,18 +72,18 @@ func getTimeDiff(timeStamp time.Time) (string, string) {
// String colorized oldest locks message.
func (u lockMessage) String() string {
const (
timeFieldMaxLen = 20
resourceFieldMaxLen = -1
typeFieldMaxLen = 6
)
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
lockState, timeDiff := getTimeDiff(u.Lock.Timestamp)
return console.Colorize(lockState, newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow(timeDiff, u.Lock.Type, u.Lock.Resource))
).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource))
}
// JSON jsonified top oldest locks message.
@@ -117,6 +102,7 @@ func checkAdminTopLocksSyntax(ctx *cli.Context) {
}
func mainAdminTopLocks(ctx *cli.Context) error {
checkAdminTopLocksSyntax(ctx)
// Get the alias parameter from cli
@@ -128,11 +114,8 @@ func mainAdminTopLocks(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call top locks API
entries, e := client.TopLocksWithOpts(globalContext, madmin.TopLockOpts{
Count: ctx.Int("count"),
Stale: ctx.Bool("stale"),
})
fatalIf(probe.NewError(e), "Unable to get server locks list.")
entries, e := client.TopLocks(globalContext)
fatalIf(probe.NewError(e), "Cannot get server locks list.")
console.SetColor("StaleLock", color.New(color.FgRed, color.Bold))
console.SetColor("Lock", color.New(color.FgBlue, color.Bold))
@@ -147,11 +130,13 @@ func printHeaders() {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
console.Println(console.Colorize("Headers", newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow("Time", "Type", "Resource")))
).buildRow("Time", "Type", "Owner", "Resource")))
}
// Prints oldest locks.
+23 -27
View File
@@ -1,41 +1,37 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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 adminTopSubcommands = []cli.Command{
adminTopLocksCmd,
}
var adminTopCmd = cli.Command{
Name: "top",
Usage: "provide top like statistics for MinIO",
Action: mainAdminTop,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminTopSubcommands,
Name: "top",
Usage: "provide top like statistics for MinIO",
Action: mainAdminTop,
Flags: globalFlags,
Subcommands: []cli.Command{
adminTopLocksCmd,
},
HideHelpCommand: true,
}
// mainAdminTop is the handle for "mc admin top" command.
func mainAdminTop(ctx *cli.Context) error {
commandNotFound(ctx, adminTopSubcommands)
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "locks" have their own main.
}
+65 -309
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2019 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
@@ -23,17 +22,16 @@ import (
"fmt"
"hash/fnv"
"net/http"
"path"
"strings"
"time"
"github.com/dustin/go-humanize"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminTraceFlags = []cli.Flag{
@@ -43,36 +41,11 @@ var adminTraceFlags = []cli.Flag{
},
cli.BoolFlag{
Name: "all, a",
Usage: "trace all call types",
},
cli.StringSliceFlag{
Name: "call",
Usage: "trace only matching Call types (values: `s3`, `internal`, `storage`, `os`)",
},
cli.StringFlag{
Name: "response-threshold",
Usage: "trace calls only with response duration greater than this threshold (e.g. `5ms`)",
},
cli.IntSliceFlag{
Name: "status-code",
Usage: "trace only matching status code",
},
cli.StringSliceFlag{
Name: "method",
Usage: "trace only matching HTTP method",
},
cli.StringSliceFlag{
Name: "funcname",
Usage: "trace only matching func name",
},
cli.StringSliceFlag{
Name: "path",
Usage: "trace only matching path",
Usage: "trace all traffic (including internode traffic between MinIO servers)",
},
cli.BoolFlag{
Name: "errors, e",
Usage: "trace only failed requests",
Usage: "trace failed requests only",
},
}
@@ -80,8 +53,7 @@ var adminTraceCmd = cli.Command{
Name: "trace",
Usage: "show http trace for MinIO server",
Action: mainAdminTrace,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminTraceFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -89,31 +61,24 @@ var adminTraceCmd = cli.Command{
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show verbose console trace for MinIO server
{{.Prompt}} {{.HelpName}} -v -a myminio
1. Show console trace for a MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} -v -a play
2. Show trace only for failed requests for MinIO server
2. Show trace only for failed requests for a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} -v -e myminio
3. Show verbose console trace for requests with '503' status code
{{.Prompt}} {{.HelpName}} -v --status-code 503 myminio
4. Show console trace for a specific path
{{.Prompt}} {{.HelpName}} --path my-bucket/my-prefix/* myminio
5. Show console trace for requests with '404' and '503' status code
{{.Prompt}} {{.HelpName}} --status-code 404 --status-code 503 myminio
`,
}
const timeFormat = "2006-01-02T15:04:05:000"
const timeFormat = "15:04:05.000"
var colors = []color.Attribute{color.FgCyan, color.FgWhite, color.FgYellow, color.FgGreen}
var (
colors = []color.Attribute{color.FgCyan, color.FgWhite, color.FgYellow, color.FgGreen}
)
func checkAdminTraceSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
@@ -121,140 +86,14 @@ func checkAdminTraceSyntax(ctx *cli.Context) {
}
}
func printTrace(verbose bool, traceInfo madmin.ServiceTraceInfo) {
if verbose {
printMsg(traceMessage{ServiceTraceInfo: traceInfo})
} else {
printMsg(shortTrace(traceInfo))
}
}
func matchTrace(ctx *cli.Context, traceInfo madmin.ServiceTraceInfo) bool {
statusCodes := ctx.IntSlice("status-code")
methods := ctx.StringSlice("method")
funcNames := ctx.StringSlice("funcname")
apiPaths := ctx.StringSlice("path")
if len(statusCodes) == 0 && len(methods) == 0 && len(funcNames) == 0 && len(apiPaths) == 0 {
// no specific filtering found trace all the requests
return true
}
// Filter request path if passed by the user
if len(apiPaths) > 0 {
matched := false
for _, apiPath := range apiPaths {
if pathMatch(path.Join("/", apiPath), traceInfo.Trace.ReqInfo.Path) {
matched = true
break
}
}
if !matched {
return false
}
}
// Filter response status codes if passed by the user
if len(statusCodes) > 0 {
matched := false
for _, code := range statusCodes {
if traceInfo.Trace.RespInfo.StatusCode == code {
matched = true
break
}
}
if !matched {
return false
}
}
// Filter request method if passed by the user
if len(methods) > 0 {
matched := false
for _, method := range methods {
if traceInfo.Trace.ReqInfo.Method == method {
matched = true
break
}
}
if !matched {
return false
}
}
if len(funcNames) > 0 {
matched := false
// Filter request function handler names if passed by the user.
for _, funcName := range funcNames {
if nameMatch(funcName, traceInfo.Trace.FuncName) {
matched = true
break
}
}
if !matched {
return false
}
}
return true
}
// Calculate tracing options for command line flags
func tracingOpts(ctx *cli.Context) (opts madmin.ServiceTraceOpts, e error) {
if t := ctx.String("response-threshold"); t != "" {
d, e := time.ParseDuration(t)
if e != nil {
return opts, fmt.Errorf("Unable to parse threshold argument: %w", e)
}
opts.Threshold = d
}
opts.OnlyErrors = ctx.Bool("errors")
if ctx.Bool("all") {
opts.All = true // Deprecated
opts.S3 = true
opts.Internal = true
opts.Storage = true
opts.OS = true
return
}
apis := ctx.StringSlice("call")
if len(apis) == 0 {
// If api flag is not specified, then we will
// trace only S3 requests by default.
opts.S3 = true
return
}
for _, api := range apis {
switch api {
case "storage":
opts.Storage = true
case "internal":
opts.Internal = true
case "s3":
opts.S3 = true
case "os":
opts.OS = true
}
}
return
}
// mainAdminTrace - the entry function of trace command
func mainAdminTrace(ctx *cli.Context) error {
// Check for command syntax
checkAdminTraceSyntax(ctx)
verbose := ctx.Bool("verbose")
all := ctx.Bool("all")
errfltr := ctx.Bool("errors")
aliasedURL := ctx.Args().Get(0)
console.SetColor("Stat", color.New(color.FgYellow))
console.SetColor("Request", color.New(color.FgCyan))
@@ -276,32 +115,30 @@ func mainAdminTrace(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
opts, e := tracingOpts(ctx)
fatalIf(probe.NewError(e), "Unable to start tracing")
// Start listening on all trace activity.
traceCh := client.ServiceTrace(ctxt, opts)
traceCh := client.ServiceTrace(ctxt, all, errfltr)
for traceInfo := range traceCh {
if traceInfo.Err != nil {
fatalIf(probe.NewError(traceInfo.Err), "Unable to listen to http trace")
fatalIf(probe.NewError(traceInfo.Err), "Cannot listen to http trace")
}
if matchTrace(ctx, traceInfo) {
printTrace(verbose, traceInfo)
if verbose {
printMsg(traceMessage{traceInfo})
continue
}
printMsg(shortTrace(traceInfo))
}
return nil
}
// Short trace record
type shortTraceMsg struct {
Status string `json:"status"`
Host string `json:"host"`
Time time.Time `json:"time"`
Client string `json:"client"`
@@ -311,20 +148,14 @@ type shortTraceMsg struct {
Query string `json:"query"`
StatusCode int `json:"statusCode"`
StatusMsg string `json:"statusMsg"`
StorageStats storageStats `json:"storageStats"`
OSStats osStats `json:"osStats"`
Type madmin.TraceType `json:"type"`
}
type traceMessage struct {
Status string `json:"status"`
madmin.ServiceTraceInfo
}
type requestInfo struct {
Time time.Time `json:"time"`
Proto string `json:"proto"`
Method string `json:"method"`
Path string `json:"path,omitempty"`
RawQuery string `json:"rawQuery,omitempty"`
@@ -338,7 +169,6 @@ type responseInfo struct {
Body string `json:"body,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
}
type callStats struct {
Rx int `json:"rx"`
Tx int `json:"tx"`
@@ -346,68 +176,36 @@ type callStats struct {
Ttfb time.Duration `json:"timeToFirstByte"`
}
type osStats struct {
Duration time.Duration `json:"duration"`
Path string `json:"path"`
}
type storageStats struct {
Duration time.Duration `json:"duration"`
Path string `json:"path"`
}
type verboseTrace struct {
Type madmin.TraceType `json:"type"`
NodeName string `json:"host"`
FuncName string `json:"api"`
Time time.Time `json:"time"`
type trace struct {
NodeName string `json:"host"`
FuncName string `json:"api"`
RequestInfo requestInfo `json:"request"`
ResponseInfo responseInfo `json:"response"`
CallStats callStats `json:"callStats"`
StorageStats storageStats `json:"storageStats"`
OSStats osStats `json:"osStats"`
}
// return a struct with minimal trace info.
func shortTrace(ti madmin.ServiceTraceInfo) shortTraceMsg {
s := shortTraceMsg{}
t := ti.Trace
s.Type = t.TraceType
s.FuncName = t.FuncName
s.Time = t.Time
switch t.TraceType {
case madmin.TraceStorage:
s.Path = t.StorageStats.Path
s.Host = t.NodeName
s.StorageStats.Duration = t.StorageStats.Duration
case madmin.TraceOS:
s.Path = t.OSStats.Path
s.Host = t.NodeName
s.OSStats.Duration = t.OSStats.Duration
case madmin.TraceHTTP:
s.Host = t.NodeName
s.Path = t.ReqInfo.Path
s.Query = t.ReqInfo.RawQuery
s.StatusCode = t.RespInfo.StatusCode
s.StatusMsg = http.StatusText(t.RespInfo.StatusCode)
s.Client = t.ReqInfo.Client
s.CallStats.Duration = t.CallStats.Latency
s.CallStats.Rx = t.CallStats.InputBytes
s.CallStats.Tx = t.CallStats.OutputBytes
// Support older versions of MinIO server
s.Time = t.ReqInfo.Time
s.Time = t.ReqInfo.Time
if host, ok := t.ReqInfo.Headers["Host"]; ok {
s.Host = strings.Join(host, "")
}
s.Path = t.ReqInfo.Path
s.Query = t.ReqInfo.RawQuery
s.FuncName = t.FuncName
s.StatusCode = t.RespInfo.StatusCode
s.StatusMsg = http.StatusText(t.RespInfo.StatusCode)
cSlice := strings.Split(t.ReqInfo.Client, ":")
s.Client = cSlice[0]
s.CallStats.Duration = t.CallStats.Latency
s.CallStats.Rx = t.CallStats.InputBytes
s.CallStats.Tx = t.CallStats.OutputBytes
return s
}
func (s shortTraceMsg) JSON() string {
s.Status = "success"
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
@@ -420,35 +218,16 @@ func (s shortTraceMsg) JSON() string {
func (s shortTraceMsg) String() string {
var hostStr string
b := &strings.Builder{}
var b = &strings.Builder{}
if s.Host != "" {
hostStr = colorizedNodeName(s.Host)
}
fmt.Fprintf(b, "%s ", s.Time.Local().Format(timeFormat))
switch s.Type {
case madmin.TraceStorage:
fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", "STORAGE"), console.Colorize("FuncName", s.FuncName),
hostStr,
s.Path,
console.Colorize("HeaderValue", s.StorageStats.Duration))
return b.String()
case madmin.TraceOS:
fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", "OS"), console.Colorize("FuncName", s.FuncName),
hostStr,
s.Path,
console.Colorize("HeaderValue", s.OSStats.Duration))
return b.String()
}
statusStr := fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg)
fmt.Fprintf(b, "%s ", s.Time.Format(timeFormat))
statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
if s.StatusCode >= http.StatusBadRequest {
statusStr = console.Colorize("ErrStatus", statusStr)
} else {
statusStr = console.Colorize("RespStatus", statusStr)
statusStr = console.Colorize("ErrStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
}
fmt.Fprintf(b, "[%s] %s ", statusStr, console.Colorize("FuncName", s.FuncName))
fmt.Fprintf(b, "%s%s", hostStr, s.Path)
@@ -456,7 +235,6 @@ func (s shortTraceMsg) String() string {
fmt.Fprintf(b, "?%s ", s.Query)
}
fmt.Fprintf(b, " %s ", s.Client)
spaces := 15 - len(s.Client)
fmt.Fprintf(b, "%*s", spaces, " ")
fmt.Fprint(b, console.Colorize("HeaderValue", fmt.Sprintf(" %2s", s.CallStats.Duration.Round(time.Microsecond))))
@@ -475,12 +253,11 @@ func colorizedNodeName(nodeName string) string {
nodeHash := fnv.New32a()
nodeHash.Write([]byte(nodeName))
nHashSum := nodeHash.Sum32()
idx := nHashSum % uint32(len(colors))
idx := uint32(nHashSum) % uint32(len(colors))
return console.Colorize(fmt.Sprintf("Node%d", colors[idx]), nodeName)
}
func (t traceMessage) JSON() string {
t.Status = "success"
rqHdrs := make(map[string]string)
rspHdrs := make(map[string]string)
rq := t.Trace.ReqInfo
@@ -491,14 +268,11 @@ func (t traceMessage) JSON() string {
for k, v := range rs.Headers {
rspHdrs[k] = strings.Join(v, " ")
}
trc := verboseTrace{
Type: t.Trace.TraceType,
trc := trace{
NodeName: t.Trace.NodeName,
FuncName: t.Trace.FuncName,
Time: t.Trace.Time,
RequestInfo: requestInfo{
Time: rq.Time,
Proto: rq.Proto,
Method: rq.Method,
Path: rq.Path,
RawQuery: rq.RawQuery,
@@ -517,14 +291,6 @@ func (t traceMessage) JSON() string {
Tx: t.Trace.CallStats.OutputBytes,
Ttfb: t.Trace.CallStats.TimeToFirstByte,
},
OSStats: osStats{
Duration: t.Trace.OSStats.Duration,
Path: t.Trace.OSStats.Path,
},
StorageStats: storageStats{
Duration: t.Trace.StorageStats.Duration,
Path: t.Trace.StorageStats.Path,
},
}
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
@@ -539,32 +305,22 @@ func (t traceMessage) JSON() string {
func (t traceMessage) String() string {
var nodeNameStr string
b := &strings.Builder{}
var b = &strings.Builder{}
trc := t.Trace
if trc.NodeName != "" {
nodeNameStr = fmt.Sprintf("%s ", colorizedNodeName(trc.NodeName))
}
switch trc.TraceType {
case madmin.TraceStorage:
fmt.Fprintf(b, "%s %s [%s] %s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[STORAGE %s]", trc.FuncName)), trc.Time.Local().Format(timeFormat), trc.StorageStats.Path, trc.StorageStats.Duration)
return b.String()
case madmin.TraceOS:
fmt.Fprintf(b, "%s %s [%s] %s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[OS %s]", trc.FuncName)), trc.Time.Local().Format(timeFormat), trc.OSStats.Path, trc.OSStats.Duration)
return b.String()
}
ri := trc.ReqInfo
rs := trc.RespInfo
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[REQUEST %s] ", trc.FuncName)))
fmt.Fprintf(b, "[%s] %s\n", ri.Time.Local().Format(timeFormat), console.Colorize("Host", fmt.Sprintf("[Client IP: %s]", ri.Client)))
fmt.Fprintf(b, "%s\n", ri.Time.Format(timeFormat))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("%s %s", ri.Method, ri.Path)))
if ri.RawQuery != "" {
fmt.Fprintf(b, "?%s", ri.RawQuery)
}
fmt.Fprint(b, "\n")
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("Proto: %s\n", ri.Proto)))
host, ok := ri.Headers["Host"]
if ok {
delete(ri.Headers, "Host")
@@ -578,7 +334,7 @@ func (t traceMessage) String() string {
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Body", fmt.Sprintf("%s\n", string(ri.Body))))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Response", "[RESPONSE] "))
fmt.Fprintf(b, "[%s] ", rs.Time.Local().Format(timeFormat))
fmt.Fprintf(b, "[%s] ", rs.Time.Format(timeFormat))
fmt.Fprint(b, console.Colorize("Stat", fmt.Sprintf("[ Duration %2s ↑ %s ↓ %s ]\n", trc.CallStats.Latency.Round(time.Microsecond), humanize.IBytes(uint64(trc.CallStats.InputBytes)), humanize.IBytes(uint64(trc.CallStats.OutputBytes)))))
statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", rs.StatusCode, http.StatusText(rs.StatusCode)))
@@ -589,7 +345,7 @@ func (t traceMessage) String() string {
for k, v := range rs.Headers {
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("RespHeaderKey",
fmt.Sprintf("%s: ", k))+console.Colorize("HeaderValue", fmt.Sprintf("%s\n", strings.Join(v, ","))))
fmt.Sprintf("%s: ", k))+console.Colorize("HeaderValue", fmt.Sprintf("%s\n", strings.Join(v, ""))))
}
fmt.Fprintf(b, "%s%s\n", nodeNameStr, console.Colorize("Body", string(rs.Body)))
fmt.Fprint(b, nodeNameStr)
+22 -24
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018-2019 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
@@ -22,18 +21,17 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminServerUpdateCmd = cli.Command{
Name: "update",
Usage: "update all MinIO servers",
Action: mainAdminServerUpdate,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "update",
Usage: "update all MinIO servers",
Action: mainAdminServerUpdate,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+23 -25
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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
@@ -25,19 +24,18 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
)
var adminUserAddCmd = cli.Command{
Name: "add",
Usage: "add a new user",
Action: mainAdminUserAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "add",
Usage: "add a new user",
Action: mainAdminUserAdd,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -182,7 +180,7 @@ func mainAdminUserAdd(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.AddUser(globalContext, accessKey, secretKey)).Trace(args...), "Unable to add new user")
fatalIf(probe.NewError(client.AddUser(globalContext, accessKey, secretKey)).Trace(args...), "Cannot add new user")
printMsg(userMessage{
op: "add",
+23 -25
View File
@@ -1,37 +1,35 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminUserDisableCmd = cli.Command{
Name: "disable",
Usage: "disable user",
Action: mainAdminUserDisable,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "disable",
Usage: "disable user",
Action: mainAdminUserDisable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -69,7 +67,7 @@ func mainAdminUserDisable(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountDisabled)
fatalIf(probe.NewError(e).Trace(args...), "Unable to disable user")
fatalIf(probe.NewError(e).Trace(args...), "Cannot disable user")
printMsg(userMessage{
op: "disable",
+23 -25
View File
@@ -1,37 +1,35 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminUserEnableCmd = cli.Command{
Name: "enable",
Usage: "enable user",
Action: mainAdminUserEnable,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "enable",
Usage: "enable user",
Action: mainAdminUserEnable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -69,7 +67,7 @@ func mainAdminUserEnable(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountEnabled)
fatalIf(probe.NewError(e).Trace(args...), "Unable to enable user")
fatalIf(probe.NewError(e).Trace(args...), "Cannot enable user")
printMsg(userMessage{
op: "enable",
+22 -24
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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
@@ -21,16 +20,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminUserInfoCmd = cli.Command{
Name: "info",
Usage: "display info of a user",
Action: mainAdminUserInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "info",
Usage: "display info of a user",
Action: mainAdminUserInfo,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -68,7 +66,7 @@ func mainAdminUserInfo(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
user, e := client.GetUserInfo(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user info")
fatalIf(probe.NewError(e).Trace(args...), "Cannot get user info")
printMsg(userMessage{
op: "info",
+22 -24
View File
@@ -1,19 +1,18 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
* MinIO Client (C) 2018 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
@@ -21,16 +20,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/minio/pkg/console"
)
var adminUserListCmd = cli.Command{
Name: "list",
Usage: "list all users",
Action: mainAdminUserList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "list",
Usage: "list all users",
Action: mainAdminUserList,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -72,7 +70,7 @@ func mainAdminUserList(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
users, e := client.ListUsers(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to list user")
fatalIf(probe.NewError(e).Trace(args...), "Cannot list user")
for k, v := range users {
printMsg(userMessage{
-82
View File
@@ -1,82 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminUserPolicyCmd = cli.Command{
Name: "policy",
Usage: "export user policies in JSON format",
Action: mainAdminUserPolicy,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display the policy document of a user "foobar" in JSON format.
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
// checkAdminUserPolicySyntax - validate all the passed arguments
func checkAdminUserPolicySyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code
}
}
// mainAdminUserPolicy is the handler for "mc admin user policy" command.
func mainAdminUserPolicy(ctx *cli.Context) error {
checkAdminUserPolicySyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
// 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.")
user, e := client.GetUserInfo(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user info")
pinfo, e := getPolicyInfo(client, user.PolicyName)
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch user policy document")
fmt.Println(string(pinfo.Policy))
return nil
}

Some files were not shown because too many files have changed in this diff Show More