1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
|
package kubernetes
import (
"context"
"fmt"
"io"
"net/http"
"strconv"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
terminal "gitlab.com/gitlab-org/gitlab-terminal"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8net "k8s.io/apimachinery/pkg/util/net"
"k8s.io/client-go/rest"
"gitlab.com/gitlab-org/gitlab-runner/session/proxy"
)
const runningState = "Running"
func (s *executor) Pool() proxy.Pool {
return s.ProxyPool
}
func (s *executor) newProxy(serviceName string, ports []proxy.Port) *proxy.Proxy {
return &proxy.Proxy{
Settings: proxy.NewProxySettings(serviceName, ports),
ConnectionHandler: s,
}
}
func (s *executor) ProxyRequest(
w http.ResponseWriter,
r *http.Request,
requestedURI string,
port string,
settings *proxy.Settings,
) {
logger := logrus.WithFields(logrus.Fields{
"uri": r.RequestURI,
"method": r.Method,
"port": port,
"settings": settings,
})
portSettings, err := settings.PortByNameOrNumber(port)
if err != nil {
logger.WithError(err).Errorf("port proxy %q not found", port)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
if !s.servicesRunning() {
logger.Errorf("services are not ready yet")
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
if websocket.IsWebSocketUpgrade(r) {
proxyWSRequest(s, w, r, requestedURI, portSettings, settings, logger)
return
}
proxyHTTPRequest(s, w, r, requestedURI, portSettings, settings, logger)
}
func (s *executor) servicesRunning() bool {
// TODO: handle the context properly with https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27932
pod, err := s.kubeClient.CoreV1().Pods(s.pod.Namespace).Get(context.TODO(), s.pod.Name, metav1.GetOptions{})
if err != nil || pod.Status.Phase != runningState {
return false
}
for _, container := range pod.Status.ContainerStatuses {
if !container.Ready {
return false
}
}
return true
}
func (s *executor) serviceEndpointRequest(
verb, serviceName, requestedURI string,
port proxy.Port,
) (*rest.Request, error) {
scheme, err := port.Scheme()
if err != nil {
return nil, err
}
result := s.kubeClient.CoreV1().RESTClient().Verb(verb).
Namespace(s.pod.Namespace).
Resource("services").
SubResource("proxy").
Name(k8net.JoinSchemeNamePort(scheme, serviceName, strconv.Itoa(port.Number))).
Suffix(requestedURI)
return result, nil
}
func proxyWSRequest(
s *executor,
w http.ResponseWriter,
r *http.Request,
requestedURI string,
port proxy.Port,
proxySettings *proxy.Settings,
logger *logrus.Entry,
) {
// In order to avoid calling this method, and use one of its own,
// we should refactor the library "gitlab.com/gitlab-org/gitlab-terminal"
// and make it more generic, not so terminal focused, with a broader
// terminology. (https://gitlab.com/gitlab-org/gitlab-runner/issues/4059)
settings, err := s.getTerminalSettings()
if err != nil {
logger.WithError(err).Errorf("service proxy: error getting WS settings")
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
req, err := s.serviceEndpointRequest(r.Method, proxySettings.ServiceName, requestedURI, port)
if err != nil {
logger.WithError(err).Errorf("service proxy: error proxying WS request")
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
u := req.URL()
u.Scheme = proxy.WebsocketProtocolFor(u.Scheme)
settings.Url = u.String()
serviceProxy := terminal.NewWebSocketProxy(1)
terminal.ProxyWebSocket(w, r, settings, serviceProxy)
}
func proxyHTTPRequest(
s *executor,
w http.ResponseWriter,
r *http.Request,
requestedURI string,
port proxy.Port,
proxy *proxy.Settings,
logger *logrus.Entry,
) {
req, err := s.serviceEndpointRequest(r.Method, proxy.ServiceName, requestedURI, port)
if err != nil {
logger.WithError(err).Errorf("service proxy: error proxying HTTP request")
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
// TODO: handle the context properly with https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27932
body, err := req.Stream(context.TODO())
if err != nil {
message, code := handleProxyHTTPErr(err, logger)
w.WriteHeader(code)
if message != "" {
_, _ = fmt.Fprint(w, message)
}
return
}
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, body)
}
func handleProxyHTTPErr(err error, logger *logrus.Entry) (string, int) {
statusError, ok := err.(*errors.StatusError)
if !ok {
return "", http.StatusInternalServerError
}
code := int(statusError.Status().Code)
// When the error is a 503 we don't want to give any information
// coming from Kubernetes
if code == http.StatusServiceUnavailable {
logger.Error(statusError.Status().Message)
return "", code
}
details := statusError.Status().Details
if details == nil {
return "", code
}
causes := details.Causes
if len(causes) > 0 {
return causes[0].Message, code
}
return "", code
}
|