From e3854b077a271ab43d81a78603c6ef9d59f53bbf Mon Sep 17 00:00:00 2001
From: kannappanr <30541348+kannappanr@users.noreply.github.com>
Date: Thu, 31 Jan 2019 12:37:04 -0800
Subject: [PATCH] List oldest locks currently used in a distributed XL setup
(#2549)
---
cmd/admin-main.go | 3 +-
cmd/admin-top-locks.go | 151 +++++++++++++++
cmd/admin-top.go | 38 ++++
vendor/github.com/dgrijalva/jwt-go/LICENSE | 8 +
.../dgrijalva/jwt-go/MIGRATION_GUIDE.md | 97 ++++++++++
vendor/github.com/dgrijalva/jwt-go/README.md | 100 ++++++++++
.../dgrijalva/jwt-go/VERSION_HISTORY.md | 118 ++++++++++++
vendor/github.com/dgrijalva/jwt-go/claims.go | 134 ++++++++++++++
vendor/github.com/dgrijalva/jwt-go/doc.go | 4 +
vendor/github.com/dgrijalva/jwt-go/ecdsa.go | 148 +++++++++++++++
.../dgrijalva/jwt-go/ecdsa_utils.go | 67 +++++++
vendor/github.com/dgrijalva/jwt-go/errors.go | 59 ++++++
vendor/github.com/dgrijalva/jwt-go/hmac.go | 95 ++++++++++
.../github.com/dgrijalva/jwt-go/map_claims.go | 94 ++++++++++
vendor/github.com/dgrijalva/jwt-go/none.go | 52 ++++++
vendor/github.com/dgrijalva/jwt-go/parser.go | 148 +++++++++++++++
vendor/github.com/dgrijalva/jwt-go/rsa.go | 101 ++++++++++
vendor/github.com/dgrijalva/jwt-go/rsa_pss.go | 126 +++++++++++++
.../github.com/dgrijalva/jwt-go/rsa_utils.go | 101 ++++++++++
.../dgrijalva/jwt-go/signing_method.go | 35 ++++
vendor/github.com/dgrijalva/jwt-go/token.go | 108 +++++++++++
.../minio/minio/pkg/auth/credentials.go | 175 ++++++++++++++++++
.../minio/minio/pkg/cpu/counter_linux.go | 37 ++++
.../minio/minio/pkg/cpu/counter_other.go | 33 ++++
vendor/github.com/minio/minio/pkg/cpu/cpu.go | 91 +++++++++
.../github.com/minio/minio/pkg/cpu/helpers.go | 30 +++
.../github.com/minio/minio/pkg/disk/disk.go | 138 ++++++++++++++
.../minio/minio/pkg/disk/helpers.go | 52 ++++++
.../minio/minio/pkg/disk/root-disk-unix.go | 31 ++++
.../minio/minio/pkg/disk/root-disk-windows.go | 9 +
.../minio/minio/pkg/disk/stat_bsd.go | 41 ++++
.../minio/minio/pkg/disk/stat_fallback.go | 24 +++
.../minio/minio/pkg/disk/stat_linux.go | 41 ++++
.../minio/minio/pkg/disk/stat_openbsd.go | 41 ++++
.../minio/minio/pkg/disk/stat_solaris.go | 40 ++++
.../minio/minio/pkg/disk/stat_windows.go | 94 ++++++++++
.../minio/minio/pkg/disk/type_bsd.go | 28 +++
.../minio/minio/pkg/disk/type_linux.go | 47 +++++
.../minio/minio/pkg/disk/type_windows.go | 70 +++++++
.../github.com/minio/minio/pkg/madmin/API.md | 89 ++++++++-
.../minio/minio/pkg/madmin/info-commands.go | 134 ++++++++++++++
.../minio/minio/pkg/madmin/top-commands.go | 78 ++++++++
.../minio/minio/pkg/madmin/user-commands.go | 11 ++
vendor/github.com/minio/minio/pkg/mem/mem.go | 39 ++++
vendor/vendor.json | 36 +++-
45 files changed, 3184 insertions(+), 12 deletions(-)
create mode 100644 cmd/admin-top-locks.go
create mode 100644 cmd/admin-top.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/LICENSE
create mode 100644 vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md
create mode 100644 vendor/github.com/dgrijalva/jwt-go/README.md
create mode 100644 vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
create mode 100644 vendor/github.com/dgrijalva/jwt-go/claims.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/doc.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/errors.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/hmac.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/map_claims.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/none.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/parser.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_pss.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_utils.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/signing_method.go
create mode 100644 vendor/github.com/dgrijalva/jwt-go/token.go
create mode 100644 vendor/github.com/minio/minio/pkg/auth/credentials.go
create mode 100644 vendor/github.com/minio/minio/pkg/cpu/counter_linux.go
create mode 100644 vendor/github.com/minio/minio/pkg/cpu/counter_other.go
create mode 100644 vendor/github.com/minio/minio/pkg/cpu/cpu.go
create mode 100644 vendor/github.com/minio/minio/pkg/cpu/helpers.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/disk.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/helpers.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/root-disk-unix.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/root-disk-windows.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/stat_bsd.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/stat_fallback.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/stat_linux.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/stat_openbsd.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/stat_solaris.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/stat_windows.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/type_bsd.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/type_linux.go
create mode 100644 vendor/github.com/minio/minio/pkg/disk/type_windows.go
create mode 100644 vendor/github.com/minio/minio/pkg/madmin/top-commands.go
create mode 100644 vendor/github.com/minio/minio/pkg/mem/mem.go
diff --git a/cmd/admin-main.go b/cmd/admin-main.go
index 984be82c..56171d3a 100644
--- a/cmd/admin-main.go
+++ b/cmd/admin-main.go
@@ -38,6 +38,7 @@ var adminCmd = cli.Command{
adminConfigCmd,
adminHealCmd,
adminProfileCmd,
+ adminTopCmd,
},
}
@@ -45,5 +46,5 @@ var adminCmd = cli.Command{
func mainAdmin(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
- // Sub-commands like "service", "heal", "lock" have their own main.
+ // Sub-commands like "service", "heal", "top" have their own main.
}
diff --git a/cmd/admin-top-locks.go b/cmd/admin-top-locks.go
new file mode 100644
index 00000000..52029bbd
--- /dev/null
+++ b/cmd/admin-top-locks.go
@@ -0,0 +1,151 @@
+/*
+ * 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 (
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/fatih/color"
+ "github.com/minio/cli"
+ "github.com/minio/mc/pkg/console"
+ "github.com/minio/mc/pkg/probe"
+ "github.com/minio/minio/pkg/madmin"
+)
+
+var adminTopLocksCmd = cli.Command{
+ Name: "locks",
+ Usage: "Get list of oldest locks on a Minio server/cluster.",
+ Before: setGlobalsFromContext,
+ Action: mainAdminTopLocks,
+ Flags: globalFlags,
+ CustomHelpTemplate: `NAME:
+ {{.HelpName}} - {{.Usage}}
+
+USAGE:
+ {{.HelpName}} TARGET
+
+FLAGS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}
+EXAMPLES:
+ 1. Get oldest locks on a Minio server/cluster.
+ $ {{.HelpName}} play/
+
+`,
+}
+
+// lockMessage struct to list lock information.
+type lockMessage struct {
+ Status string `json:"status"`
+ Lock madmin.LockEntry `json:"locks"`
+}
+
+func getTimeDiff(timeStamp time.Time) (string, string) {
+ now := time.Now().UTC()
+ diff := now.Sub(timeStamp)
+ hours := int(diff.Hours())
+ minutes := int(diff.Minutes()) % 60
+ seconds := int(diff.Seconds()) % 60
+ if hours == 0 {
+ if minutes == 0 {
+ return "Lock", fmt.Sprint(seconds, " seconds")
+ }
+ return "Lock", fmt.Sprint(minutes, " minutes")
+ }
+ return "StaleLock", fmt.Sprint(hours, " hours")
+}
+
+// String colorized oldest locks message.
+func (u lockMessage) String() string {
+ 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.Owner, u.Lock.Resource))
+}
+
+// JSON jsonified top oldest locks message.
+func (u lockMessage) JSON() string {
+ u.Status = "success"
+ statusJSONBytes, e := json.Marshal(u)
+ fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
+ return string(statusJSONBytes)
+}
+
+// checkAdminTopLocksSyntax - validate all the passed arguments
+func checkAdminTopLocksSyntax(ctx *cli.Context) {
+ if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
+ cli.ShowCommandHelpAndExit(ctx, "locks", 1) // last argument is exit code
+ }
+}
+
+func mainAdminTopLocks(ctx *cli.Context) error {
+
+ checkAdminTopLocksSyntax(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, "Cannot get a configured admin connection.")
+
+ // Call top locks API
+ entries, e := client.TopLocks()
+ 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))
+ console.SetColor("Headers", color.New(color.FgGreen, color.Bold))
+
+ // Print
+ printLocks(entries)
+ return nil
+}
+
+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", "Owner", "Resource")))
+}
+
+// Prints oldest locks.
+func printLocks(locks madmin.LockEntries) {
+ if !globalJSON {
+ printHeaders()
+ }
+ for _, entry := range locks {
+ printMsg(lockMessage{Lock: entry})
+ }
+}
diff --git a/cmd/admin-top.go b/cmd/admin-top.go
new file mode 100644
index 00000000..77863c79
--- /dev/null
+++ b/cmd/admin-top.go
@@ -0,0 +1,38 @@
+/*
+ * 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 adminTopCmd = cli.Command{
+ Name: "top",
+ Usage: "command like top in linux",
+ Action: mainAdminTop,
+ Before: setGlobalsFromContext,
+ Flags: globalFlags,
+ Subcommands: []cli.Command{
+ adminTopLocksCmd,
+ },
+ HideHelpCommand: true,
+}
+
+// mainAdminTop is the handle for "mc admin top" command.
+func mainAdminTop(ctx *cli.Context) error {
+ cli.ShowCommandHelp(ctx, ctx.Args().First())
+ return nil
+ // Sub-commands like "locks" have their own main.
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/dgrijalva/jwt-go/LICENSE
new file mode 100644
index 00000000..df83a9c2
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/LICENSE
@@ -0,0 +1,8 @@
+Copyright (c) 2012 Dave Grijalva
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md
new file mode 100644
index 00000000..7fc1f793
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md
@@ -0,0 +1,97 @@
+## Migration Guide from v2 -> v3
+
+Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code.
+
+### `Token.Claims` is now an interface type
+
+The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`.
+
+`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property.
+
+The old example for parsing a token looked like this..
+
+```go
+ if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil {
+ fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"])
+ }
+```
+
+is now directly mapped to...
+
+```go
+ if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil {
+ claims := token.Claims.(jwt.MapClaims)
+ fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"])
+ }
+```
+
+`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type.
+
+```go
+ type MyCustomClaims struct {
+ User string
+ *StandardClaims
+ }
+
+ if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil {
+ claims := token.Claims.(*MyCustomClaims)
+ fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt)
+ }
+```
+
+### `ParseFromRequest` has been moved
+
+To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`.
+
+`Extractors` do the work of picking the token string out of a request. The interface is simple and composable.
+
+This simple parsing example:
+
+```go
+ if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil {
+ fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"])
+ }
+```
+
+is directly mapped to:
+
+```go
+ if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil {
+ claims := token.Claims.(jwt.MapClaims)
+ fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"])
+ }
+```
+
+There are several concrete `Extractor` types provided for your convenience:
+
+* `HeaderExtractor` will search a list of headers until one contains content.
+* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content.
+* `MultiExtractor` will try a list of `Extractors` in order until one returns content.
+* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token.
+* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument
+* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header
+
+
+### RSA signing methods no longer accept `[]byte` keys
+
+Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse.
+
+To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types.
+
+```go
+ func keyLookupFunc(*Token) (interface{}, error) {
+ // Don't forget to validate the alg is what you expect:
+ if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
+ return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
+ }
+
+ // Look up key
+ key, err := lookupPublicKey(token.Header["kid"])
+ if err != nil {
+ return nil, err
+ }
+
+ // Unpack key from PEM encoded PKCS8
+ return jwt.ParseRSAPublicKeyFromPEM(key)
+ }
+```
diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md
new file mode 100644
index 00000000..d064e4ee
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/README.md
@@ -0,0 +1,100 @@
+# jwt-go
+
+[](https://travis-ci.org/dgrijalva/jwt-go)
+[](https://godoc.org/github.com/dgrijalva/jwt-go)
+
+A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html)
+
+**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3.
+
+**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail.
+
+**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.
+
+## What the heck is a JWT?
+
+JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens.
+
+In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way.
+
+The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used.
+
+The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own.
+
+## What's in the box?
+
+This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own.
+
+## Examples
+
+See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage:
+
+* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac)
+* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac)
+* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples)
+
+## Extensions
+
+This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`.
+
+Here's an example of an extension that integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS): https://github.com/someone1/gcp-jwt-go
+
+## Compliance
+
+This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences:
+
+* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key.
+
+## Project Status & Versioning
+
+This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason).
+
+This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases).
+
+While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning.
+
+**BREAKING CHANGES:***
+* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code.
+
+## Usage Tips
+
+### Signing vs Encryption
+
+A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:
+
+* The author of the token was in the possession of the signing secret
+* The data has not been modified since it was signed
+
+It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library.
+
+### Choosing a Signing Method
+
+There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric.
+
+Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.
+
+Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.
+
+### Signing Methods and Key Types
+
+Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones:
+
+* The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation
+* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation
+* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation
+
+### JWT and OAuth
+
+It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.
+
+Without going too far down the rabbit hole, here's a description of the interaction of these technologies:
+
+* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
+* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
+* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.
+
+## More
+
+Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
+
+The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation.
diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
new file mode 100644
index 00000000..63702983
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
@@ -0,0 +1,118 @@
+## `jwt-go` Version History
+
+#### 3.2.0
+
+* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation
+* HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate
+* Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before.
+* Deprecated `ParseFromRequestWithClaims` to simplify API in the future.
+
+#### 3.1.0
+
+* Improvements to `jwt` command line tool
+* Added `SkipClaimsValidation` option to `Parser`
+* Documentation updates
+
+#### 3.0.0
+
+* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code
+ * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods.
+ * `ParseFromRequest` has been moved to `request` subpackage and usage has changed
+ * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims.
+* Other Additions and Changes
+ * Added `Claims` interface type to allow users to decode the claims into a custom type
+ * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into.
+ * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage
+ * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims`
+ * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`.
+ * Added several new, more specific, validation errors to error type bitmask
+ * Moved examples from README to executable example files
+ * Signing method registry is now thread safe
+ * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser)
+
+#### 2.7.0
+
+This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes.
+
+* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying
+* Error text for expired tokens includes how long it's been expired
+* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM`
+* Documentation updates
+
+#### 2.6.0
+
+* Exposed inner error within ValidationError
+* Fixed validation errors when using UseJSONNumber flag
+* Added several unit tests
+
+#### 2.5.0
+
+* Added support for signing method none. You shouldn't use this. The API tries to make this clear.
+* Updated/fixed some documentation
+* Added more helpful error message when trying to parse tokens that begin with `BEARER `
+
+#### 2.4.0
+
+* Added new type, Parser, to allow for configuration of various parsing parameters
+ * You can now specify a list of valid signing methods. Anything outside this set will be rejected.
+ * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON
+* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go)
+* Fixed some bugs with ECDSA parsing
+
+#### 2.3.0
+
+* Added support for ECDSA signing methods
+* Added support for RSA PSS signing methods (requires go v1.4)
+
+#### 2.2.0
+
+* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic.
+
+#### 2.1.0
+
+Backwards compatible API change that was missed in 2.0.0.
+
+* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte`
+
+#### 2.0.0
+
+There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change.
+
+The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`.
+
+It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`.
+
+* **Compatibility Breaking Changes**
+ * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct`
+ * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct`
+ * `KeyFunc` now returns `interface{}` instead of `[]byte`
+ * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key
+ * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key
+* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type.
+ * Added public package global `SigningMethodHS256`
+ * Added public package global `SigningMethodHS384`
+ * Added public package global `SigningMethodHS512`
+* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type.
+ * Added public package global `SigningMethodRS256`
+ * Added public package global `SigningMethodRS384`
+ * Added public package global `SigningMethodRS512`
+* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged.
+* Refactored the RSA implementation to be easier to read
+* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM`
+
+#### 1.0.2
+
+* Fixed bug in parsing public keys from certificates
+* Added more tests around the parsing of keys for RS256
+* Code refactoring in RS256 implementation. No functional changes
+
+#### 1.0.1
+
+* Fixed panic if RS256 signing method was passed an invalid key
+
+#### 1.0.0
+
+* First versioned release
+* API stabilized
+* Supports creating, signing, parsing, and validating JWT tokens
+* Supports RS256 and HS256 signing methods
\ No newline at end of file
diff --git a/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/dgrijalva/jwt-go/claims.go
new file mode 100644
index 00000000..f0228f02
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/claims.go
@@ -0,0 +1,134 @@
+package jwt
+
+import (
+ "crypto/subtle"
+ "fmt"
+ "time"
+)
+
+// For a type to be a Claims object, it must just have a Valid method that determines
+// if the token is invalid for any supported reason
+type Claims interface {
+ Valid() error
+}
+
+// Structured version of Claims Section, as referenced at
+// https://tools.ietf.org/html/rfc7519#section-4.1
+// See examples for how to use this with your own claim types
+type StandardClaims struct {
+ Audience string `json:"aud,omitempty"`
+ ExpiresAt int64 `json:"exp,omitempty"`
+ Id string `json:"jti,omitempty"`
+ IssuedAt int64 `json:"iat,omitempty"`
+ Issuer string `json:"iss,omitempty"`
+ NotBefore int64 `json:"nbf,omitempty"`
+ Subject string `json:"sub,omitempty"`
+}
+
+// Validates time based claims "exp, iat, nbf".
+// There is no accounting for clock skew.
+// As well, if any of the above claims are not in the token, it will still
+// be considered a valid claim.
+func (c StandardClaims) Valid() error {
+ vErr := new(ValidationError)
+ now := TimeFunc().Unix()
+
+ // The claims below are optional, by default, so if they are set to the
+ // default value in Go, let's not fail the verification for them.
+ if c.VerifyExpiresAt(now, false) == false {
+ delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
+ vErr.Inner = fmt.Errorf("token is expired by %v", delta)
+ vErr.Errors |= ValidationErrorExpired
+ }
+
+ if c.VerifyIssuedAt(now, false) == false {
+ vErr.Inner = fmt.Errorf("Token used before issued")
+ vErr.Errors |= ValidationErrorIssuedAt
+ }
+
+ if c.VerifyNotBefore(now, false) == false {
+ vErr.Inner = fmt.Errorf("token is not valid yet")
+ vErr.Errors |= ValidationErrorNotValidYet
+ }
+
+ if vErr.valid() {
+ return nil
+ }
+
+ return vErr
+}
+
+// Compares the aud claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool {
+ return verifyAud(c.Audience, cmp, req)
+}
+
+// Compares the exp claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool {
+ return verifyExp(c.ExpiresAt, cmp, req)
+}
+
+// Compares the iat claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool {
+ return verifyIat(c.IssuedAt, cmp, req)
+}
+
+// Compares the iss claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool {
+ return verifyIss(c.Issuer, cmp, req)
+}
+
+// Compares the nbf claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
+ return verifyNbf(c.NotBefore, cmp, req)
+}
+
+// ----- helpers
+
+func verifyAud(aud string, cmp string, required bool) bool {
+ if aud == "" {
+ return !required
+ }
+ if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 {
+ return true
+ } else {
+ return false
+ }
+}
+
+func verifyExp(exp int64, now int64, required bool) bool {
+ if exp == 0 {
+ return !required
+ }
+ return now <= exp
+}
+
+func verifyIat(iat int64, now int64, required bool) bool {
+ if iat == 0 {
+ return !required
+ }
+ return now >= iat
+}
+
+func verifyIss(iss string, cmp string, required bool) bool {
+ if iss == "" {
+ return !required
+ }
+ if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 {
+ return true
+ } else {
+ return false
+ }
+}
+
+func verifyNbf(nbf int64, now int64, required bool) bool {
+ if nbf == 0 {
+ return !required
+ }
+ return now >= nbf
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/dgrijalva/jwt-go/doc.go
new file mode 100644
index 00000000..a86dc1a3
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/doc.go
@@ -0,0 +1,4 @@
+// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html
+//
+// See README.md for more info.
+package jwt
diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go
new file mode 100644
index 00000000..f9773812
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go
@@ -0,0 +1,148 @@
+package jwt
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/rand"
+ "errors"
+ "math/big"
+)
+
+var (
+ // Sadly this is missing from crypto/ecdsa compared to crypto/rsa
+ ErrECDSAVerification = errors.New("crypto/ecdsa: verification error")
+)
+
+// Implements the ECDSA family of signing methods signing methods
+// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification
+type SigningMethodECDSA struct {
+ Name string
+ Hash crypto.Hash
+ KeySize int
+ CurveBits int
+}
+
+// Specific instances for EC256 and company
+var (
+ SigningMethodES256 *SigningMethodECDSA
+ SigningMethodES384 *SigningMethodECDSA
+ SigningMethodES512 *SigningMethodECDSA
+)
+
+func init() {
+ // ES256
+ SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256}
+ RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod {
+ return SigningMethodES256
+ })
+
+ // ES384
+ SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384}
+ RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod {
+ return SigningMethodES384
+ })
+
+ // ES512
+ SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521}
+ RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod {
+ return SigningMethodES512
+ })
+}
+
+func (m *SigningMethodECDSA) Alg() string {
+ return m.Name
+}
+
+// Implements the Verify method from SigningMethod
+// For this verify method, key must be an ecdsa.PublicKey struct
+func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error {
+ var err error
+
+ // Decode the signature
+ var sig []byte
+ if sig, err = DecodeSegment(signature); err != nil {
+ return err
+ }
+
+ // Get the key
+ var ecdsaKey *ecdsa.PublicKey
+ switch k := key.(type) {
+ case *ecdsa.PublicKey:
+ ecdsaKey = k
+ default:
+ return ErrInvalidKeyType
+ }
+
+ if len(sig) != 2*m.KeySize {
+ return ErrECDSAVerification
+ }
+
+ r := big.NewInt(0).SetBytes(sig[:m.KeySize])
+ s := big.NewInt(0).SetBytes(sig[m.KeySize:])
+
+ // Create hasher
+ if !m.Hash.Available() {
+ return ErrHashUnavailable
+ }
+ hasher := m.Hash.New()
+ hasher.Write([]byte(signingString))
+
+ // Verify the signature
+ if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true {
+ return nil
+ } else {
+ return ErrECDSAVerification
+ }
+}
+
+// Implements the Sign method from SigningMethod
+// For this signing method, key must be an ecdsa.PrivateKey struct
+func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) {
+ // Get the key
+ var ecdsaKey *ecdsa.PrivateKey
+ switch k := key.(type) {
+ case *ecdsa.PrivateKey:
+ ecdsaKey = k
+ default:
+ return "", ErrInvalidKeyType
+ }
+
+ // Create the hasher
+ if !m.Hash.Available() {
+ return "", ErrHashUnavailable
+ }
+
+ hasher := m.Hash.New()
+ hasher.Write([]byte(signingString))
+
+ // Sign the string and return r, s
+ if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
+ curveBits := ecdsaKey.Curve.Params().BitSize
+
+ if m.CurveBits != curveBits {
+ return "", ErrInvalidKey
+ }
+
+ keyBytes := curveBits / 8
+ if curveBits%8 > 0 {
+ keyBytes += 1
+ }
+
+ // We serialize the outpus (r and s) into big-endian byte arrays and pad
+ // them with zeros on the left to make sure the sizes work out. Both arrays
+ // must be keyBytes long, and the output must be 2*keyBytes long.
+ rBytes := r.Bytes()
+ rBytesPadded := make([]byte, keyBytes)
+ copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
+
+ sBytes := s.Bytes()
+ sBytesPadded := make([]byte, keyBytes)
+ copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
+
+ out := append(rBytesPadded, sBytesPadded...)
+
+ return EncodeSegment(out), nil
+ } else {
+ return "", err
+ }
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go
new file mode 100644
index 00000000..d19624b7
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go
@@ -0,0 +1,67 @@
+package jwt
+
+import (
+ "crypto/ecdsa"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+)
+
+var (
+ ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
+ ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key")
+)
+
+// Parse PEM encoded Elliptic Curve Private Key Structure
+func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
+ var err error
+
+ // Parse PEM block
+ var block *pem.Block
+ if block, _ = pem.Decode(key); block == nil {
+ return nil, ErrKeyMustBePEMEncoded
+ }
+
+ // Parse the key
+ var parsedKey interface{}
+ if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
+ return nil, err
+ }
+
+ var pkey *ecdsa.PrivateKey
+ var ok bool
+ if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
+ return nil, ErrNotECPrivateKey
+ }
+
+ return pkey, nil
+}
+
+// Parse PEM encoded PKCS1 or PKCS8 public key
+func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
+ var err error
+
+ // Parse PEM block
+ var block *pem.Block
+ if block, _ = pem.Decode(key); block == nil {
+ return nil, ErrKeyMustBePEMEncoded
+ }
+
+ // Parse the key
+ var parsedKey interface{}
+ if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
+ if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
+ parsedKey = cert.PublicKey
+ } else {
+ return nil, err
+ }
+ }
+
+ var pkey *ecdsa.PublicKey
+ var ok bool
+ if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
+ return nil, ErrNotECPublicKey
+ }
+
+ return pkey, nil
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go
new file mode 100644
index 00000000..1c93024a
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/errors.go
@@ -0,0 +1,59 @@
+package jwt
+
+import (
+ "errors"
+)
+
+// Error constants
+var (
+ ErrInvalidKey = errors.New("key is invalid")
+ ErrInvalidKeyType = errors.New("key is of invalid type")
+ ErrHashUnavailable = errors.New("the requested hash function is unavailable")
+)
+
+// The errors that might occur when parsing and validating a token
+const (
+ ValidationErrorMalformed uint32 = 1 << iota // Token is malformed
+ ValidationErrorUnverifiable // Token could not be verified because of signing problems
+ ValidationErrorSignatureInvalid // Signature validation failed
+
+ // Standard Claim validation errors
+ ValidationErrorAudience // AUD validation failed
+ ValidationErrorExpired // EXP validation failed
+ ValidationErrorIssuedAt // IAT validation failed
+ ValidationErrorIssuer // ISS validation failed
+ ValidationErrorNotValidYet // NBF validation failed
+ ValidationErrorId // JTI validation failed
+ ValidationErrorClaimsInvalid // Generic claims validation error
+)
+
+// Helper for constructing a ValidationError with a string error message
+func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
+ return &ValidationError{
+ text: errorText,
+ Errors: errorFlags,
+ }
+}
+
+// The error from Parse if token is not valid
+type ValidationError struct {
+ Inner error // stores the error returned by external dependencies, i.e.: KeyFunc
+ Errors uint32 // bitfield. see ValidationError... constants
+ text string // errors that do not have a valid error just have text
+}
+
+// Validation error is an error type
+func (e ValidationError) Error() string {
+ if e.Inner != nil {
+ return e.Inner.Error()
+ } else if e.text != "" {
+ return e.text
+ } else {
+ return "token is invalid"
+ }
+}
+
+// No errors
+func (e *ValidationError) valid() bool {
+ return e.Errors == 0
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go
new file mode 100644
index 00000000..addbe5d4
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/hmac.go
@@ -0,0 +1,95 @@
+package jwt
+
+import (
+ "crypto"
+ "crypto/hmac"
+ "errors"
+)
+
+// Implements the HMAC-SHA family of signing methods signing methods
+// Expects key type of []byte for both signing and validation
+type SigningMethodHMAC struct {
+ Name string
+ Hash crypto.Hash
+}
+
+// Specific instances for HS256 and company
+var (
+ SigningMethodHS256 *SigningMethodHMAC
+ SigningMethodHS384 *SigningMethodHMAC
+ SigningMethodHS512 *SigningMethodHMAC
+ ErrSignatureInvalid = errors.New("signature is invalid")
+)
+
+func init() {
+ // HS256
+ SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256}
+ RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod {
+ return SigningMethodHS256
+ })
+
+ // HS384
+ SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384}
+ RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod {
+ return SigningMethodHS384
+ })
+
+ // HS512
+ SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512}
+ RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod {
+ return SigningMethodHS512
+ })
+}
+
+func (m *SigningMethodHMAC) Alg() string {
+ return m.Name
+}
+
+// Verify the signature of HSXXX tokens. Returns nil if the signature is valid.
+func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
+ // Verify the key is the right type
+ keyBytes, ok := key.([]byte)
+ if !ok {
+ return ErrInvalidKeyType
+ }
+
+ // Decode signature, for comparison
+ sig, err := DecodeSegment(signature)
+ if err != nil {
+ return err
+ }
+
+ // Can we use the specified hashing method?
+ if !m.Hash.Available() {
+ return ErrHashUnavailable
+ }
+
+ // This signing method is symmetric, so we validate the signature
+ // by reproducing the signature from the signing string and key, then
+ // comparing that against the provided signature.
+ hasher := hmac.New(m.Hash.New, keyBytes)
+ hasher.Write([]byte(signingString))
+ if !hmac.Equal(sig, hasher.Sum(nil)) {
+ return ErrSignatureInvalid
+ }
+
+ // No validation errors. Signature is good.
+ return nil
+}
+
+// Implements the Sign method from SigningMethod for this signing method.
+// Key must be []byte
+func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) {
+ if keyBytes, ok := key.([]byte); ok {
+ if !m.Hash.Available() {
+ return "", ErrHashUnavailable
+ }
+
+ hasher := hmac.New(m.Hash.New, keyBytes)
+ hasher.Write([]byte(signingString))
+
+ return EncodeSegment(hasher.Sum(nil)), nil
+ }
+
+ return "", ErrInvalidKeyType
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/dgrijalva/jwt-go/map_claims.go
new file mode 100644
index 00000000..291213c4
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/map_claims.go
@@ -0,0 +1,94 @@
+package jwt
+
+import (
+ "encoding/json"
+ "errors"
+ // "fmt"
+)
+
+// Claims type that uses the map[string]interface{} for JSON decoding
+// This is the default claims type if you don't supply one
+type MapClaims map[string]interface{}
+
+// Compares the aud claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (m MapClaims) VerifyAudience(cmp string, req bool) bool {
+ aud, _ := m["aud"].(string)
+ return verifyAud(aud, cmp, req)
+}
+
+// Compares the exp claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool {
+ switch exp := m["exp"].(type) {
+ case float64:
+ return verifyExp(int64(exp), cmp, req)
+ case json.Number:
+ v, _ := exp.Int64()
+ return verifyExp(v, cmp, req)
+ }
+ return req == false
+}
+
+// Compares the iat claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool {
+ switch iat := m["iat"].(type) {
+ case float64:
+ return verifyIat(int64(iat), cmp, req)
+ case json.Number:
+ v, _ := iat.Int64()
+ return verifyIat(v, cmp, req)
+ }
+ return req == false
+}
+
+// Compares the iss claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (m MapClaims) VerifyIssuer(cmp string, req bool) bool {
+ iss, _ := m["iss"].(string)
+ return verifyIss(iss, cmp, req)
+}
+
+// Compares the nbf claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool {
+ switch nbf := m["nbf"].(type) {
+ case float64:
+ return verifyNbf(int64(nbf), cmp, req)
+ case json.Number:
+ v, _ := nbf.Int64()
+ return verifyNbf(v, cmp, req)
+ }
+ return req == false
+}
+
+// Validates time based claims "exp, iat, nbf".
+// There is no accounting for clock skew.
+// As well, if any of the above claims are not in the token, it will still
+// be considered a valid claim.
+func (m MapClaims) Valid() error {
+ vErr := new(ValidationError)
+ now := TimeFunc().Unix()
+
+ if m.VerifyExpiresAt(now, false) == false {
+ vErr.Inner = errors.New("Token is expired")
+ vErr.Errors |= ValidationErrorExpired
+ }
+
+ if m.VerifyIssuedAt(now, false) == false {
+ vErr.Inner = errors.New("Token used before issued")
+ vErr.Errors |= ValidationErrorIssuedAt
+ }
+
+ if m.VerifyNotBefore(now, false) == false {
+ vErr.Inner = errors.New("Token is not valid yet")
+ vErr.Errors |= ValidationErrorNotValidYet
+ }
+
+ if vErr.valid() {
+ return nil
+ }
+
+ return vErr
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/dgrijalva/jwt-go/none.go
new file mode 100644
index 00000000..f04d189d
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/none.go
@@ -0,0 +1,52 @@
+package jwt
+
+// Implements the none signing method. This is required by the spec
+// but you probably should never use it.
+var SigningMethodNone *signingMethodNone
+
+const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"
+
+var NoneSignatureTypeDisallowedError error
+
+type signingMethodNone struct{}
+type unsafeNoneMagicConstant string
+
+func init() {
+ SigningMethodNone = &signingMethodNone{}
+ NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid)
+
+ RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod {
+ return SigningMethodNone
+ })
+}
+
+func (m *signingMethodNone) Alg() string {
+ return "none"
+}
+
+// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key
+func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) {
+ // Key must be UnsafeAllowNoneSignatureType to prevent accidentally
+ // accepting 'none' signing method
+ if _, ok := key.(unsafeNoneMagicConstant); !ok {
+ return NoneSignatureTypeDisallowedError
+ }
+ // If signing method is none, signature must be an empty string
+ if signature != "" {
+ return NewValidationError(
+ "'none' signing method with non-empty signature",
+ ValidationErrorSignatureInvalid,
+ )
+ }
+
+ // Accept 'none' signing method.
+ return nil
+}
+
+// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key
+func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) {
+ if _, ok := key.(unsafeNoneMagicConstant); ok {
+ return "", nil
+ }
+ return "", NoneSignatureTypeDisallowedError
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go
new file mode 100644
index 00000000..d6901d9a
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/parser.go
@@ -0,0 +1,148 @@
+package jwt
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+type Parser struct {
+ ValidMethods []string // If populated, only these methods will be considered valid
+ UseJSONNumber bool // Use JSON Number format in JSON decoder
+ SkipClaimsValidation bool // Skip claims validation during token parsing
+}
+
+// Parse, validate, and return a token.
+// keyFunc will receive the parsed token and should return the key for validating.
+// If everything is kosher, err will be nil
+func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
+ return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
+}
+
+func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
+ token, parts, err := p.ParseUnverified(tokenString, claims)
+ if err != nil {
+ return token, err
+ }
+
+ // Verify signing method is in the required set
+ if p.ValidMethods != nil {
+ var signingMethodValid = false
+ var alg = token.Method.Alg()
+ for _, m := range p.ValidMethods {
+ if m == alg {
+ signingMethodValid = true
+ break
+ }
+ }
+ if !signingMethodValid {
+ // signing method is not in the listed set
+ return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid)
+ }
+ }
+
+ // Lookup key
+ var key interface{}
+ if keyFunc == nil {
+ // keyFunc was not provided. short circuiting validation
+ return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable)
+ }
+ if key, err = keyFunc(token); err != nil {
+ // keyFunc returned an error
+ if ve, ok := err.(*ValidationError); ok {
+ return token, ve
+ }
+ return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
+ }
+
+ vErr := &ValidationError{}
+
+ // Validate Claims
+ if !p.SkipClaimsValidation {
+ if err := token.Claims.Valid(); err != nil {
+
+ // If the Claims Valid returned an error, check if it is a validation error,
+ // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
+ if e, ok := err.(*ValidationError); !ok {
+ vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
+ } else {
+ vErr = e
+ }
+ }
+ }
+
+ // Perform validation
+ token.Signature = parts[2]
+ if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
+ vErr.Inner = err
+ vErr.Errors |= ValidationErrorSignatureInvalid
+ }
+
+ if vErr.valid() {
+ token.Valid = true
+ return token, nil
+ }
+
+ return token, vErr
+}
+
+// WARNING: Don't use this method unless you know what you're doing
+//
+// This method parses the token but doesn't validate the signature. It's only
+// ever useful in cases where you know the signature is valid (because it has
+// been checked previously in the stack) and you want to extract values from
+// it.
+func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) {
+ parts = strings.Split(tokenString, ".")
+ if len(parts) != 3 {
+ return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
+ }
+
+ token = &Token{Raw: tokenString}
+
+ // parse Header
+ var headerBytes []byte
+ if headerBytes, err = DecodeSegment(parts[0]); err != nil {
+ if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
+ return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed)
+ }
+ return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+ }
+ if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
+ return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+ }
+
+ // parse Claims
+ var claimBytes []byte
+ token.Claims = claims
+
+ if claimBytes, err = DecodeSegment(parts[1]); err != nil {
+ return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+ }
+ dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
+ if p.UseJSONNumber {
+ dec.UseNumber()
+ }
+ // JSON Decode. Special case for map type to avoid weird pointer behavior
+ if c, ok := token.Claims.(MapClaims); ok {
+ err = dec.Decode(&c)
+ } else {
+ err = dec.Decode(&claims)
+ }
+ // Handle decode error
+ if err != nil {
+ return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+ }
+
+ // Lookup signature method
+ if method, ok := token.Header["alg"].(string); ok {
+ if token.Method = GetSigningMethod(method); token.Method == nil {
+ return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable)
+ }
+ } else {
+ return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
+ }
+
+ return token, parts, nil
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go
new file mode 100644
index 00000000..e4caf1ca
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/rsa.go
@@ -0,0 +1,101 @@
+package jwt
+
+import (
+ "crypto"
+ "crypto/rand"
+ "crypto/rsa"
+)
+
+// Implements the RSA family of signing methods signing methods
+// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation
+type SigningMethodRSA struct {
+ Name string
+ Hash crypto.Hash
+}
+
+// Specific instances for RS256 and company
+var (
+ SigningMethodRS256 *SigningMethodRSA
+ SigningMethodRS384 *SigningMethodRSA
+ SigningMethodRS512 *SigningMethodRSA
+)
+
+func init() {
+ // RS256
+ SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256}
+ RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod {
+ return SigningMethodRS256
+ })
+
+ // RS384
+ SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384}
+ RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod {
+ return SigningMethodRS384
+ })
+
+ // RS512
+ SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512}
+ RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod {
+ return SigningMethodRS512
+ })
+}
+
+func (m *SigningMethodRSA) Alg() string {
+ return m.Name
+}
+
+// Implements the Verify method from SigningMethod
+// For this signing method, must be an *rsa.PublicKey structure.
+func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
+ var err error
+
+ // Decode the signature
+ var sig []byte
+ if sig, err = DecodeSegment(signature); err != nil {
+ return err
+ }
+
+ var rsaKey *rsa.PublicKey
+ var ok bool
+
+ if rsaKey, ok = key.(*rsa.PublicKey); !ok {
+ return ErrInvalidKeyType
+ }
+
+ // Create hasher
+ if !m.Hash.Available() {
+ return ErrHashUnavailable
+ }
+ hasher := m.Hash.New()
+ hasher.Write([]byte(signingString))
+
+ // Verify the signature
+ return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
+}
+
+// Implements the Sign method from SigningMethod
+// For this signing method, must be an *rsa.PrivateKey structure.
+func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {
+ var rsaKey *rsa.PrivateKey
+ var ok bool
+
+ // Validate type of key
+ if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
+ return "", ErrInvalidKey
+ }
+
+ // Create the hasher
+ if !m.Hash.Available() {
+ return "", ErrHashUnavailable
+ }
+
+ hasher := m.Hash.New()
+ hasher.Write([]byte(signingString))
+
+ // Sign the string and return the encoded bytes
+ if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {
+ return EncodeSegment(sigBytes), nil
+ } else {
+ return "", err
+ }
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go
new file mode 100644
index 00000000..10ee9db8
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go
@@ -0,0 +1,126 @@
+// +build go1.4
+
+package jwt
+
+import (
+ "crypto"
+ "crypto/rand"
+ "crypto/rsa"
+)
+
+// Implements the RSAPSS family of signing methods signing methods
+type SigningMethodRSAPSS struct {
+ *SigningMethodRSA
+ Options *rsa.PSSOptions
+}
+
+// Specific instances for RS/PS and company
+var (
+ SigningMethodPS256 *SigningMethodRSAPSS
+ SigningMethodPS384 *SigningMethodRSAPSS
+ SigningMethodPS512 *SigningMethodRSAPSS
+)
+
+func init() {
+ // PS256
+ SigningMethodPS256 = &SigningMethodRSAPSS{
+ &SigningMethodRSA{
+ Name: "PS256",
+ Hash: crypto.SHA256,
+ },
+ &rsa.PSSOptions{
+ SaltLength: rsa.PSSSaltLengthAuto,
+ Hash: crypto.SHA256,
+ },
+ }
+ RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod {
+ return SigningMethodPS256
+ })
+
+ // PS384
+ SigningMethodPS384 = &SigningMethodRSAPSS{
+ &SigningMethodRSA{
+ Name: "PS384",
+ Hash: crypto.SHA384,
+ },
+ &rsa.PSSOptions{
+ SaltLength: rsa.PSSSaltLengthAuto,
+ Hash: crypto.SHA384,
+ },
+ }
+ RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod {
+ return SigningMethodPS384
+ })
+
+ // PS512
+ SigningMethodPS512 = &SigningMethodRSAPSS{
+ &SigningMethodRSA{
+ Name: "PS512",
+ Hash: crypto.SHA512,
+ },
+ &rsa.PSSOptions{
+ SaltLength: rsa.PSSSaltLengthAuto,
+ Hash: crypto.SHA512,
+ },
+ }
+ RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod {
+ return SigningMethodPS512
+ })
+}
+
+// Implements the Verify method from SigningMethod
+// For this verify method, key must be an rsa.PublicKey struct
+func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error {
+ var err error
+
+ // Decode the signature
+ var sig []byte
+ if sig, err = DecodeSegment(signature); err != nil {
+ return err
+ }
+
+ var rsaKey *rsa.PublicKey
+ switch k := key.(type) {
+ case *rsa.PublicKey:
+ rsaKey = k
+ default:
+ return ErrInvalidKey
+ }
+
+ // Create hasher
+ if !m.Hash.Available() {
+ return ErrHashUnavailable
+ }
+ hasher := m.Hash.New()
+ hasher.Write([]byte(signingString))
+
+ return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options)
+}
+
+// Implements the Sign method from SigningMethod
+// For this signing method, key must be an rsa.PrivateKey struct
+func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) {
+ var rsaKey *rsa.PrivateKey
+
+ switch k := key.(type) {
+ case *rsa.PrivateKey:
+ rsaKey = k
+ default:
+ return "", ErrInvalidKeyType
+ }
+
+ // Create the hasher
+ if !m.Hash.Available() {
+ return "", ErrHashUnavailable
+ }
+
+ hasher := m.Hash.New()
+ hasher.Write([]byte(signingString))
+
+ // Sign the string and return the encoded bytes
+ if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil {
+ return EncodeSegment(sigBytes), nil
+ } else {
+ return "", err
+ }
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go
new file mode 100644
index 00000000..a5ababf9
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go
@@ -0,0 +1,101 @@
+package jwt
+
+import (
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+)
+
+var (
+ ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
+ ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
+ ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
+)
+
+// Parse PEM encoded PKCS1 or PKCS8 private key
+func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
+ var err error
+
+ // Parse PEM block
+ var block *pem.Block
+ if block, _ = pem.Decode(key); block == nil {
+ return nil, ErrKeyMustBePEMEncoded
+ }
+
+ var parsedKey interface{}
+ if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
+ if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
+ return nil, err
+ }
+ }
+
+ var pkey *rsa.PrivateKey
+ var ok bool
+ if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
+ return nil, ErrNotRSAPrivateKey
+ }
+
+ return pkey, nil
+}
+
+// Parse PEM encoded PKCS1 or PKCS8 private key protected with password
+func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) {
+ var err error
+
+ // Parse PEM block
+ var block *pem.Block
+ if block, _ = pem.Decode(key); block == nil {
+ return nil, ErrKeyMustBePEMEncoded
+ }
+
+ var parsedKey interface{}
+
+ var blockDecrypted []byte
+ if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil {
+ return nil, err
+ }
+
+ if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil {
+ if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil {
+ return nil, err
+ }
+ }
+
+ var pkey *rsa.PrivateKey
+ var ok bool
+ if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
+ return nil, ErrNotRSAPrivateKey
+ }
+
+ return pkey, nil
+}
+
+// Parse PEM encoded PKCS1 or PKCS8 public key
+func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
+ var err error
+
+ // Parse PEM block
+ var block *pem.Block
+ if block, _ = pem.Decode(key); block == nil {
+ return nil, ErrKeyMustBePEMEncoded
+ }
+
+ // Parse the key
+ var parsedKey interface{}
+ if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
+ if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
+ parsedKey = cert.PublicKey
+ } else {
+ return nil, err
+ }
+ }
+
+ var pkey *rsa.PublicKey
+ var ok bool
+ if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
+ return nil, ErrNotRSAPublicKey
+ }
+
+ return pkey, nil
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go
new file mode 100644
index 00000000..ed1f212b
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/signing_method.go
@@ -0,0 +1,35 @@
+package jwt
+
+import (
+ "sync"
+)
+
+var signingMethods = map[string]func() SigningMethod{}
+var signingMethodLock = new(sync.RWMutex)
+
+// Implement SigningMethod to add new methods for signing or verifying tokens.
+type SigningMethod interface {
+ Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid
+ Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error
+ Alg() string // returns the alg identifier for this method (example: 'HS256')
+}
+
+// Register the "alg" name and a factory function for signing method.
+// This is typically done during init() in the method's implementation
+func RegisterSigningMethod(alg string, f func() SigningMethod) {
+ signingMethodLock.Lock()
+ defer signingMethodLock.Unlock()
+
+ signingMethods[alg] = f
+}
+
+// Get a signing method from an "alg" string
+func GetSigningMethod(alg string) (method SigningMethod) {
+ signingMethodLock.RLock()
+ defer signingMethodLock.RUnlock()
+
+ if methodF, ok := signingMethods[alg]; ok {
+ method = methodF()
+ }
+ return
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go
new file mode 100644
index 00000000..d637e086
--- /dev/null
+++ b/vendor/github.com/dgrijalva/jwt-go/token.go
@@ -0,0 +1,108 @@
+package jwt
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "strings"
+ "time"
+)
+
+// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time).
+// You can override it to use another time value. This is useful for testing or if your
+// server uses a different time zone than your tokens.
+var TimeFunc = time.Now
+
+// Parse methods use this callback function to supply
+// the key for verification. The function receives the parsed,
+// but unverified Token. This allows you to use properties in the
+// Header of the token (such as `kid`) to identify which key to use.
+type Keyfunc func(*Token) (interface{}, error)
+
+// A JWT Token. Different fields will be used depending on whether you're
+// creating or parsing/verifying a token.
+type Token struct {
+ Raw string // The raw token. Populated when you Parse a token
+ Method SigningMethod // The signing method used or to be used
+ Header map[string]interface{} // The first segment of the token
+ Claims Claims // The second segment of the token
+ Signature string // The third segment of the token. Populated when you Parse a token
+ Valid bool // Is the token valid? Populated when you Parse/Verify a token
+}
+
+// Create a new Token. Takes a signing method
+func New(method SigningMethod) *Token {
+ return NewWithClaims(method, MapClaims{})
+}
+
+func NewWithClaims(method SigningMethod, claims Claims) *Token {
+ return &Token{
+ Header: map[string]interface{}{
+ "typ": "JWT",
+ "alg": method.Alg(),
+ },
+ Claims: claims,
+ Method: method,
+ }
+}
+
+// Get the complete, signed token
+func (t *Token) SignedString(key interface{}) (string, error) {
+ var sig, sstr string
+ var err error
+ if sstr, err = t.SigningString(); err != nil {
+ return "", err
+ }
+ if sig, err = t.Method.Sign(sstr, key); err != nil {
+ return "", err
+ }
+ return strings.Join([]string{sstr, sig}, "."), nil
+}
+
+// Generate the signing string. This is the
+// most expensive part of the whole deal. Unless you
+// need this for something special, just go straight for
+// the SignedString.
+func (t *Token) SigningString() (string, error) {
+ var err error
+ parts := make([]string, 2)
+ for i, _ := range parts {
+ var jsonValue []byte
+ if i == 0 {
+ if jsonValue, err = json.Marshal(t.Header); err != nil {
+ return "", err
+ }
+ } else {
+ if jsonValue, err = json.Marshal(t.Claims); err != nil {
+ return "", err
+ }
+ }
+
+ parts[i] = EncodeSegment(jsonValue)
+ }
+ return strings.Join(parts, "."), nil
+}
+
+// Parse, validate, and return a token.
+// keyFunc will receive the parsed token and should return the key for validating.
+// If everything is kosher, err will be nil
+func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
+ return new(Parser).Parse(tokenString, keyFunc)
+}
+
+func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
+ return new(Parser).ParseWithClaims(tokenString, claims, keyFunc)
+}
+
+// Encode JWT specific base64url encoding with padding stripped
+func EncodeSegment(seg []byte) string {
+ return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
+}
+
+// Decode JWT specific base64url encoding with padding stripped
+func DecodeSegment(seg string) ([]byte, error) {
+ if l := len(seg) % 4; l > 0 {
+ seg += strings.Repeat("=", 4-l)
+ }
+
+ return base64.URLEncoding.DecodeString(seg)
+}
diff --git a/vendor/github.com/minio/minio/pkg/auth/credentials.go b/vendor/github.com/minio/minio/pkg/auth/credentials.go
new file mode 100644
index 00000000..bba029fe
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/auth/credentials.go
@@ -0,0 +1,175 @@
+/*
+ * Minio Cloud Storage, (C) 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 auth
+
+import (
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/base64"
+ "fmt"
+ "strings"
+ "time"
+
+ jwtgo "github.com/dgrijalva/jwt-go"
+)
+
+const (
+ // Minimum length for Minio access key.
+ accessKeyMinLen = 3
+
+ // Maximum length for Minio access key.
+ // There is no max length enforcement for access keys
+ accessKeyMaxLen = 20
+
+ // Minimum length for Minio secret key for both server and gateway mode.
+ secretKeyMinLen = 8
+
+ // Maximum secret key length for Minio, this
+ // is used when autogenerating new credentials.
+ // There is no max length enforcement for secret keys
+ secretKeyMaxLen = 40
+
+ // Alpha numeric table used for generating access keys.
+ alphaNumericTable = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+
+ // Total length of the alpha numeric table.
+ alphaNumericTableLen = byte(len(alphaNumericTable))
+)
+
+// Common errors generated for access and secret key validation.
+var (
+ ErrInvalidAccessKeyLength = fmt.Errorf("access key must be minimum %v or more characters long", accessKeyMinLen)
+ ErrInvalidSecretKeyLength = fmt.Errorf("secret key must be minimum %v or more characters long", secretKeyMinLen)
+)
+
+// IsAccessKeyValid - validate access key for right length.
+func IsAccessKeyValid(accessKey string) bool {
+ return len(accessKey) >= accessKeyMinLen
+}
+
+// IsSecretKeyValid - validate secret key for right length.
+func IsSecretKeyValid(secretKey string) bool {
+ return len(secretKey) >= secretKeyMinLen
+}
+
+// Credentials holds access and secret keys.
+type Credentials struct {
+ AccessKey string `xml:"AccessKeyId" json:"accessKey,omitempty"`
+ SecretKey string `xml:"SecretAccessKey" json:"secretKey,omitempty"`
+ Expiration time.Time `xml:"Expiration" json:"expiration,omitempty"`
+ SessionToken string `xml:"SessionToken" json:"sessionToken,omitempty"`
+ Status string `xml:"-" json:"status,omitempty"`
+}
+
+// IsExpired - returns whether Credential is expired or not.
+func (cred Credentials) IsExpired() bool {
+ if cred.Expiration.IsZero() || cred.Expiration == timeSentinel {
+ return false
+ }
+
+ return cred.Expiration.Before(time.Now().UTC())
+}
+
+// IsValid - returns whether credential is valid or not.
+func (cred Credentials) IsValid() bool {
+ // Verify credentials if its enabled or not set.
+ if cred.Status == "enabled" || cred.Status == "" {
+ return IsAccessKeyValid(cred.AccessKey) && IsSecretKeyValid(cred.SecretKey) && !cred.IsExpired()
+ }
+ return false
+}
+
+// Equal - returns whether two credentials are equal or not.
+func (cred Credentials) Equal(ccred Credentials) bool {
+ if !ccred.IsValid() {
+ return false
+ }
+ return (cred.AccessKey == ccred.AccessKey && subtle.ConstantTimeCompare([]byte(cred.SecretKey), []byte(ccred.SecretKey)) == 1 &&
+ subtle.ConstantTimeCompare([]byte(cred.SessionToken), []byte(ccred.SessionToken)) == 1)
+}
+
+var timeSentinel = time.Unix(0, 0).UTC()
+
+// GetNewCredentialsWithMetadata generates and returns new credential with expiry.
+func GetNewCredentialsWithMetadata(m map[string]interface{}, tokenSecret string) (cred Credentials, err error) {
+ readBytes := func(size int) (data []byte, err error) {
+ data = make([]byte, size)
+ var n int
+ if n, err = rand.Read(data); err != nil {
+ return nil, err
+ } else if n != size {
+ return nil, fmt.Errorf("Not enough data. Expected to read: %v bytes, got: %v bytes", size, n)
+ }
+ return data, nil
+ }
+
+ // Generate access key.
+ keyBytes, err := readBytes(accessKeyMaxLen)
+ if err != nil {
+ return cred, err
+ }
+ for i := 0; i < accessKeyMaxLen; i++ {
+ keyBytes[i] = alphaNumericTable[keyBytes[i]%alphaNumericTableLen]
+ }
+ cred.AccessKey = string(keyBytes)
+
+ // Generate secret key.
+ keyBytes, err = readBytes(secretKeyMaxLen)
+ if err != nil {
+ return cred, err
+ }
+ cred.SecretKey = strings.Replace(string([]byte(base64.StdEncoding.EncodeToString(keyBytes))[:secretKeyMaxLen]), "/", "+", -1)
+ cred.Status = "enabled"
+
+ expiry, ok := m["exp"].(float64)
+ if !ok {
+ cred.Expiration = timeSentinel
+ return cred, nil
+ }
+
+ m["accessKey"] = cred.AccessKey
+ jwt := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.MapClaims(m))
+
+ cred.Expiration = time.Unix(int64(expiry), 0)
+ cred.SessionToken, err = jwt.SignedString([]byte(tokenSecret))
+ if err != nil {
+ return cred, err
+ }
+
+ return cred, nil
+}
+
+// GetNewCredentials generates and returns new credential.
+func GetNewCredentials() (cred Credentials, err error) {
+ return GetNewCredentialsWithMetadata(map[string]interface{}{}, "")
+}
+
+// CreateCredentials returns new credential with the given access key and secret key.
+// Error is returned if given access key or secret key are invalid length.
+func CreateCredentials(accessKey, secretKey string) (cred Credentials, err error) {
+ if !IsAccessKeyValid(accessKey) {
+ return cred, ErrInvalidAccessKeyLength
+ }
+ if !IsSecretKeyValid(secretKey) {
+ return cred, ErrInvalidSecretKeyLength
+ }
+ cred.AccessKey = accessKey
+ cred.SecretKey = secretKey
+ cred.Expiration = timeSentinel
+ cred.Status = "enabled"
+ return cred, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/cpu/counter_linux.go b/vendor/github.com/minio/minio/pkg/cpu/counter_linux.go
new file mode 100644
index 00000000..44449bc7
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/cpu/counter_linux.go
@@ -0,0 +1,37 @@
+/*
+ * Minio Cloud Storage, (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 cpu
+
+import (
+ "syscall"
+ "time"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+func newCounter() (counter, error) {
+ return counter{}, nil
+}
+
+func (c counter) now() time.Time {
+ var ts syscall.Timespec
+ // Retrieve Per-process CPU-time clock
+ syscall.Syscall(syscall.SYS_CLOCK_GETTIME, unix.CLOCK_PROCESS_CPUTIME_ID, uintptr(unsafe.Pointer(&ts)), 0)
+ sec, nsec := ts.Unix()
+ return time.Unix(sec, nsec)
+}
diff --git a/vendor/github.com/minio/minio/pkg/cpu/counter_other.go b/vendor/github.com/minio/minio/pkg/cpu/counter_other.go
new file mode 100644
index 00000000..cc3e7ea7
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/cpu/counter_other.go
@@ -0,0 +1,33 @@
+// +build darwin freebsd openbsd netbsd dragonfly windows
+
+/*
+ * Minio Cloud Storage, (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 cpu
+
+import (
+ "fmt"
+ "runtime"
+ "time"
+)
+
+func newCounter() (counter, error) {
+ return counter{}, fmt.Errorf("cpu metrics not implemented for %s platform", runtime.GOOS)
+}
+
+func (c counter) now() time.Time {
+ return time.Time{}
+}
diff --git a/vendor/github.com/minio/minio/pkg/cpu/cpu.go b/vendor/github.com/minio/minio/pkg/cpu/cpu.go
new file mode 100644
index 00000000..147aab3d
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/cpu/cpu.go
@@ -0,0 +1,91 @@
+/*
+ * Minio Cloud Storage, (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 cpu
+
+import (
+ "fmt"
+ "sync"
+ "time"
+)
+
+const (
+ // cpuLoadWindow is the interval of time for which the
+ // cpu utilization is measured
+ cpuLoadWindow = 200 * time.Millisecond
+
+ // cpuLoadSampleSize is the number of samples measured
+ // for calculating cpu utilization
+ cpuLoadSampleSize = 3
+
+ // endOfTime represents the end of time
+ endOfTime = time.Duration(1<<63 - 1)
+)
+
+// Load holds CPU utilization % measured in three intervals of 200ms each
+type Load struct {
+ Avg string `json:"avg"`
+ Max string `json:"max"`
+ Min string `json:"min"`
+ Error string `json:"error,omitempty"`
+}
+
+type counter struct{}
+
+// GetLoad returns the CPU utilization % of the current process
+func GetLoad() Load {
+ vals := make(chan time.Duration, 3)
+ wg := sync.WaitGroup{}
+ for i := 0; i < cpuLoadSampleSize; i++ {
+ cpuCounter, err := newCounter()
+ if err != nil {
+ return Load{
+ Error: err.Error(),
+ }
+ }
+ wg.Add(1)
+ go func() {
+ start := cpuCounter.now()
+ time.Sleep(cpuLoadWindow)
+ end := cpuCounter.now()
+ vals <- end.Sub(start)
+ wg.Done()
+ }()
+ }
+ wg.Wait()
+
+ sum := time.Duration(0)
+ max := time.Duration(0)
+ min := (endOfTime)
+ for i := 0; i < cpuLoadSampleSize; i++ {
+ val := <-vals
+ sum = sum + val
+ if val > max {
+ max = val
+ }
+ if val < min {
+ min = val
+ }
+ }
+ close(vals)
+ avg := sum / 3
+ return Load{
+ Avg: fmt.Sprintf("%.2f%%", toFixed4(float64(avg)/float64(200*time.Millisecond))*100),
+ Max: fmt.Sprintf("%.2f%%", toFixed4(float64(max)/float64(200*time.Millisecond))*100),
+ Min: fmt.Sprintf("%.2f%%", toFixed4(float64(min)/float64(200*time.Millisecond))*100),
+ Error: "",
+ }
+}
diff --git a/vendor/github.com/minio/minio/pkg/cpu/helpers.go b/vendor/github.com/minio/minio/pkg/cpu/helpers.go
new file mode 100644
index 00000000..96eb2466
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/cpu/helpers.go
@@ -0,0 +1,30 @@
+/*
+ * Minio Cloud Storage, (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 cpu
+
+import (
+ "math"
+)
+
+func round(num float64) int {
+ return int(num + math.Copysign(0.5, num))
+}
+
+func toFixed4(num float64) float64 {
+ output := math.Pow(10, float64(4))
+ return float64(round(num*output)) / output
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/disk.go b/vendor/github.com/minio/minio/pkg/disk/disk.go
new file mode 100644
index 00000000..7660cce5
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/disk.go
@@ -0,0 +1,138 @@
+/*
+ * Minio Cloud Storage, (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 disk
+
+import (
+ "bytes"
+ "crypto/rand"
+ "errors"
+ "os"
+ "path"
+ "strconv"
+ "time"
+
+ humanize "github.com/dustin/go-humanize"
+)
+
+// file size for performance read and write checks
+const randBufSize = 1 * humanize.KiByte
+const randParts = 1024
+const fileSize = randParts * randBufSize
+
+// Total count of read / write iteration for performance measurement
+const iterations = 10
+
+// Info stat fs struct is container which holds following values
+// Total - total size of the volume / disk
+// Free - free size of the volume / disk
+// Files - total inodes available
+// Ffree - free inodes available
+// FSType - file system type
+type Info struct {
+ Total uint64
+ Free uint64
+ Files uint64
+ Ffree uint64
+ FSType string
+
+ // Usage is calculated per tenant.
+ Usage uint64
+}
+
+// Performance holds informantion about read and write speed of a disk
+type Performance struct {
+ Path string `json:"path"`
+ Error string `json:"error,omitempty"`
+ WriteSpeed float64 `json:"writeSpeed"`
+ ReadSpeed float64 `json:"readSpeed"`
+}
+
+// GetPerformance returns given disk's read and write performance
+func GetPerformance(path string) Performance {
+ perf := Performance{}
+ write, read, err := doPerfMeasure(path)
+ if err != nil {
+ perf.Error = err.Error()
+ return perf
+ }
+ perf.WriteSpeed = write
+ perf.ReadSpeed = read
+ return perf
+}
+
+// Calculate the write and read performance - write and read 10 tmp (1 MiB)
+// files and find the average time taken (Bytes / Sec)
+func doPerfMeasure(fsPath string) (write, read float64, err error) {
+ var count int
+ var totalWriteElapsed time.Duration
+ var totalReadElapsed time.Duration
+
+ defer os.RemoveAll(fsPath)
+
+ randBuf := make([]byte, randBufSize)
+ rand.Read(randBuf)
+ buf := bytes.Repeat(randBuf, randParts)
+
+ // create the enclosing directory
+ err = os.MkdirAll(fsPath, 0777)
+ if err != nil {
+ return 0, 0, err
+ }
+
+ for count = 1; count <= iterations; count++ {
+ fsTempObjPath := path.Join(fsPath, strconv.Itoa(count))
+
+ // Write performance calculation
+ writeStart := time.Now()
+ n, err := writeFile(fsTempObjPath, buf)
+
+ if err != nil {
+ return 0, 0, err
+ }
+ if n != fileSize {
+ return 0, 0, errors.New("Could not write temporary data to disk")
+ }
+
+ writeElapsed := time.Since(writeStart)
+ totalWriteElapsed += writeElapsed
+
+ // Read performance calculation
+ readStart := time.Now()
+ n, err = readFile(fsTempObjPath, buf)
+
+ if err != nil {
+ return 0, 0, err
+ }
+ if n != fileSize {
+ return 0, 0, errors.New("Could not read temporary data from disk")
+ }
+
+ readElapsed := time.Since(readStart)
+ totalReadElapsed += readElapsed
+ }
+ // Average time spent = total time elapsed / number of writes
+ avgWriteTime := totalWriteElapsed.Seconds() / float64(count)
+ // Write perf = fileSize (in Bytes) / average time spent writing (in seconds)
+ write = fileSize / avgWriteTime
+
+ // Average time spent = total time elapsed / number of writes
+ avgReadTime := totalReadElapsed.Seconds() / float64(count)
+ // read perf = fileSize (in Bytes) / average time spent reading (in seconds)
+ read = fileSize / avgReadTime
+
+ return write, read, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/helpers.go b/vendor/github.com/minio/minio/pkg/disk/helpers.go
new file mode 100644
index 00000000..c0da6da0
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/helpers.go
@@ -0,0 +1,52 @@
+/*
+ * Minio Cloud Storage, (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 disk
+
+import (
+ "os"
+)
+
+func readFile(path string, buf []byte) (int, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return 0, err
+ }
+ defer f.Close()
+
+ n, err := f.Read(buf)
+ if err != nil {
+ return 0, err
+ }
+
+ return n, nil
+}
+
+func writeFile(path string, data []byte) (int, error) {
+ f, err := os.Create(path)
+ if err != nil {
+ return 0, err
+ }
+ defer f.Close()
+
+ n, err := f.Write(data)
+ if err != nil {
+ return 0, err
+ }
+
+ f.Sync()
+ return n, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/root-disk-unix.go b/vendor/github.com/minio/minio/pkg/disk/root-disk-unix.go
new file mode 100644
index 00000000..be51f0df
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/root-disk-unix.go
@@ -0,0 +1,31 @@
+// +build !windows
+
+package disk
+
+import (
+ "os"
+ "syscall"
+)
+
+// IsRootDisk returns if diskPath belongs to root-disk, i.e the disk mounted at "/"
+func IsRootDisk(diskPath string) (bool, error) {
+ rootDisk := false
+ diskInfo, err := os.Stat(diskPath)
+ if err != nil {
+ return false, err
+ }
+ rootInfo, err := os.Stat("/")
+ if err != nil {
+ return false, err
+ }
+ diskStat, diskStatOK := diskInfo.Sys().(*syscall.Stat_t)
+ rootStat, rootStatOK := rootInfo.Sys().(*syscall.Stat_t)
+ if diskStatOK && rootStatOK {
+ if diskStat.Dev == rootStat.Dev {
+ // Indicate if the disk path is on root disk. This is used to indicate the healing
+ // process not to format the drive and end up healing it.
+ rootDisk = true
+ }
+ }
+ return rootDisk, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/root-disk-windows.go b/vendor/github.com/minio/minio/pkg/disk/root-disk-windows.go
new file mode 100644
index 00000000..b19034f3
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/root-disk-windows.go
@@ -0,0 +1,9 @@
+// +build windows
+
+package disk
+
+// IsRootDisk returns if diskPath belongs to root-disk, i.e the disk mounted at "/"
+func IsRootDisk(diskPath string) (bool, error) {
+ // On windows a disk can never be mounted on a subpath.
+ return false, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/stat_bsd.go b/vendor/github.com/minio/minio/pkg/disk/stat_bsd.go
new file mode 100644
index 00000000..7922ec34
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/stat_bsd.go
@@ -0,0 +1,41 @@
+// +build darwin freebsd dragonfly
+
+/*
+ * Minio Cloud Storage, (C) 2015, 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 disk
+
+import (
+ "syscall"
+)
+
+// GetInfo returns total and free bytes available in a directory, e.g. `/`.
+func GetInfo(path string) (info Info, err error) {
+ s := syscall.Statfs_t{}
+ err = syscall.Statfs(path, &s)
+ if err != nil {
+ return Info{}, err
+ }
+ reservedBlocks := uint64(s.Bfree) - uint64(s.Bavail)
+ info = Info{
+ Total: uint64(s.Bsize) * (uint64(s.Blocks) - reservedBlocks),
+ Free: uint64(s.Bsize) * uint64(s.Bavail),
+ Files: uint64(s.Files),
+ Ffree: uint64(s.Ffree),
+ FSType: getFSType(s.Fstypename[:]),
+ }
+ return info, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/stat_fallback.go b/vendor/github.com/minio/minio/pkg/disk/stat_fallback.go
new file mode 100644
index 00000000..cfae4d3d
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/stat_fallback.go
@@ -0,0 +1,24 @@
+// +build netbsd
+
+/*
+ * Minio Cloud Storage, (C) 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 disk
+
+// GetInfo returns total and free bytes available in a directory, e.g. `/`.
+func GetInfo(path string) (info Info, err error) {
+ return Info{}, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/stat_linux.go b/vendor/github.com/minio/minio/pkg/disk/stat_linux.go
new file mode 100644
index 00000000..278aca5e
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/stat_linux.go
@@ -0,0 +1,41 @@
+// +build linux
+
+/*
+ * Minio Cloud Storage, (C) 2015, 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 disk
+
+import (
+ "syscall"
+)
+
+// GetInfo returns total and free bytes available in a directory, e.g. `/`.
+func GetInfo(path string) (info Info, err error) {
+ s := syscall.Statfs_t{}
+ err = syscall.Statfs(path, &s)
+ if err != nil {
+ return Info{}, err
+ }
+ reservedBlocks := uint64(s.Bfree) - uint64(s.Bavail)
+ info = Info{
+ Total: uint64(s.Frsize) * (uint64(s.Blocks) - reservedBlocks),
+ Free: uint64(s.Frsize) * uint64(s.Bavail),
+ Files: uint64(s.Files),
+ Ffree: uint64(s.Ffree),
+ FSType: getFSType(int64(s.Type)),
+ }
+ return info, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/stat_openbsd.go b/vendor/github.com/minio/minio/pkg/disk/stat_openbsd.go
new file mode 100644
index 00000000..1ad190cd
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/stat_openbsd.go
@@ -0,0 +1,41 @@
+// +build openbsd
+
+/*
+ * Minio Cloud Storage, (C) 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 disk
+
+import (
+ "syscall"
+)
+
+// GetInfo returns total and free bytes available in a directory, e.g. `/`.
+func GetInfo(path string) (info Info, err error) {
+ s := syscall.Statfs_t{}
+ err = syscall.Statfs(path, &s)
+ if err != nil {
+ return Info{}, err
+ }
+ reservedBlocks := uint64(s.F_bfree) - uint64(s.F_bavail)
+ info = Info{
+ Total: uint64(s.F_bsize) * (uint64(s.F_blocks) - reservedBlocks),
+ Free: uint64(s.F_bsize) * uint64(s.F_bavail),
+ Files: uint64(s.F_files),
+ Ffree: uint64(s.F_ffree),
+ FSType: getFSType(s.F_fstypename[:]),
+ }
+ return info, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/stat_solaris.go b/vendor/github.com/minio/minio/pkg/disk/stat_solaris.go
new file mode 100644
index 00000000..243b6216
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/stat_solaris.go
@@ -0,0 +1,40 @@
+// +build solaris
+
+/*
+ * Minio Cloud Storage, (C) 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 disk
+
+import (
+ "golang.org/x/sys/unix"
+)
+
+// GetInfo returns total and free bytes available in a directory, e.g. `/`.
+func GetInfo(path string) (info Info, err error) {
+ s := unix.Statvfs_t{}
+ if err = unix.Statvfs(path, &s); err != nil {
+ return Info{}, err
+ }
+ reservedBlocks := uint64(s.Bfree) - uint64(s.Bavail)
+ info = Info{
+ Total: uint64(s.Frsize) * (uint64(s.Blocks) - reservedBlocks),
+ Free: uint64(s.Frsize) * uint64(s.Bavail),
+ Files: uint64(s.Files),
+ Ffree: uint64(s.Ffree),
+ FSType: getFSType(s.Fstr[:]),
+ }
+ return info, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/stat_windows.go b/vendor/github.com/minio/minio/pkg/disk/stat_windows.go
new file mode 100644
index 00000000..1a6bed8d
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/stat_windows.go
@@ -0,0 +1,94 @@
+// +build windows
+
+/*
+ * Minio Cloud Storage, (C) 2015 Minio, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package disk
+
+import (
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+var (
+ kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+ // GetDiskFreeSpaceEx - https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx
+ // Retrieves information about the amount of space that is available on a disk volume,
+ // which is the total amount of space, the total amount of free space, and the total
+ // amount of free space available to the user that is associated with the calling thread.
+ GetDiskFreeSpaceEx = kernel32.NewProc("GetDiskFreeSpaceExW")
+ // GetDiskFreeSpace - https://msdn.microsoft.com/en-us/library/windows/desktop/aa364935(v=vs.85).aspx
+ // Retrieves information about the specified disk, including the amount of free space on the disk.
+ GetDiskFreeSpace = kernel32.NewProc("GetDiskFreeSpaceW")
+)
+
+// GetInfo returns total and free bytes available in a directory, e.g. `C:\`.
+// It returns free space available to the user (including quota limitations)
+//
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx
+func GetInfo(path string) (info Info, err error) {
+ // Stat to know if the path exists.
+ if _, err = os.Stat(path); err != nil {
+ return Info{}, err
+ }
+
+ lpFreeBytesAvailable := int64(0)
+ lpTotalNumberOfBytes := int64(0)
+ lpTotalNumberOfFreeBytes := int64(0)
+
+ // Extract values safely
+ // BOOL WINAPI GetDiskFreeSpaceEx(
+ // _In_opt_ LPCTSTR lpDirectoryName,
+ // _Out_opt_ PULARGE_INTEGER lpFreeBytesAvailable,
+ // _Out_opt_ PULARGE_INTEGER lpTotalNumberOfBytes,
+ // _Out_opt_ PULARGE_INTEGER lpTotalNumberOfFreeBytes
+ // );
+ _, _, _ = GetDiskFreeSpaceEx.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))),
+ uintptr(unsafe.Pointer(&lpFreeBytesAvailable)),
+ uintptr(unsafe.Pointer(&lpTotalNumberOfBytes)),
+ uintptr(unsafe.Pointer(&lpTotalNumberOfFreeBytes)))
+ info = Info{}
+ info.Total = uint64(lpTotalNumberOfBytes)
+ info.Free = uint64(lpFreeBytesAvailable)
+ info.FSType = getFSType(path)
+
+ // Return values of GetDiskFreeSpace()
+ lpSectorsPerCluster := uint32(0)
+ lpBytesPerSector := uint32(0)
+ lpNumberOfFreeClusters := uint32(0)
+ lpTotalNumberOfClusters := uint32(0)
+
+ // Extract values safely
+ // BOOL WINAPI GetDiskFreeSpace(
+ // _In_ LPCTSTR lpRootPathName,
+ // _Out_ LPDWORD lpSectorsPerCluster,
+ // _Out_ LPDWORD lpBytesPerSector,
+ // _Out_ LPDWORD lpNumberOfFreeClusters,
+ // _Out_ LPDWORD lpTotalNumberOfClusters
+ // );
+ _, _, _ = GetDiskFreeSpace.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))),
+ uintptr(unsafe.Pointer(&lpSectorsPerCluster)),
+ uintptr(unsafe.Pointer(&lpBytesPerSector)),
+ uintptr(unsafe.Pointer(&lpNumberOfFreeClusters)),
+ uintptr(unsafe.Pointer(&lpTotalNumberOfClusters)))
+
+ info.Files = uint64(lpTotalNumberOfClusters)
+ info.Ffree = uint64(lpNumberOfFreeClusters)
+
+ return info, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/type_bsd.go b/vendor/github.com/minio/minio/pkg/disk/type_bsd.go
new file mode 100644
index 00000000..187976e7
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/type_bsd.go
@@ -0,0 +1,28 @@
+// +build darwin freebsd dragonfly openbsd solaris
+
+/*
+ * Minio Cloud Storage, (C) 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 disk
+
+// getFSType returns the filesystem type of the underlying mounted filesystem
+func getFSType(fstype []int8) string {
+ b := make([]byte, len(fstype))
+ for i, v := range fstype {
+ b[i] = byte(v)
+ }
+ return string(b)
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/type_linux.go b/vendor/github.com/minio/minio/pkg/disk/type_linux.go
new file mode 100644
index 00000000..7de259a3
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/type_linux.go
@@ -0,0 +1,47 @@
+// +build linux
+
+/*
+ * Minio Cloud Storage, (C) 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 disk
+
+import "strconv"
+
+// fsType2StringMap - list of filesystems supported by donut on linux
+var fsType2StringMap = map[string]string{
+ "1021994": "TMPFS",
+ "137d": "EXT",
+ "4244": "HFS",
+ "4d44": "MSDOS",
+ "52654973": "REISERFS",
+ "5346544e": "NTFS",
+ "58465342": "XFS",
+ "61756673": "AUFS",
+ "6969": "NFS",
+ "ef51": "EXT2OLD",
+ "ef53": "EXT4",
+ "f15f": "ecryptfs",
+}
+
+// getFSType returns the filesystem type of the underlying mounted filesystem
+func getFSType(ftype int64) string {
+ fsTypeHex := strconv.FormatInt(ftype, 16)
+ fsTypeString, ok := fsType2StringMap[fsTypeHex]
+ if !ok {
+ return "UNKNOWN"
+ }
+ return fsTypeString
+}
diff --git a/vendor/github.com/minio/minio/pkg/disk/type_windows.go b/vendor/github.com/minio/minio/pkg/disk/type_windows.go
new file mode 100644
index 00000000..023fd5b5
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/disk/type_windows.go
@@ -0,0 +1,70 @@
+// +build windows
+
+/*
+ * Minio Cloud Storage, (C) 2015 Minio, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package disk
+
+import (
+ "path/filepath"
+ "syscall"
+ "unsafe"
+)
+
+var (
+ // GetVolumeInformation provides windows drive volume information.
+ GetVolumeInformation = kernel32.NewProc("GetVolumeInformationW")
+)
+
+// getFSType returns the filesystem type of the underlying mounted filesystem
+func getFSType(path string) string {
+ var volumeNameSize uint32 = 260
+ var nFileSystemNameSize, lpVolumeSerialNumber uint32
+ var lpFileSystemFlags, lpMaximumComponentLength uint32
+ var lpFileSystemNameBuffer, volumeName [260]byte
+ var ps = syscall.StringToUTF16Ptr(filepath.VolumeName(path))
+
+ // Extract values safely
+ // BOOL WINAPI GetVolumeInformation(
+ // _In_opt_ LPCTSTR lpRootPathName,
+ // _Out_opt_ LPTSTR lpVolumeNameBuffer,
+ // _In_ DWORD nVolumeNameSize,
+ // _Out_opt_ LPDWORD lpVolumeSerialNumber,
+ // _Out_opt_ LPDWORD lpMaximumComponentLength,
+ // _Out_opt_ LPDWORD lpFileSystemFlags,
+ // _Out_opt_ LPTSTR lpFileSystemNameBuffer,
+ // _In_ DWORD nFileSystemNameSize
+ // );
+
+ _, _, _ = GetVolumeInformation.Call(uintptr(unsafe.Pointer(ps)),
+ uintptr(unsafe.Pointer(&volumeName)),
+ uintptr(volumeNameSize),
+ uintptr(unsafe.Pointer(&lpVolumeSerialNumber)),
+ uintptr(unsafe.Pointer(&lpMaximumComponentLength)),
+ uintptr(unsafe.Pointer(&lpFileSystemFlags)),
+ uintptr(unsafe.Pointer(&lpFileSystemNameBuffer)),
+ uintptr(unsafe.Pointer(&nFileSystemNameSize)), 0)
+ var bytes []byte
+ if lpFileSystemNameBuffer[6] == 0 {
+ bytes = []byte{lpFileSystemNameBuffer[0], lpFileSystemNameBuffer[2],
+ lpFileSystemNameBuffer[4]}
+ } else {
+ bytes = []byte{lpFileSystemNameBuffer[0], lpFileSystemNameBuffer[2],
+ lpFileSystemNameBuffer[4], lpFileSystemNameBuffer[6]}
+ }
+
+ return string(bytes)
+}
diff --git a/vendor/github.com/minio/minio/pkg/madmin/API.md b/vendor/github.com/minio/minio/pkg/madmin/API.md
index 04e8642f..f65fea6a 100644
--- a/vendor/github.com/minio/minio/pkg/madmin/API.md
+++ b/vendor/github.com/minio/minio/pkg/madmin/API.md
@@ -36,12 +36,12 @@ func main() {
```
-| Service operations | Info operations | Healing operations | Config operations | IAM operations | Misc |
-|:----------------------------|:----------------------------|:--------------------------------------|:--------------------------|:------------------------------------|:------------------------------------|
-| [`ServiceStatus`](#ServiceStatus) | [`ServerInfo`](#ServerInfo) | [`Heal`](#Heal) | [`GetConfig`](#GetConfig) | [`AddUser`](#AddUser) | [`SetAdminCredentials`](#SetAdminCredentials) |
-| [`ServiceSendAction`](#ServiceSendAction) | | | [`SetConfig`](#SetConfig) | [`SetUserPolicy`](#SetUserPolicy) | [`StartProfiling`](#StartProfiling) |
-| | | | [`GetConfigKeys`](#GetConfigKeys) | [`ListUsers`](#ListUsers) | [`DownloadProfilingData`](#DownloadProfilingData) |
-| | | | [`SetConfigKeys`](#SetConfigKeys) | [`AddCannedPolicy`](#AddCannedPolicy) | |
+| Service operations | Info operations | Healing operations | Config operations | Top operations | IAM operations | Misc |
+|:----------------------------|:----------------------------|:--------------------------------------|:--------------------------|:--------------------------|:------------------------------------|:------------------------------------|
+| [`ServiceStatus`](#ServiceStatus) | [`ServerInfo`](#ServerInfo) | [`Heal`](#Heal) | [`GetConfig`](#GetConfig) | [`TopLocks`](#TopLocks) | [`AddUser`](#AddUser) | [`SetAdminCredentials`](#SetAdminCredentials) |
+| [`ServiceSendAction`](#ServiceSendAction) | [`ServerCPULoadInfo`](#ServerCPULoadInfo) | | [`SetConfig`](#SetConfig) | | [`SetUserPolicy`](#SetUserPolicy) | [`StartProfiling`](#StartProfiling) |
+| |[`ServerMemUsageInfo`](#ServerMemUsageInfo) | | [`GetConfigKeys`](#GetConfigKeys) | | [`ListUsers`](#ListUsers) | [`DownloadProfilingData`](#DownloadProfilingData) |
+| | | | [`SetConfigKeys`](#SetConfigKeys) | | [`AddCannedPolicy`](#AddCannedPolicy) | |
## 1. Constructor
@@ -204,6 +204,57 @@ Fetches information for all cluster nodes, such as server properties, storage in
```
+
+### ServerDrivesPerfInfo() ([]ServerDrivesPerfInfo, error)
+
+Fetches drive performance information for all cluster nodes. Returned value is in Bytes/s.
+
+| Param | Type | Description |
+|---|---|---|
+|`di.Addr` | _string_ | Address of the server the following information is retrieved from. |
+|`di.Error` | _string _ | Errors (if any) encountered while reaching this node |
+|`di.DrivesPerf` | _disk.Performance_ | Path of the drive mount on above server and read, write speed. |
+
+| Param | Type | Description |
+|---|---|---|
+|`disk.Performance.Path` | _string_ | Path of drive mount. |
+|`disk.Performance.Error` | _string_ | Error (if any) encountered while accessing this drive. |
+|`disk.Performance.WriteSpeed` | _float64_ | Write speed on above path in Bytes/s. |
+|`disk.Performance.ReadSpeed` | _float64_ | Read speed on above path in Bytes/s. |
+
+
+### ServerCPULoadInfo() ([]ServerCPULoadInfo, error)
+
+Fetches CPU utilization for all cluster nodes. Returned value is in Bytes.
+
+| Param | Type | Description |
+|-------|------|-------------|
+|`cpui.Addr` | _string_ | Address of the server the following information is retrieved from. |
+|`cpui.Error` | _string_ | Errors (if any) encountered while reaching this node |
+|`cpui.CPULoad` | _cpu.Load_ | The load on the CPU. |
+
+| Param | Type | Description |
+|-------|------|-------------|
+|`cpu.Load.Avg` | _string_ | The average utilization % of the CPU measured in a 200ms interval |
+|`cpu.Load.Min` | _string_ | The minimum utilization % of the CPU measured in a 200ms interval |
+|`cpu.Load.Max` | _string_ | The maximum utilization % of the CPU measured in a 200ms interval |
+|`cpu.Load.Error` | _string_ | Error (if any) encountered while accesing the CPU info |
+
+
+### ServerMemUsageInfo() ([]ServerMemUsageInfo, error)
+
+Fetches Mem utilization for all cluster nodes. Returned value is in Bytes.
+
+| Param | Type | Description |
+|-------|------|-------------|
+|`memi.Addr` | _string_ | Address of the server the following information is retrieved from. |
+|`memi.Error` | _string_ | Errors (if any) encountered while reaching this node |
+|`memi.MemUsage` | _mem.Usage_ | The utilitzation of Memory |
+
+| Param | Type | Description |
+|-------|------|-------------|
+|`mem.Usage.Mem` | _string_ | The total number of bytes obtained from the OS |
+|`mem.Usage.Error` | _string_ | Error (if any) encountered while accesing the CPU info |
## 6. Heal operations
@@ -348,7 +399,29 @@ __Example__
log.Println("New configuration successfully set")
```
-## 8. IAM operations
+## 8. Top operations
+
+
+### TopLocks() (LockEntries, error)
+Get the oldest locks from Minio server.
+
+__Example__
+
+``` go
+ locks, err := madmClnt.TopLocks()
+ if err != nil {
+ log.Fatalf("failed due to: %v", err)
+ }
+
+ out, err := json.Marshal(locks)
+ if err != nil {
+ log.Fatalf("Marshal failed due to: %v", err)
+ }
+
+ log.Println("TopLocks received successfully: ", string(out))
+```
+
+## 9. IAM operations
### AddCannedPolicy(policyName string, policy string) error
@@ -404,7 +477,7 @@ __Example__
}
```
-## 9. Misc operations
+## 10. Misc operations
### SetAdminCredentials() error
diff --git a/vendor/github.com/minio/minio/pkg/madmin/info-commands.go b/vendor/github.com/minio/minio/pkg/madmin/info-commands.go
index 1a0d71af..b3968117 100644
--- a/vendor/github.com/minio/minio/pkg/madmin/info-commands.go
+++ b/vendor/github.com/minio/minio/pkg/madmin/info-commands.go
@@ -21,7 +21,12 @@ import (
"encoding/json"
"io/ioutil"
"net/http"
+ "net/url"
"time"
+
+ "github.com/minio/minio/pkg/cpu"
+ "github.com/minio/minio/pkg/disk"
+ "github.com/minio/minio/pkg/mem"
)
// BackendType - represents different backend types.
@@ -147,3 +152,132 @@ func (adm *AdminClient) ServerInfo() ([]ServerInfo, error) {
return serversInfo, nil
}
+
+// ServerDrivesPerfInfo holds informantion about address and write speed of
+// all drives in a single server node
+type ServerDrivesPerfInfo struct {
+ Addr string `json:"addr"`
+ Error string `json:"error,omitempty"`
+ Perf []disk.Performance `json:"perf"`
+}
+
+// ServerDrivesPerfInfo - Returns drive's read and write performance information
+func (adm *AdminClient) ServerDrivesPerfInfo() ([]ServerDrivesPerfInfo, error) {
+ v := url.Values{}
+ v.Set("perfType", string("drive"))
+ resp, err := adm.executeMethod("GET", requestData{
+ relPath: "/v1/performance",
+ queryValues: v,
+ })
+
+ defer closeResponse(resp)
+ if err != nil {
+ return nil, err
+ }
+
+ // Check response http status code
+ if resp.StatusCode != http.StatusOK {
+ return nil, httpRespToErrorResponse(resp)
+ }
+
+ // Unmarshal the server's json response
+ var info []ServerDrivesPerfInfo
+
+ respBytes, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ err = json.Unmarshal(respBytes, &info)
+ if err != nil {
+ return nil, err
+ }
+
+ return info, nil
+}
+
+// ServerCPULoadInfo holds information about address and cpu load of
+// a single server node
+type ServerCPULoadInfo struct {
+ Addr string `json:"addr"`
+ Error string `json:"error,omitempty"`
+ Load []cpu.Load `json:"load"`
+}
+
+// ServerCPULoadInfo - Returns cpu utilization information
+func (adm *AdminClient) ServerCPULoadInfo() ([]ServerCPULoadInfo, error) {
+ v := url.Values{}
+ v.Set("perfType", string("cpu"))
+ resp, err := adm.executeMethod("GET", requestData{
+ relPath: "/v1/performance",
+ queryValues: v,
+ })
+
+ defer closeResponse(resp)
+ if err != nil {
+ return nil, err
+ }
+
+ // Check response http status code
+ if resp.StatusCode != http.StatusOK {
+ return nil, httpRespToErrorResponse(resp)
+ }
+
+ // Unmarshal the server's json response
+ var info []ServerCPULoadInfo
+
+ respBytes, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ err = json.Unmarshal(respBytes, &info)
+ if err != nil {
+ return nil, err
+ }
+
+ return info, nil
+}
+
+// ServerMemUsageInfo holds information about address and memory utilization of
+// a single server node
+type ServerMemUsageInfo struct {
+ Addr string `json:"addr"`
+ Error string `json:"error,omitempty"`
+ Usage []mem.Usage `json:"usage"`
+}
+
+// ServerMemUsageInfo - Returns mem utilization information
+func (adm *AdminClient) ServerMemUsageInfo() ([]ServerMemUsageInfo, error) {
+ v := url.Values{}
+ v.Set("perfType", string("mem"))
+ resp, err := adm.executeMethod("GET", requestData{
+ relPath: "/v1/performance",
+ queryValues: v,
+ })
+
+ defer closeResponse(resp)
+ if err != nil {
+ return nil, err
+ }
+
+ // Check response http status code
+ if resp.StatusCode != http.StatusOK {
+ return nil, httpRespToErrorResponse(resp)
+ }
+
+ // Unmarshal the server's json response
+ var info []ServerMemUsageInfo
+
+ respBytes, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ err = json.Unmarshal(respBytes, &info)
+ if err != nil {
+ return nil, err
+ }
+
+ return info, nil
+}
diff --git a/vendor/github.com/minio/minio/pkg/madmin/top-commands.go b/vendor/github.com/minio/minio/pkg/madmin/top-commands.go
new file mode 100644
index 00000000..29cffe3f
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/madmin/top-commands.go
@@ -0,0 +1,78 @@
+/*
+ * Minio Cloud Storage, (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 madmin
+
+import (
+ "encoding/json"
+ "io/ioutil"
+ "net/http"
+ "time"
+)
+
+// LockEntry holds information about client requesting the lock,
+// servers holding the lock, source on the client machine,
+// ID, type(read or write) and time stamp.
+type LockEntry struct {
+ Timestamp time.Time `json:"time"` // Timestamp set at the time of initialization.
+ Resource string `json:"resource"` // Resource contains info like bucket, object etc
+ Type string `json:"type"` // Bool whether write or read lock.
+ Source string `json:"source"` // Source which created the lock
+ ServerList []string `json:"serverlist"` // RPC path of servers issuing the lock.
+ Owner string `json:"owner"` // RPC path of client claiming lock.
+ ID string `json:"id"` // UID to uniquely identify request of client.
+}
+
+// LockEntries - To sort the locks
+type LockEntries []LockEntry
+
+func (l LockEntries) Len() int {
+ return len(l)
+}
+
+func (l LockEntries) Less(i, j int) bool {
+ return l[i].Timestamp.Before(l[j].Timestamp)
+}
+
+func (l LockEntries) Swap(i, j int) {
+ l[i], l[j] = l[j], l[i]
+}
+
+// TopLocks - returns the oldest locks in a minio setup.
+func (adm *AdminClient) TopLocks() (LockEntries, error) {
+ // Execute GET on /minio/admin/v1/top/locks
+ // to get the oldest locks in a minio setup.
+ resp, err := adm.executeMethod("GET",
+ requestData{relPath: "/v1/top/locks"})
+ defer closeResponse(resp)
+ if err != nil {
+ return nil, err
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, httpRespToErrorResponse(resp)
+ }
+
+ response, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return LockEntries{}, err
+ }
+
+ var lockEntries LockEntries
+ err = json.Unmarshal(response, &lockEntries)
+ return lockEntries, err
+}
diff --git a/vendor/github.com/minio/minio/pkg/madmin/user-commands.go b/vendor/github.com/minio/minio/pkg/madmin/user-commands.go
index a413f7d6..336e905f 100644
--- a/vendor/github.com/minio/minio/pkg/madmin/user-commands.go
+++ b/vendor/github.com/minio/minio/pkg/madmin/user-commands.go
@@ -21,6 +21,8 @@ import (
"encoding/json"
"net/http"
"net/url"
+
+ "github.com/minio/minio/pkg/auth"
)
// AccountStatus - account status.
@@ -97,6 +99,15 @@ func (adm *AdminClient) ListUsers() (map[string]UserInfo, error) {
// SetUser - sets a user info.
func (adm *AdminClient) SetUser(accessKey, secretKey string, status AccountStatus) error {
+
+ if !auth.IsAccessKeyValid(accessKey) {
+ return auth.ErrInvalidAccessKeyLength
+ }
+
+ if !auth.IsSecretKeyValid(secretKey) {
+ return auth.ErrInvalidSecretKeyLength
+ }
+
data, err := json.Marshal(UserInfo{
SecretKey: secretKey,
Status: status,
diff --git a/vendor/github.com/minio/minio/pkg/mem/mem.go b/vendor/github.com/minio/minio/pkg/mem/mem.go
new file mode 100644
index 00000000..95357d62
--- /dev/null
+++ b/vendor/github.com/minio/minio/pkg/mem/mem.go
@@ -0,0 +1,39 @@
+/*
+ * Minio Cloud Storage, (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 mem
+
+import (
+ "runtime"
+
+ humanize "github.com/dustin/go-humanize"
+)
+
+// Usage holds memory utilization information in human readable format
+type Usage struct {
+ Mem string `json:"mem"`
+ Error string `json:"error,omitempty"`
+}
+
+// GetUsage measures the total memory provisioned for the current process
+// from the OS
+func GetUsage() Usage {
+ memStats := new(runtime.MemStats)
+ runtime.ReadMemStats(memStats)
+ return Usage{
+ Mem: humanize.IBytes(memStats.Sys),
+ }
+}
diff --git a/vendor/vendor.json b/vendor/vendor.json
index c0f07ead..4e4a58a0 100644
--- a/vendor/vendor.json
+++ b/vendor/vendor.json
@@ -44,6 +44,12 @@
"revision": "e214231b295a8ea9479f11b70b35d5acf3556d9b",
"revisionTime": "2018-01-08T23:09:05Z"
},
+ {
+ "checksumSHA1": "blOHP3HPYU+IeV6yWCalQuuM+zE=",
+ "path": "github.com/dgrijalva/jwt-go",
+ "revision": "3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8",
+ "revisionTime": "2018-09-21T17:23:15Z"
+ },
{
"path": "github.com/dustin/go-humanize",
"revision": "1c212aae1d02984808182b98b0da7a3e07e4c770",
@@ -153,10 +159,28 @@
"revisionTime": "2019-01-24T10:19:12Z"
},
{
- "checksumSHA1": "g8YlJVY8CHJy+N4pAF1522n/Yr8=",
+ "checksumSHA1": "vqWf9FPX+6SLfJCL66rLKKHVco8=",
+ "path": "github.com/minio/minio/pkg/auth",
+ "revision": "ce870466ff5db524e5f6c54b97eb0b26d9fcdf46",
+ "revisionTime": "2019-01-24T15:22:14Z"
+ },
+ {
+ "checksumSHA1": "uY4P8FoN5LsB1/ro6mv1twStP3k=",
+ "path": "github.com/minio/minio/pkg/cpu",
+ "revision": "ce870466ff5db524e5f6c54b97eb0b26d9fcdf46",
+ "revisionTime": "2019-01-24T15:22:14Z"
+ },
+ {
+ "checksumSHA1": "EELmZW4tgqdBTjjbxasCP/pfV6k=",
+ "path": "github.com/minio/minio/pkg/disk",
+ "revision": "ce870466ff5db524e5f6c54b97eb0b26d9fcdf46",
+ "revisionTime": "2019-01-24T15:22:14Z"
+ },
+ {
+ "checksumSHA1": "Qocnf0xycWqutHFLzxrG7vD1R70=",
"path": "github.com/minio/minio/pkg/madmin",
- "revision": "86f6ca3cea734ba0bd320e8279e90c6025460b0f",
- "revisionTime": "2018-10-27T02:40:32Z"
+ "revision": "ce870466ff5db524e5f6c54b97eb0b26d9fcdf46",
+ "revisionTime": "2019-01-24T15:22:14Z"
},
{
"checksumSHA1": "flg07CqTxM9togozKRQiJugao4s=",
@@ -164,6 +188,12 @@
"revision": "7b274cb618deef62a8f5df2761f2d8431ed71ca7",
"revisionTime": "2018-05-22T01:58:01Z"
},
+ {
+ "checksumSHA1": "qGGJQJ1AGA4yjLGGRVfKY3YWf3Q=",
+ "path": "github.com/minio/minio/pkg/mem",
+ "revision": "ce870466ff5db524e5f6c54b97eb0b26d9fcdf46",
+ "revisionTime": "2019-01-24T15:22:14Z"
+ },
{
"checksumSHA1": "Twe2beSe125vyX6Jx+q01YdOxyk=",
"path": "github.com/minio/minio/pkg/mimedb",