k8s.io/kubernetes@v1.29.3/test/e2e/framework/websocket/websocket_util.go (about)

     1  /*
     2  Copyright 2020 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package websocket
    18  
    19  import (
    20  	"fmt"
    21  	"net/http"
    22  	"net/url"
    23  
    24  	restclient "k8s.io/client-go/rest"
    25  
    26  	"golang.org/x/net/websocket"
    27  )
    28  
    29  type extractRT struct {
    30  	http.Header
    31  }
    32  
    33  func (rt *extractRT) RoundTrip(req *http.Request) (*http.Response, error) {
    34  	rt.Header = req.Header
    35  	return &http.Response{}, nil
    36  }
    37  
    38  // OpenWebSocketForURL constructs a websocket connection to the provided URL, using the client
    39  // config, with the specified protocols.
    40  func OpenWebSocketForURL(url *url.URL, config *restclient.Config, protocols []string) (*websocket.Conn, error) {
    41  	tlsConfig, err := restclient.TLSConfigFor(config)
    42  	if err != nil {
    43  		return nil, fmt.Errorf("Failed to create tls config: %w", err)
    44  	}
    45  	if url.Scheme == "https" {
    46  		url.Scheme = "wss"
    47  	} else {
    48  		url.Scheme = "ws"
    49  	}
    50  	headers, err := headersForConfig(config, url)
    51  	if err != nil {
    52  		return nil, fmt.Errorf("Failed to load http headers: %w", err)
    53  	}
    54  	cfg, err := websocket.NewConfig(url.String(), "http://localhost")
    55  	if err != nil {
    56  		return nil, fmt.Errorf("Failed to create websocket config: %w", err)
    57  	}
    58  	cfg.Header = headers
    59  	cfg.TlsConfig = tlsConfig
    60  	cfg.Protocol = protocols
    61  	return websocket.DialConfig(cfg)
    62  }
    63  
    64  // headersForConfig extracts any http client logic necessary for the provided
    65  // config.
    66  func headersForConfig(c *restclient.Config, url *url.URL) (http.Header, error) {
    67  	extract := &extractRT{}
    68  	rt, err := restclient.HTTPWrappersForConfig(c, extract)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	request, err := http.NewRequest("GET", url.String(), nil)
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  	if _, err := rt.RoundTrip(request); err != nil {
    77  		return nil, err
    78  	}
    79  	return extract.Header, nil
    80  }