Add register sub-command to mc admin subnet (#3808)
By default, it will run in `online` mode and try to register the cluster on subnet. If the subnet license is not available in minio/mc config, it will - ask the user for login credentials - use the credentials for authentication and call the registration api - get the license from response of the api and store it in config - use the stored license for any subsequent calls In case the user belongs to multiple organizations in subnet, they will be prompted to choose the appropriate organization from the list. If the client machine is in an airgapped environment, user can choose to use the `--offline` flag when running the command. In this case, it will - generate and print the registration token - ask the user to paste it in the subnet registration screen - accept the license generated by subnet and store it in config As part of this work, the `health` sub-command is also enhanced to: - run in `online` mode by default, which tries to upload the health report to subnet. Here the user will be prompted for subnet credentials (if license not available in config) _before_ generating the health report as it is a long running process. - support a new flag `--offline` which can be used when subnet is not reachable. When used, the health report will be generated in a local json.gz file, which can then be uploaded on subnet. The examples in help text of both the sub-commands are enhanced to list multiple use cases. When saving license to config, first preference is given to minio config. If the minio server supports the `subnet license` key, the license will be stored here. In case it is an older version of minio that doesn't support this key, then the license will be stored in mc host config.
This commit is contained in:
+76
-84
@@ -25,7 +25,6 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -45,7 +44,7 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
var adminHealthFlags = []cli.Flag{
|
||||
var adminHealthFlags = append([]cli.Flag{
|
||||
HealthDataTypeFlag{
|
||||
Name: "test",
|
||||
Usage: "choose health tests to run [" + fullOptions.String() + "]",
|
||||
@@ -61,36 +60,23 @@ var adminHealthFlags = []cli.Flag{
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "license",
|
||||
Usage: "Subnet license key",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "Cluster name to be saved in subnet on 1st upload",
|
||||
Usage: "SUBNET license key",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "schedule",
|
||||
Usage: "Schedule of uploading to subnet in no of days",
|
||||
Usage: "Schedule automatic generation and upload of health reports to SUBNET based on the specified number of days (e.g. --schedule 2 is every 2 days)",
|
||||
Value: 0,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "subnet-proxy",
|
||||
Usage: "HTTP(S) proxy URL to be used along with license flag",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dev",
|
||||
Usage: "Development mode",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "full",
|
||||
Usage: "Include long running tests (takes longer to generate the report)",
|
||||
Hidden: false,
|
||||
},
|
||||
}
|
||||
}, subnetCommonFlags...)
|
||||
|
||||
var adminSubnetHealthCmd = cli.Command{
|
||||
Name: "health",
|
||||
Usage: "run health check for Subnet",
|
||||
Usage: "run health check for SUBNET",
|
||||
OnUsageError: onUsageError,
|
||||
Action: mainAdminHealth,
|
||||
Before: setGlobalsFromContext,
|
||||
@@ -105,8 +91,14 @@ FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get server information of the 'play' MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} play/
|
||||
1. Upload health diagnostics for the MinIO cluster with alias 'play' (https://play.min.io by default) to SUBNET
|
||||
{{.Prompt}} {{.HelpName}} play
|
||||
2. Upload health diagnostics for the MinIO cluster with alias 'play' (https://play.min.io by default) to SUBNET using the proxy https://192.168.1.3:3128
|
||||
{{.Prompt}} {{.HelpName}} play --subnet-proxy https://192.168.1.3:3128
|
||||
3. Periodically upload health diagnostics for the MinIO cluster with alias 'play' (https://play.min.io by default) to SUBNET every 2 days
|
||||
{{.Prompt}} {{.HelpName}} play --schedule 2
|
||||
4. Generate health diagnostics report for the MinIO cluster with alias 'play' (https://play.min.io by default) to and output them to the current working directory
|
||||
{{.Prompt}} {{.HelpName}} play --offline
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -177,24 +169,28 @@ func mainAdminHealth(ctx *cli.Context) error {
|
||||
|
||||
// Get the alias parameter from cli
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
alias, _ := url2Alias(aliasedURL)
|
||||
|
||||
license, schedule, dev, name := fetchSubnetUploadFlags(ctx)
|
||||
license, schedule, name, offline := fetchSubnetUploadFlags(ctx)
|
||||
|
||||
uploadToSubnet := !offline
|
||||
if uploadToSubnet && !subnetReachable() {
|
||||
console.Fatalln(subnetNotReachableMsg())
|
||||
}
|
||||
|
||||
uploadToSubnet := len(license) > 0
|
||||
uploadPeriodically := schedule != 0
|
||||
|
||||
e := validateFlags(uploadToSubnet, uploadPeriodically, dev, name)
|
||||
e := validateFlags(uploadToSubnet, uploadPeriodically, name)
|
||||
fatalIf(probe.NewError(e), "Invalid flags.")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
client := getClient(aliasedURL)
|
||||
|
||||
if len(name) == 0 {
|
||||
name = aliasedURL
|
||||
name = alias
|
||||
}
|
||||
// Main execution
|
||||
execAdminHealth(ctx, client, aliasedURL, license, name, dev)
|
||||
execAdminHealth(ctx, client, alias, license, name, uploadToSubnet)
|
||||
|
||||
if uploadToSubnet && uploadPeriodically {
|
||||
// Periodic upload to subnet
|
||||
@@ -202,33 +198,33 @@ func mainAdminHealth(ctx *cli.Context) error {
|
||||
sleepDuration := time.Hour * 24 * time.Duration(schedule)
|
||||
console.Infoln("Waiting for", sleepDuration, "before running health diagnostics again.")
|
||||
time.Sleep(sleepDuration)
|
||||
execAdminHealth(ctx, client, aliasedURL, license, name, dev)
|
||||
execAdminHealth(ctx, client, alias, license, name, uploadToSubnet)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fetchSubnetUploadFlags(ctx *cli.Context) (string, int, bool, string) {
|
||||
func fetchSubnetUploadFlags(ctx *cli.Context) (string, int, string, bool) {
|
||||
// license flag is passed when the health data
|
||||
// is to be uploadeD to Subnet
|
||||
// is to be uploadeD to SUBNET
|
||||
license := ctx.String("license")
|
||||
|
||||
// non-zero schedule means that health diagnostics
|
||||
// are to be run periodically and uploaded to subnet
|
||||
schedule := ctx.Int("schedule")
|
||||
|
||||
// If set (along with --license), the health data will
|
||||
// be uploaded to a local (devenv) subnet server
|
||||
dev := ctx.Bool("dev")
|
||||
|
||||
// If set (along with --license), this will be passed to
|
||||
// subnet as the name of the cluster
|
||||
name := ctx.String("name")
|
||||
|
||||
return license, schedule, dev, name
|
||||
// If set, the health report file will not be uploaded
|
||||
// to subnet and will only be saved locally.
|
||||
offline := ctx.Bool("offline")
|
||||
|
||||
return license, schedule, name, offline
|
||||
}
|
||||
|
||||
func validateFlags(uploadToSubnet bool, uploadPeriodically bool, dev bool, name string) error {
|
||||
func validateFlags(uploadToSubnet bool, uploadPeriodically bool, name string) error {
|
||||
if uploadToSubnet {
|
||||
if globalJSON {
|
||||
return errors.New("--json and --license should not be passed together")
|
||||
@@ -236,8 +232,8 @@ func validateFlags(uploadToSubnet bool, uploadPeriodically bool, dev bool, name
|
||||
return nil
|
||||
}
|
||||
|
||||
if dev {
|
||||
return errors.New("--dev is applicable only when --license is also passed")
|
||||
if globalDevMode {
|
||||
return errors.New("--dev is not applicable in offline mode")
|
||||
}
|
||||
|
||||
if uploadPeriodically {
|
||||
@@ -251,7 +247,17 @@ func validateFlags(uploadToSubnet bool, uploadPeriodically bool, dev bool, name
|
||||
return nil
|
||||
}
|
||||
|
||||
func execAdminHealth(ctx *cli.Context, client *madmin.AdminClient, aliasedURL string, license string, clusterName string, dev bool) {
|
||||
func execAdminHealth(ctx *cli.Context, client *madmin.AdminClient, alias string, license string, clusterName string, uploadToSubnet bool) {
|
||||
var reqURL string
|
||||
var headers map[string]string
|
||||
|
||||
filename := fmt.Sprintf("%s-health_%s.json.gz", filepath.Clean(alias), UTCNow().Format("20060102150405"))
|
||||
if uploadToSubnet {
|
||||
// Retrieve subnet credentials (login/license) beforehand as
|
||||
// it can take a long time to fetch the health information
|
||||
reqURL, headers = prepareHealthUploadURL(alias, clusterName, filename, license)
|
||||
}
|
||||
|
||||
healthInfo, version, e := fetchServerHealthInfo(ctx, client)
|
||||
fatalIf(probe.NewError(e), "Unable to fetch health information.")
|
||||
|
||||
@@ -265,79 +271,65 @@ func execAdminHealth(ctx *cli.Context, client *madmin.AdminClient, aliasedURL st
|
||||
return
|
||||
}
|
||||
|
||||
uploadToSubnet := len(license) > 0
|
||||
filename := fmt.Sprintf("%s-health_%s.json.gz", filepath.Clean(aliasedURL), UTCNow().Format("20060102150405"))
|
||||
e = tarGZ(healthInfo, version, filename, !uploadToSubnet)
|
||||
fatalIf(probe.NewError(e), "Unable to create health report file")
|
||||
|
||||
if uploadToSubnet {
|
||||
var proxyURL *url.URL
|
||||
if value := ctx.String("subnet-proxy"); value != "" {
|
||||
proxyURL, e = url.Parse(value)
|
||||
fatalIf(probe.NewError(e), "Unable to parse subnet-proxy flag")
|
||||
}
|
||||
|
||||
e = uploadHealthReport(aliasedURL, clusterName, filename, license, dev, proxyURL)
|
||||
e = uploadHealthReport(alias, filename, reqURL, headers)
|
||||
if e == nil {
|
||||
// Delete the report after successful upload
|
||||
deleteFile(filename)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to upload health report to Subnet portal")
|
||||
fatalIf(probe.NewError(e), "Unable to upload health report to SUBNET portal")
|
||||
}
|
||||
}
|
||||
|
||||
func uploadHealthReport(alias string, clusterName string, filename string, license string, dev bool, proxyURL *url.URL) error {
|
||||
func prepareHealthUploadURL(alias string, clusterName string, filename string, license string) (string, map[string]string) {
|
||||
if len(clusterName) == 0 {
|
||||
clusterName = alias
|
||||
}
|
||||
uploadURL := subnetUploadURL(clusterName, filename, license, dev)
|
||||
req, e := subnetUploadReq(uploadURL, filename)
|
||||
|
||||
uploadURL := subnetHealthUploadURL()
|
||||
|
||||
if len(license) == 0 {
|
||||
license = getSubnetLicenseFromConfig(alias)
|
||||
}
|
||||
|
||||
reqURL, headers, e := subnetURLWithAuth(uploadURL, license)
|
||||
fatalIf(probe.NewError(e), "Unable to get SUBNET auth")
|
||||
|
||||
reqURL = fmt.Sprintf("%s&clustername=%s&filename=%s", reqURL, clusterName, filename)
|
||||
return reqURL, headers
|
||||
}
|
||||
|
||||
func uploadHealthReport(alias string, filename string, reqURL string, headers map[string]string) error {
|
||||
req, e := subnetUploadReq(reqURL, filename)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
client := httpClient(10 * time.Second)
|
||||
if proxyURL != nil {
|
||||
client.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyURL)
|
||||
}
|
||||
resp, herr := client.Do(req)
|
||||
resp, herr := subnetExecReq(req, headers)
|
||||
if herr != nil {
|
||||
return herr
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody []byte
|
||||
respBody, e = ioutil.ReadAll(resp.Body)
|
||||
if e != nil {
|
||||
return e
|
||||
// extract license from response and set it in minio config
|
||||
subnetLic := gjson.Parse(resp).Get("license").String()
|
||||
if len(subnetLic) > 0 {
|
||||
setSubnetLicenseConfig(alias, subnetLic)
|
||||
}
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
msg := "MinIO Health data was successfully uploaded to Subnet."
|
||||
clusterURL, _ := url.PathUnescape(gjson.Get(string(respBody), "cluster_url").String())
|
||||
if len(clusterURL) > 0 {
|
||||
msg += fmt.Sprintf(" Can be viewed at: %s", clusterURL)
|
||||
}
|
||||
console.Infoln(msg)
|
||||
return nil
|
||||
msg := "MinIO Health data was successfully uploaded to SUBNET."
|
||||
clusterURL, _ := url.PathUnescape(gjson.Get(string(resp), "cluster_url").String())
|
||||
if len(clusterURL) > 0 {
|
||||
msg += fmt.Sprintf(" Can be viewed at: %s", clusterURL)
|
||||
}
|
||||
|
||||
return fmt.Errorf("Upload to subnet failed with status code %d: %s", resp.StatusCode, respBody)
|
||||
}
|
||||
|
||||
func subnetUploadURL(clusterName string, filename string, license string, dev bool) string {
|
||||
const apiPath = "/api/health/upload"
|
||||
baseURL := "https://subnet.min.io"
|
||||
if dev {
|
||||
baseURL = "http://localhost:9000"
|
||||
}
|
||||
url := fmt.Sprintf("%s%s?license=%s&clustername=%s&filename=%s", baseURL, apiPath, license, clusterName, filename)
|
||||
return url
|
||||
console.Infoln(msg)
|
||||
return nil
|
||||
}
|
||||
|
||||
func subnetUploadReq(url string, filename string) (*http.Request, error) {
|
||||
console.Println(infoText("Uploading health report to subnet"))
|
||||
|
||||
file, _ := os.Open(filename)
|
||||
defer file.Close()
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
var adminSubnetRegisterCmd = cli.Command{
|
||||
Name: "register",
|
||||
Usage: "Register the MinIO Cluster with SUBNET",
|
||||
OnUsageError: onUsageError,
|
||||
Action: mainAdminRegister,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(subnetCommonFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Register the MinIO cluster with alias 'play' to SUBNET, using the alias as the cluster name.
|
||||
{{.Prompt}} {{.HelpName}} play
|
||||
2. Register the MinIO cluster with alias 'play' to SUBNET using the name "play-cluster".
|
||||
{{.Prompt}} {{.HelpName}} play --name play-cluster
|
||||
3. Register the MinIO cluster with alias 'play' to SUBNET, using the proxy https://192.168.1.3:3128
|
||||
{{.Prompt}} {{.HelpName}} play --subnet-proxy https://192.168.1.3:3128
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminRegisterSyntax - validate arguments passed by a user
|
||||
func checkAdminRegisterSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "register", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// ClusterRegistrationReq - JSON payload of the subnet api for cluster registration
|
||||
// Contains a registration token created by base64 encoding of the registration info
|
||||
type ClusterRegistrationReq struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// ClusterRegistrationInfo - Information stored in the cluster registration token
|
||||
type ClusterRegistrationInfo struct {
|
||||
DeploymentID string `json:"deployment_id"`
|
||||
ClusterName string `json:"cluster_name"`
|
||||
UsedCapacity uint64 `json:"used_capacity"`
|
||||
Info ClusterInfo `json:"info"`
|
||||
}
|
||||
|
||||
// ClusterInfo - The "info" sub-node of the cluster registration information struct
|
||||
// Intended to be extensible i.e. more fields will be added as and when required
|
||||
type ClusterInfo struct {
|
||||
MinioVersion string `json:"minio_version"`
|
||||
NoOfServerPools int `json:"no_of_server_pools"`
|
||||
NoOfServers int `json:"no_of_servers"`
|
||||
NoOfDrives int `json:"no_of_drives"`
|
||||
NoOfBuckets uint64 `json:"no_of_buckets"`
|
||||
NoOfObjects uint64 `json:"no_of_objects"`
|
||||
TotalDriveSpace uint64 `json:"total_drive_space"`
|
||||
UsedDriveSpace uint64 `json:"used_drive_space"`
|
||||
}
|
||||
|
||||
// SubnetLoginReq - JSON payload of the SUBNET login api
|
||||
type SubnetLoginReq struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// SubnetMFAReq - JSON payload of the SUBNET mfa api
|
||||
type SubnetMFAReq struct {
|
||||
Username string `json:"username"`
|
||||
OTP string `json:"otp"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
func mainAdminRegister(ctx *cli.Context) error {
|
||||
checkAdminRegisterSyntax(ctx)
|
||||
|
||||
offlineMode := ctx.Bool(("offline"))
|
||||
if !offlineMode && !subnetReachable() {
|
||||
console.Fatalln(subnetNotReachableMsg())
|
||||
}
|
||||
|
||||
// Get the alias parameter from cli
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
alias, _ := url2Alias(aliasedURL)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client := getClient(aliasedURL)
|
||||
|
||||
// Fetch info of all servers (cluster or single server)
|
||||
admInfo, e := client.ServerInfo(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to fetch cluster info")
|
||||
|
||||
clusterName := ctx.String("name")
|
||||
if len(clusterName) == 0 {
|
||||
clusterName = alias
|
||||
}
|
||||
|
||||
regInfo := getClusterRegInfo(admInfo, clusterName)
|
||||
|
||||
if offlineMode {
|
||||
registerOffline(regInfo, alias)
|
||||
} else {
|
||||
registerOnline(regInfo, alias, clusterName)
|
||||
}
|
||||
|
||||
msg := fmt.Sprintln("Cluster", alias, "successfully registered on SUBNET.")
|
||||
console.Infoln(msg)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func registerOffline(clusterRegInfo ClusterRegistrationInfo, alias string) {
|
||||
regToken, e := generateRegToken(clusterRegInfo)
|
||||
fatalIf(probe.NewError(e), "Unable to generate registration token")
|
||||
|
||||
subnetRegisterPageURL := "https://subnet.min.io/cluster/register"
|
||||
|
||||
fmt.Print("The registration token for the cluster " + clusterRegInfo.ClusterName + ` is:
|
||||
|
||||
` + regToken + `
|
||||
|
||||
Please follow these steps to complete the registration:
|
||||
|
||||
1) Copy the registration token shown above
|
||||
2) Open ` + subnetRegisterPageURL + `
|
||||
3) Paste the registration token there and submit the form
|
||||
4) Copy the license string generated
|
||||
5) Paste it here: `)
|
||||
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
lic, e := reader.ReadString('\n')
|
||||
fatalIf(probe.NewError(e), "Error in reading license string")
|
||||
lic = strings.Trim(lic, "\n")
|
||||
|
||||
if len(lic) > 0 {
|
||||
e := verifySubnetLicense(lic)
|
||||
fatalIf(probe.NewError(e), "Invalid license specified:")
|
||||
setSubnetLicenseConfig(alias, lic)
|
||||
} else {
|
||||
console.Fatalln("Invalid license specified. Please run the command again with a valid SUBNET license to complete registration.")
|
||||
}
|
||||
}
|
||||
|
||||
func registerOnline(clusterRegInfo ClusterRegistrationInfo, alias string, clusterName string) {
|
||||
resp, e := registerClusterOnSubnet(alias, clusterRegInfo)
|
||||
fatalIf(probe.NewError(e), "Could not register cluster with SUBNET:")
|
||||
|
||||
// extract license from response and set it in minio config
|
||||
subnetLic := gjson.Parse(resp).Get("license").String()
|
||||
if len(subnetLic) > 0 {
|
||||
setSubnetLicenseConfig(alias, subnetLic)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -24,7 +24,7 @@ import (
|
||||
|
||||
var subnetHealthSubcommands = []cli.Command{
|
||||
adminSubnetHealthCmd,
|
||||
// adminSubnetRegister to be added
|
||||
adminSubnetRegisterCmd,
|
||||
}
|
||||
|
||||
var adminSubnetCmd = cli.Command{
|
||||
|
||||
@@ -370,7 +370,8 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/admin/kms/key/create": aliasCompleter,
|
||||
"/admin/kms/key/status": aliasCompleter,
|
||||
|
||||
"/admin/subnet/health": aliasCompleter,
|
||||
"/admin/subnet/health": aliasCompleter,
|
||||
"/admin/subnet/register": aliasCompleter,
|
||||
|
||||
"/admin/tier/add": nil,
|
||||
"/admin/tier/edit": nil,
|
||||
|
||||
@@ -44,6 +44,7 @@ type aliasConfigV10 struct {
|
||||
SessionToken string `json:"sessionToken,omitempty"`
|
||||
API string `json:"api"`
|
||||
Path string `json:"path"`
|
||||
License string `json:"license,omitempty"`
|
||||
}
|
||||
|
||||
// configV10 config version.
|
||||
|
||||
+26
-8
@@ -21,6 +21,7 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"net/url"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/pkg/console"
|
||||
@@ -55,12 +56,14 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
globalQuiet = false // Quiet flag set via command line
|
||||
globalJSON = false // Json flag set via command line
|
||||
globalJSONLine = false // Print json as single line.
|
||||
globalDebug = false // Debug flag set via command line
|
||||
globalNoColor = false // No Color flag set via command line
|
||||
globalInsecure = false // Insecure flag set via command line
|
||||
globalQuiet = false // Quiet flag set via command line
|
||||
globalJSON = false // Json flag set via command line
|
||||
globalJSONLine = false // Print json as single line.
|
||||
globalDebug = false // Debug flag set via command line
|
||||
globalNoColor = false // No Color flag set via command line
|
||||
globalInsecure = false // Insecure flag set via command line
|
||||
globalDevMode = false // dev flag set via command line
|
||||
globalSubnetProxyURL *url.URL // Proxy to be used for communication with subnet
|
||||
|
||||
globalContext, globalCancel = context.WithCancel(context.Background())
|
||||
)
|
||||
@@ -74,13 +77,15 @@ var (
|
||||
)
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobals(quiet, debug, json, noColor, insecure bool) {
|
||||
func setGlobals(quiet, debug, json, noColor, insecure, devMode bool, subnetProxyURL *url.URL) {
|
||||
globalQuiet = globalQuiet || quiet
|
||||
globalDebug = globalDebug || debug
|
||||
globalJSONLine = !isTerminal() && json
|
||||
globalJSON = globalJSON || json
|
||||
globalNoColor = globalNoColor || noColor || globalJSONLine
|
||||
globalInsecure = globalInsecure || insecure
|
||||
globalDevMode = globalDevMode || devMode
|
||||
globalSubnetProxyURL = subnetProxyURL
|
||||
|
||||
// Disable colorified messages if requested.
|
||||
if globalNoColor || globalQuiet {
|
||||
@@ -95,6 +100,19 @@ func setGlobalsFromContext(ctx *cli.Context) error {
|
||||
json := ctx.IsSet("json") || ctx.GlobalIsSet("json")
|
||||
noColor := ctx.IsSet("no-color") || ctx.GlobalIsSet("no-color")
|
||||
insecure := ctx.IsSet("insecure") || ctx.GlobalIsSet("insecure")
|
||||
setGlobals(quiet, debug, json, noColor, insecure)
|
||||
devMode := ctx.IsSet("dev") || ctx.GlobalIsSet("dev")
|
||||
|
||||
subnetProxy := ctx.String("subnet-proxy")
|
||||
|
||||
var proxyURL *url.URL
|
||||
var e error
|
||||
if value := ctx.String("subnet-proxy"); value != "" {
|
||||
proxyURL, e = url.Parse(subnetProxy)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
|
||||
setGlobals(quiet, debug, json, noColor, insecure, devMode, proxyURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/licverifier"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
)
|
||||
|
||||
const minioSubscriptionURL = "https://min.io/subscription"
|
||||
|
||||
var subnetCommonFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "Specify the name to associate to this MinIO cluster in SUBNET",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "subnet-proxy",
|
||||
Usage: "Specify the HTTP(S) proxy URL to use for connecting to SUBNET",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "offline",
|
||||
Usage: "Use in environments without network access to SUBNET (e.g. airgapped, firewalled, etc.)",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dev",
|
||||
Usage: "Development mode - talks to local SUBNET",
|
||||
Hidden: true,
|
||||
},
|
||||
}
|
||||
|
||||
func subnetBaseURL() string {
|
||||
if globalDevMode {
|
||||
return "http://localhost:9000"
|
||||
}
|
||||
|
||||
return "https://subnet.min.io"
|
||||
}
|
||||
|
||||
func subnetHealthUploadURL() string {
|
||||
return subnetBaseURL() + "/api/health/upload"
|
||||
}
|
||||
|
||||
func subnetRegisterURL() string {
|
||||
return subnetBaseURL() + "/api/cluster/register"
|
||||
}
|
||||
|
||||
func subnetLoginURL() string {
|
||||
return subnetBaseURL() + "/api/auth/login"
|
||||
}
|
||||
|
||||
func subnetOrgsURL() string {
|
||||
return subnetBaseURL() + "/api/auth/organizations"
|
||||
}
|
||||
|
||||
func subnetMFAURL() string {
|
||||
return subnetBaseURL() + "/api/auth/mfa-login"
|
||||
}
|
||||
|
||||
func urlReachable(url string) bool {
|
||||
r, e := http.Head(url)
|
||||
return e == nil && r.StatusCode == http.StatusOK
|
||||
}
|
||||
|
||||
func subnetReachable() bool {
|
||||
return urlReachable(subnetBaseURL())
|
||||
}
|
||||
|
||||
func subnetURLWithAuth(reqURL string, license string) (string, map[string]string, error) {
|
||||
headers := map[string]string{}
|
||||
if len(license) > 0 {
|
||||
// Add license in url for authentication
|
||||
reqURL = reqURL + "?license=" + license
|
||||
} else {
|
||||
// License not available in minio/mc config.
|
||||
// Ask the user to log in to get auth token
|
||||
token, e := subnetLogin()
|
||||
if e != nil {
|
||||
return "", nil, e
|
||||
}
|
||||
headers = subnetAuthHeaders(token)
|
||||
|
||||
accID, err := getSubnetAccID(headers)
|
||||
if err != nil {
|
||||
return "", headers, e
|
||||
}
|
||||
|
||||
reqURL = reqURL + "?aid=" + accID
|
||||
}
|
||||
return reqURL, headers, nil
|
||||
}
|
||||
|
||||
func subnetAuthHeaders(authToken string) map[string]string {
|
||||
return map[string]string{"Authorization": "Bearer " + authToken}
|
||||
}
|
||||
|
||||
func execReq(req *http.Request) (*http.Response, error) {
|
||||
client := httpClient(10 * time.Second)
|
||||
if globalSubnetProxyURL != nil {
|
||||
client.Transport.(*http.Transport).Proxy = http.ProxyURL(globalSubnetProxyURL)
|
||||
}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func subnetExecReq(r *http.Request, headers map[string]string) (string, error) {
|
||||
for k, v := range headers {
|
||||
r.Header.Add(k, v)
|
||||
}
|
||||
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if len(ct) == 0 {
|
||||
r.Header.Add("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
resp, e := execReq(r)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
respBytes, e := ioutil.ReadAll(io.LimitReader(resp.Body, resp.ContentLength))
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
respStr := string(respBytes)
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return respStr, nil
|
||||
}
|
||||
return respStr, fmt.Errorf("Request failed with code %d and error: %s", resp.StatusCode, respStr)
|
||||
}
|
||||
|
||||
func subnetGetReq(reqURL string, headers map[string]string) (string, error) {
|
||||
r, _ := http.NewRequest("GET", reqURL, nil)
|
||||
return subnetExecReq(r, headers)
|
||||
}
|
||||
|
||||
func subnetPostReq(reqURL string, payload interface{}, headers map[string]string) (string, error) {
|
||||
body, _ := json.Marshal(payload)
|
||||
r, e := http.NewRequest("POST", reqURL, bytes.NewBuffer(body))
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
return subnetExecReq(r, headers)
|
||||
}
|
||||
|
||||
func getSubnetLicenseFromConfig(alias string) string {
|
||||
client, err := newAdminClient(alias)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if minioConfigSupportsLicense(client) {
|
||||
sh, pe := client.HelpConfigKV(globalContext, "subnet", "license", false)
|
||||
fatalIf(probe.NewError(pe), "Unable to get config keys for SUBNET")
|
||||
|
||||
buf, e := client.GetConfigKV(globalContext, "subnet")
|
||||
fatalIf(probe.NewError(e), "Unable to get server SUBNET config")
|
||||
|
||||
tgt, e := madmin.ParseSubSysTarget(buf, sh)
|
||||
fatalIf(probe.NewError(e), "Unable to parse sub-system target 'subnet'")
|
||||
|
||||
lic := tgt.KVS.Get("license")
|
||||
if len(lic) > 0 {
|
||||
return lic
|
||||
}
|
||||
}
|
||||
|
||||
return mcConfig().Aliases[alias].License
|
||||
}
|
||||
|
||||
func mcConfig() *configV10 {
|
||||
loadMcConfig = loadMcConfigFactory()
|
||||
config, err := loadMcConfig()
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.")
|
||||
return config
|
||||
}
|
||||
|
||||
func minioConfigSupportsLicense(client *madmin.AdminClient) bool {
|
||||
help, e := client.HelpConfigKV(globalContext, "", "", false)
|
||||
fatalIf(probe.NewError(e), "Unable to get minio config keys")
|
||||
|
||||
for _, h := range help.KeysHelp {
|
||||
if h.Key == "subnet" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func setSubnetLicenseConfig(alias string, lic string) {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(alias)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if minioConfigSupportsLicense(client) {
|
||||
configStr := "subnet license=" + lic
|
||||
_, e := client.SetConfigKV(globalContext, configStr)
|
||||
fatalIf(probe.NewError(e), "Unable to set SUBNET license config on minio")
|
||||
return
|
||||
}
|
||||
mcCfg := mcConfig()
|
||||
aliasCfg := mcCfg.Aliases[alias]
|
||||
aliasCfg.License = lic
|
||||
setAlias(alias, aliasCfg)
|
||||
}
|
||||
|
||||
func getClusterRegInfo(admInfo madmin.InfoMessage, clusterName string) ClusterRegistrationInfo {
|
||||
noOfPools := 1
|
||||
noOfDrives := 0
|
||||
for _, srvr := range admInfo.Servers {
|
||||
if srvr.PoolNumber > noOfPools {
|
||||
noOfPools = srvr.PoolNumber
|
||||
}
|
||||
noOfDrives += len(srvr.Disks)
|
||||
}
|
||||
|
||||
totalSpace, usedSpace := getDriveSpaceInfo(admInfo)
|
||||
|
||||
return ClusterRegistrationInfo{
|
||||
DeploymentID: admInfo.DeploymentID,
|
||||
ClusterName: clusterName,
|
||||
UsedCapacity: admInfo.Usage.Size,
|
||||
Info: ClusterInfo{
|
||||
MinioVersion: admInfo.Servers[0].Version,
|
||||
NoOfServerPools: noOfPools,
|
||||
NoOfServers: len(admInfo.Servers),
|
||||
NoOfDrives: noOfDrives,
|
||||
TotalDriveSpace: totalSpace,
|
||||
UsedDriveSpace: usedSpace,
|
||||
NoOfBuckets: admInfo.Buckets.Count,
|
||||
NoOfObjects: admInfo.Objects.Count,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getDriveSpaceInfo(admInfo madmin.InfoMessage) (uint64, uint64) {
|
||||
total := uint64(0)
|
||||
used := uint64(0)
|
||||
for _, srvr := range admInfo.Servers {
|
||||
for _, d := range srvr.Disks {
|
||||
total += d.TotalSpace
|
||||
used += d.UsedSpace
|
||||
}
|
||||
}
|
||||
return total, used
|
||||
}
|
||||
|
||||
func generateRegToken(clusterRegInfo ClusterRegistrationInfo) (string, error) {
|
||||
token, e := json.Marshal(clusterRegInfo)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(token), nil
|
||||
}
|
||||
|
||||
func subnetLogin() (string, error) {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
fmt.Print("SUBNET username: ")
|
||||
username, _ := reader.ReadString('\n')
|
||||
username = strings.Trim(username, "\n")
|
||||
|
||||
if len(username) == 0 {
|
||||
return "", errors.New("Username cannot be empty. If you don't have one, please create one from here: " + minioSubscriptionURL)
|
||||
}
|
||||
|
||||
fmt.Print("Password: ")
|
||||
bytepw, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Println()
|
||||
|
||||
loginReq := map[string]string{
|
||||
"username": username,
|
||||
"password": string(bytepw),
|
||||
}
|
||||
respStr, e := subnetPostReq(subnetLoginURL(), loginReq, nil)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
|
||||
mfaRequired := gjson.Get(respStr, "mfa_required").Bool()
|
||||
if mfaRequired {
|
||||
mfaToken := gjson.Get(respStr, "mfa_token").String()
|
||||
fmt.Print("OTP received in email: ")
|
||||
byteotp, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Println()
|
||||
|
||||
mfaLoginReq := SubnetMFAReq{Username: username, OTP: string(byteotp), Token: mfaToken}
|
||||
respStr, e = subnetPostReq(subnetMFAURL(), mfaLoginReq, nil)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
}
|
||||
|
||||
token := gjson.Get(respStr, "token_info.access_token")
|
||||
if token.Exists() {
|
||||
return token.String(), nil
|
||||
}
|
||||
return "", fmt.Errorf("access token not found in response")
|
||||
}
|
||||
|
||||
func getSubnetAccID(headers map[string]string) (string, error) {
|
||||
respStr, e := subnetGetReq(subnetOrgsURL(), headers)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
data := gjson.Parse(respStr)
|
||||
orgs := data.Array()
|
||||
idx := 1
|
||||
if len(orgs) > 1 {
|
||||
fmt.Println("You are part of multiple organizations on SUBNET:")
|
||||
for idx, org := range orgs {
|
||||
fmt.Println(" ", idx+1, ":", org.Get("company"))
|
||||
}
|
||||
fmt.Print("Please choose the organization for this cluster: ")
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
accIdx, _ := reader.ReadString('\n')
|
||||
accIdx = strings.Trim(accIdx, "\n")
|
||||
idx, e = strconv.Atoi(accIdx)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
if idx > len(orgs) {
|
||||
msg := "Invalid choice for organization. Please run the command again."
|
||||
return "", fmt.Errorf(msg)
|
||||
}
|
||||
}
|
||||
return orgs[idx-1].Get("accountId").String(), nil
|
||||
}
|
||||
|
||||
// registerClusterOnSubnet - Registers the given cluster on SUBNET
|
||||
func registerClusterOnSubnet(alias string, clusterRegInfo ClusterRegistrationInfo) (string, error) {
|
||||
lic := getSubnetLicenseFromConfig(alias)
|
||||
|
||||
regURL, headers, e := subnetURLWithAuth(subnetRegisterURL(), lic)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
|
||||
regToken, e := generateRegToken(clusterRegInfo)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
|
||||
reqPayload := ClusterRegistrationReq{Token: regToken}
|
||||
return subnetPostReq(regURL, reqPayload, headers)
|
||||
}
|
||||
|
||||
func verifySubnetLicense(lic string) error {
|
||||
var pemBytes []byte
|
||||
if globalDevMode {
|
||||
pemBytes = []byte(`-----BEGIN PUBLIC KEY-----
|
||||
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEbo+e1wpBY4tBq9AONKww3Kq7m6QP/TBQ
|
||||
mr/cKCUyBL7rcAvg0zNq1vcSrUSGlAmY3SEDCu3GOKnjG/U4E7+p957ocWSV+mQU
|
||||
9NKlTdQFGF3+aO6jbQ4hX/S5qPyF+a3z
|
||||
-----END PUBLIC KEY-----`)
|
||||
} else {
|
||||
pemBytes = []byte(`-----BEGIN PUBLIC KEY-----
|
||||
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEaK31xujr6/rZ7ZfXZh3SlwovjC+X8wGq
|
||||
qkltaKyTLRENd4w3IRktYYCRgzpDLPn/nrf7snV/ERO5qcI7fkEES34IVEr+2Uff
|
||||
JkO2PfyyAYEO/5dBlPh1Undu9WQl6J7B
|
||||
-----END PUBLIC KEY-----`)
|
||||
}
|
||||
lv, e := licverifier.NewLicenseVerifier(pemBytes)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = lv.Verify(lic)
|
||||
return e
|
||||
}
|
||||
|
||||
func subnetNotReachableMsg() string {
|
||||
errMsg := "https://subnet.min.io is not reachable"
|
||||
if globalSubnetProxyURL != nil {
|
||||
errMsg += " using proxy " + globalSubnetProxyURL.String()
|
||||
}
|
||||
return errMsg
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSubnetBaseURL(t *testing.T) {
|
||||
sbu := subnetBaseURL()
|
||||
u, err := url.ParseRequestURI(sbu)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.Scheme != "https" {
|
||||
t.Fatalf("Expected TestSubnetBaseURL() to return an https url, received %s", u.Scheme)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user