Signed-off-by: Miloslav Trmač <mitr@redhat.com>
This commit is contained in:
Miloslav Trmač
2024-05-09 21:49:41 +02:00
parent dcf937e170
commit 7649059a0d
474 changed files with 30496 additions and 30923 deletions

View File

@@ -48,8 +48,7 @@ func (d *drainingReadCloser) Close() error {
// If the reader side (a HTTP server) is misbehaving, it still may send
// some bytes, but the closer ignores them to keep the underling
// connection open.
//nolint:errcheck
io.Copy(io.Discard, d.rdr)
_, _ = io.Copy(io.Discard, d.rdr)
}
return d.rdr.Close()
}

View File

@@ -11,7 +11,8 @@ import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"go.opentelemetry.io/otel/semconv/v1.17.0/httpconv"
"go.opentelemetry.io/otel/trace"
)
@@ -131,8 +132,11 @@ func (t *openTelemetryTransport) Submit(op *runtime.ClientOperation) (interface{
op.Reader = runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if span != nil {
statusCode := response.Code()
span.SetAttributes(attribute.Int(string(semconv.HTTPStatusCodeKey), statusCode))
span.SetStatus(semconv.SpanStatusFromHTTPStatusCodeAndSpanKind(statusCode, trace.SpanKindClient))
// NOTE: this is replaced by semconv.HTTPResponseStatusCode in semconv v1.21
span.SetAttributes(semconv.HTTPStatusCode(statusCode))
// NOTE: the conversion from HTTP status code to trace code is no longer available with
// semconv v1.21
span.SetStatus(httpconv.ServerStatus(statusCode))
}
return reader.ReadResponse(response, consumer)

View File

@@ -16,6 +16,7 @@ package client
import (
"bytes"
"context"
"fmt"
"io"
"log"
@@ -35,7 +36,7 @@ import (
)
// NewRequest creates a new swagger http client request
func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) (*request, error) {
func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) *request {
return &request{
pathPattern: pathPattern,
method: method,
@@ -44,7 +45,7 @@ func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter)
query: make(url.Values),
timeout: DefaultTimeout,
getBody: getRequestBuffer,
}, nil
}
}
// Request represents a swagger client request.
@@ -102,7 +103,7 @@ func logClose(err error, pw *io.PipeWriter) {
}
}
func (r *request) buildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) {
func (r *request) buildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) { //nolint:gocyclo,maintidx
// build the data
if err := r.writer.WriteToRequest(r, registry); err != nil {
return nil, err
@@ -170,7 +171,7 @@ func (r *request) buildHTTP(mediaType, basePath string, producers map[string]run
// Need to read the data so that we can detect the content type
buf := make([]byte, 512)
size, err := fi.Read(buf)
if err != nil {
if err != nil && err != io.EOF {
logClose(err, pw)
return
}
@@ -317,13 +318,13 @@ DoneChoosingBodySource:
urlPath := path.Join(basePathURL.Path, pathPatternURL.Path)
for k, v := range r.pathParams {
urlPath = strings.Replace(urlPath, "{"+k+"}", url.PathEscape(v), -1)
urlPath = strings.ReplaceAll(urlPath, "{"+k+"}", url.PathEscape(v))
}
if reinstateSlash {
urlPath = urlPath + "/"
urlPath += "/"
}
req, err := http.NewRequest(r.method, urlPath, body)
req, err := http.NewRequestWithContext(context.Background(), r.method, urlPath, body)
if err != nil {
return nil, err
}
@@ -361,7 +362,7 @@ func (r *request) GetMethod() string {
func (r *request) GetPath() string {
path := r.pathPattern
for k, v := range r.pathParams {
path = strings.Replace(path, "{"+k+"}", v, -1)
path = strings.ReplaceAll(path, "{"+k+"}", v)
}
return path
}

View File

@@ -22,6 +22,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"mime"
"net/http"
@@ -31,13 +32,18 @@ import (
"sync"
"time"
"github.com/go-openapi/strfmt"
"github.com/opentracing/opentracing-go"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/logger"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/runtime/yamlpc"
"github.com/go-openapi/strfmt"
)
const (
schemeHTTP = "http"
schemeHTTPS = "https"
)
// TLSClientOptions to configure client authentication with mutual TLS
@@ -70,7 +76,7 @@ type TLSClientOptions struct {
LoadedCA *x509.Certificate
// LoadedCAPool specifies a pool of RootCAs to use when validating the server's TLS certificate.
// If set, it will be combined with the the other loaded certificates (see LoadedCA and CA).
// If set, it will be combined with the other loaded certificates (see LoadedCA and CA).
// If neither LoadedCA or CA is set, the provided pool with override the system
// certificate pool.
// The caller must not use the supplied pool after calling TLSClientAuth.
@@ -112,7 +118,9 @@ type TLSClientOptions struct {
// TLSClientAuth creates a tls.Config for mutual auth
func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
// create client tls config
cfg := &tls.Config{}
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
}
// load client cert if specified
if opts.Certificate != "" {
@@ -136,7 +144,7 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
return nil, fmt.Errorf("tls client priv key: %v", err)
}
default:
return nil, fmt.Errorf("tls client priv key: unsupported key type")
return nil, errors.New("tls client priv key: unsupported key type")
}
block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes}
@@ -158,11 +166,12 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
// When no CA certificate is provided, default to the system cert pool
// that way when a request is made to a server known by the system trust store,
// the name is still verified
if opts.LoadedCA != nil {
switch {
case opts.LoadedCA != nil:
caCertPool := basePool(opts.LoadedCAPool)
caCertPool.AddCert(opts.LoadedCA)
cfg.RootCAs = caCertPool
} else if opts.CA != "" {
case opts.CA != "":
// load ca cert
caCert, err := os.ReadFile(opts.CA)
if err != nil {
@@ -171,7 +180,7 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
caCertPool := basePool(opts.LoadedCAPool)
caCertPool.AppendCertsFromPEM(caCert)
cfg.RootCAs = caCertPool
} else if opts.LoadedCAPool != nil {
case opts.LoadedCAPool != nil:
cfg.RootCAs = opts.LoadedCAPool
}
@@ -227,7 +236,7 @@ type Runtime struct {
Host string
BasePath string
Formats strfmt.Registry
Context context.Context
Context context.Context //nolint:containedctx // we precisely want this type to contain the request context
Debug bool
logger logger.Logger
@@ -316,7 +325,7 @@ func (r *Runtime) pickScheme(schemes []string) string {
if v := r.selectScheme(schemes); v != "" {
return v
}
return "http"
return schemeHTTP
}
func (r *Runtime) selectScheme(schemes []string) string {
@@ -327,9 +336,9 @@ func (r *Runtime) selectScheme(schemes []string) string {
scheme := schemes[0]
// prefer https, but skip when not possible
if scheme != "https" && schLen > 1 {
if scheme != schemeHTTPS && schLen > 1 {
for _, sch := range schemes {
if sch == "https" {
if sch == schemeHTTPS {
scheme = sch
break
}
@@ -368,17 +377,14 @@ func (r *Runtime) EnableConnectionReuse() {
}
// takes a client operation and creates equivalent http.Request
func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*request, *http.Request, error) {
func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*request, *http.Request, error) { //nolint:revive,stylecheck
params, _, auth := operation.Params, operation.Reader, operation.AuthInfo
request, err := newRequest(operation.Method, operation.PathPattern, params)
if err != nil {
return nil, nil, err
}
request := newRequest(operation.Method, operation.PathPattern, params)
var accept []string
accept = append(accept, operation.ProducesMediaTypes...)
if err = request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil {
if err := request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil {
return nil, nil, err
}
@@ -420,7 +426,7 @@ func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*reques
return request, req, nil
}
func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *http.Request, err error) {
func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *http.Request, err error) { //nolint:revive,stylecheck
_, req, err = r.createHttpRequest(operation)
return
}
@@ -450,27 +456,36 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error
r.logger.Debugf("%s\n", string(b))
}
var hasTimeout bool
pctx := operation.Context
if pctx == nil {
pctx = r.Context
} else {
hasTimeout = true
var parentCtx context.Context
switch {
case operation.Context != nil:
parentCtx = operation.Context
case r.Context != nil:
parentCtx = r.Context
default:
parentCtx = context.Background()
}
if pctx == nil {
pctx = context.Background()
}
var ctx context.Context
var cancel context.CancelFunc
if hasTimeout {
ctx, cancel = context.WithCancel(pctx)
var (
ctx context.Context
cancel context.CancelFunc
)
if request.timeout == 0 {
// There may be a deadline in the context passed to the operation.
// Otherwise, there is no timeout set.
ctx, cancel = context.WithCancel(parentCtx)
} else {
ctx, cancel = context.WithTimeout(pctx, request.timeout)
// Sets the timeout passed from request params (by default runtime.DefaultTimeout).
// If there is already a deadline in the parent context, the shortest will
// apply.
ctx, cancel = context.WithTimeout(parentCtx, request.timeout)
}
defer cancel()
client := operation.Client
if client == nil {
var client *http.Client
if operation.Client != nil {
client = operation.Client
} else {
client = r.client
}
req = req.WithContext(ctx)
@@ -481,7 +496,7 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error
defer res.Body.Close()
ct := res.Header.Get(runtime.HeaderContentType)
if ct == "" { // this should really really never occur
if ct == "" { // this should really never occur
ct = r.DefaultMediaType
}
@@ -526,7 +541,7 @@ func (r *Runtime) SetLogger(logger logger.Logger) {
middleware.Logger = logger
}
type ClientResponseFunc = func(*http.Response) runtime.ClientResponse
type ClientResponseFunc = func(*http.Response) runtime.ClientResponse //nolint:revive
// SetResponseReader changes the response reader implementation.
func (r *Runtime) SetResponseReader(f ClientResponseFunc) {