Refactor methods that initialize client to reuse code blocks (#4755)

This commit is contained in:
Pedro Juarez
2023-11-15 13:20:52 -08:00
committed by GitHub
parent c3ebf165ee
commit 6c9cdc27bc
2 changed files with 144 additions and 200 deletions
+7 -104
View File
@@ -20,22 +20,15 @@ package cmd
import (
"crypto/tls"
"fmt"
"hash/fnv"
"net"
"net/http"
"net/url"
"os"
"sync"
"time"
"github.com/klauspost/compress/gzhttp"
"github.com/minio/pkg/v2/env"
"github.com/mattn/go-ieproxy"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/limiter"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/credentials"
)
@@ -52,19 +45,11 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
if e != nil {
return nil, probe.NewError(e)
}
// By default enable HTTPs.
useTLS := true
if targetURL.Scheme == "http" {
useTLS = false
}
// Save if target supports virtual host style.
hostName := targetURL.Host
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
confSum := confHash.Sum32()
confSum := getConfigHash(config)
useTLS := isHostTLS(config)
// Lookup previous cache by hash.
mutex.Lock()
@@ -73,95 +58,13 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
var found bool
if api, found = clientCache[confSum]; !found {
var transport http.RoundTripper
transport := getTransportForConfig(config, true)
if config.Transport != nil {
transport = config.Transport
} else {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(config),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
DisableCompression: true,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
}
if useTLS {
// Keep TLS config.
tlsConfig := &tls.Config{
RootCAs: globalRootCAs,
// Can't use SSLv3 because of POODLE and BEAST
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
// Can't use TLSv1.1 because of RC4 cipher usage
MinVersion: tls.VersionTLS12,
}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
tr.TLSClientConfig = tlsConfig
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
// See https://github.com/golang/go/issues/14275
//
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
//
// if e = http2.ConfigureTransport(tr); e != nil {
// return nil, probe.NewError(e)
// }
}
transport = tr
credsChain, err := getCredentialsChainForConfig(config, transport)
if err != nil {
return nil, err
}
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
if config.Debug {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
}
transport = gzhttp.Transport(transport)
var credsChain []credentials.Provider
// if an STS endpoint is set, we will add that to the chain
if stsEndpoint := env.Get("MC_STS_ENDPOINT", ""); stsEndpoint != "" {
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE", ""); val != "" {
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
}
stsEndpointURL, err := url.Parse(stsEndpoint)
if err != nil {
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %v", err))
}
credsSts := &credentials.IAM{
Client: &http.Client{
Transport: transport,
},
Endpoint: stsEndpointURL.String(),
}
credsChain = append(credsChain, credsSts)
}
// V4 Credentials
credsV4 := &credentials.Static{
Value: credentials.Value{
AccessKeyID: config.AccessKey,
SecretAccessKey: config.SecretKey,
SessionToken: config.SessionToken,
SignerType: credentials.SignatureV4,
},
}
credsChain = append(credsChain, credsV4)
// Admin API only supports signature v4.
creds := credentials.NewChainCredentials(credsChain)
// Not found. Instantiate a new MinIO
+137 -96
View File
@@ -38,6 +38,7 @@ import (
"sync"
"time"
"github.com/klauspost/compress/gzhttp"
"github.com/minio/pkg/v2/env"
"github.com/minio/minio-go/v7"
@@ -117,6 +118,135 @@ func newCustomDialContext(c *Config) dialContext {
var timeSentinel = time.Unix(0, 0).UTC()
// getConfigHash returns the Hash for che *Config
func getConfigHash(config *Config) uint32 {
// Creates a parsed URL.
targetURL := newClientURL(config.HostURL)
// Save if target supports virtual host style.
hostName := targetURL.Host
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey + config.SessionToken))
confSum := confHash.Sum32()
return confSum
}
// isHostTLS returns true if the Host URL is https
func isHostTLS(config *Config) bool {
// By default enable HTTPs.
useTLS := true
targetURL := newClientURL(config.HostURL)
if targetURL.Scheme == "http" {
useTLS = false
}
return useTLS
}
// getTransportForConfig returns a corresponding *http.Transport for the *Config
// set withS3v2 bool to true to add traceV2 tracer.
func getTransportForConfig(config *Config, withS3v2 bool) http.RoundTripper {
var transport http.RoundTripper
useTLS := isHostTLS(config)
if config.Transport != nil {
transport = config.Transport
} else {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(config),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
DisableCompression: true,
}
if useTLS {
// Keep TLS config.
tlsConfig := &tls.Config{
RootCAs: globalRootCAs,
// Can't use SSLv3 because of POODLE and BEAST
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
// Can't use TLSv1.1 because of RC4 cipher usage
MinVersion: tls.VersionTLS12,
}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
tr.TLSClientConfig = tlsConfig
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
// See https://github.com/golang/go/issues/14275
//
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
//
// if e = http2.ConfigureTransport(tr); e != nil {
// return nil, probe.NewError(e)
// }
}
transport = tr
}
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
if config.Debug {
if strings.EqualFold(config.Signature, "S3v4") {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
} else if strings.EqualFold(config.Signature, "S3v2") && withS3v2 {
transport = httptracer.GetNewTraceTransport(newTraceV2(), transport)
}
}
transport = gzhttp.Transport(transport)
return transport
}
// getCredentialsChainForConfig returns an []credentials.Provider array for the config
// and the STS configuration (if present)
func getCredentialsChainForConfig(config *Config, transport http.RoundTripper) ([]credentials.Provider, *probe.Error) {
var credsChain []credentials.Provider
// if an STS endpoint is set, we will add that to the chain
if stsEndpoint := env.Get("MC_STS_ENDPOINT", ""); stsEndpoint != "" {
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE", ""); val != "" {
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
}
stsEndpointURL, err := url.Parse(stsEndpoint)
if err != nil {
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %v", err))
}
credsSts := &credentials.IAM{
Client: &http.Client{
Transport: transport,
},
Endpoint: stsEndpointURL.String(),
}
credsChain = append(credsChain, credsSts)
}
// V4 Credentials
credsV4 := &credentials.Static{
Value: credentials.Value{
AccessKeyID: config.AccessKey,
SecretAccessKey: config.SecretKey,
SessionToken: config.SessionToken,
SignerType: credentials.SignatureV4,
},
}
credsChain = append(credsChain, credsV4)
return credsChain, nil
}
// newFactory encloses New function with client cache.
func newFactory() func(config *Config) (Client, *probe.Error) {
clientCache := make(map[uint32]*minio.Client)
@@ -126,19 +256,13 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
return func(config *Config) (Client, *probe.Error) {
// Creates a parsed URL.
targetURL := newClientURL(config.HostURL)
// By default enable HTTPs.
useTLS := true
if targetURL.Scheme == "http" {
useTLS = false
}
// Save if target supports virtual host style.
hostName := targetURL.Host
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey + config.SessionToken))
confSum := confHash.Sum32()
confSum := getConfigHash(config)
useTLS := isHostTLS(config)
// Instantiate s3
s3Clnt := &S3Client{}
@@ -162,96 +286,13 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
var found bool
if api, found = clientCache[confSum]; !found {
var transport http.RoundTripper
transport := getTransportForConfig(config, true)
if config.Transport != nil {
transport = config.Transport
} else {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(config),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
DisableCompression: true,
}
if useTLS {
// Keep TLS config.
tlsConfig := &tls.Config{
RootCAs: globalRootCAs,
// Can't use SSLv3 because of POODLE and BEAST
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
// Can't use TLSv1.1 because of RC4 cipher usage
MinVersion: tls.VersionTLS12,
}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
tr.TLSClientConfig = tlsConfig
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
// See https://github.com/golang/go/issues/14275
//
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
//
// if e = http2.ConfigureTransport(tr); e != nil {
// return nil, probe.NewError(e)
// }
}
transport = tr
credsChain, err := getCredentialsChainForConfig(config, transport)
if err != nil {
return nil, err
}
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
if config.Debug {
if strings.EqualFold(config.Signature, "S3v4") {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
} else if strings.EqualFold(config.Signature, "S3v2") {
transport = httptracer.GetNewTraceTransport(newTraceV2(), transport)
}
}
var credsChain []credentials.Provider
// if an STS endpoint is set, we will add that to the chain
if stsEndpoint := env.Get("MC_STS_ENDPOINT", ""); stsEndpoint != "" {
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE", ""); val != "" {
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
}
stsEndpointURL, err := url.Parse(stsEndpoint)
if err != nil {
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %v", err))
}
credsSts := &credentials.IAM{
Client: &http.Client{
Transport: transport,
},
Endpoint: stsEndpointURL.String(),
}
credsChain = append(credsChain, credsSts)
}
// V4 Credentials
credsV4 := &credentials.Static{
Value: credentials.Value{
AccessKeyID: config.AccessKey,
SecretAccessKey: config.SecretKey,
SessionToken: config.SessionToken,
SignerType: credentials.SignatureV4,
},
}
credsChain = append(credsChain, credsV4)
// V2 Credentials
credsV2 := &credentials.Static{
Value: credentials.Value{