apiserver.go 17.0 KB
Newer Older
Z
zryfish 已提交
1 2 3
package apiserver

import (
4 5 6
	"bytes"
	"context"
	"fmt"
Z
zryfish 已提交
7
	"github.com/emicklei/go-restful"
8 9
	"k8s.io/apimachinery/pkg/runtime/schema"
	urlruntime "k8s.io/apimachinery/pkg/util/runtime"
Z
zryfish 已提交
10
	"k8s.io/apimachinery/pkg/util/sets"
H
hongming 已提交
11
	unionauth "k8s.io/apiserver/pkg/authentication/request/union"
Z
zryfish 已提交
12
	"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
13
	"k8s.io/klog"
H
hongming 已提交
14 15 16
	clusterv1alpha1 "kubesphere.io/kubesphere/pkg/apis/cluster/v1alpha1"
	iamv1alpha2 "kubesphere.io/kubesphere/pkg/apis/iam/v1alpha2"
	tenantv1alpha1 "kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
H
update  
hongming 已提交
17
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/authenticators/basic"
Z
zryfish 已提交
18
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/authenticators/jwttoken"
H
update  
hongming 已提交
19 20
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/request/anonymous"
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/request/basictoken"
R
runzexia 已提交
21
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/request/bearertoken"
H
update  
hongming 已提交
22
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/token"
H
hongming 已提交
23
	"kubesphere.io/kubesphere/pkg/apiserver/authorization/authorizer"
H
hongming 已提交
24
	"kubesphere.io/kubesphere/pkg/apiserver/authorization/authorizerfactory"
H
hongming 已提交
25
	authorizationoptions "kubesphere.io/kubesphere/pkg/apiserver/authorization/options"
H
hongming 已提交
26 27
	"kubesphere.io/kubesphere/pkg/apiserver/authorization/path"
	unionauthorizer "kubesphere.io/kubesphere/pkg/apiserver/authorization/union"
28
	apiserverconfig "kubesphere.io/kubesphere/pkg/apiserver/config"
Z
zryfish 已提交
29 30 31
	"kubesphere.io/kubesphere/pkg/apiserver/dispatch"
	"kubesphere.io/kubesphere/pkg/apiserver/filters"
	"kubesphere.io/kubesphere/pkg/apiserver/request"
Z
zryfish 已提交
32
	"kubesphere.io/kubesphere/pkg/informers"
33
	clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1"
34
	configv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/config/v1alpha2"
R
fmt  
runzexia 已提交
35
	devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2"
H
hongming 已提交
36
	iamapi "kubesphere.io/kubesphere/pkg/kapis/iam/v1alpha2"
37
	loggingv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/logging/v1alpha2"
R
runzexia 已提交
38
	monitoringv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/monitoring/v1alpha3"
Z
Zhengyi Lai 已提交
39
	networkv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/network/v1alpha2"
H
hongming 已提交
40
	"kubesphere.io/kubesphere/pkg/kapis/oauth"
41 42 43
	openpitrixv1 "kubesphere.io/kubesphere/pkg/kapis/openpitrix/v1"
	operationsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/operations/v1alpha2"
	resourcesv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha2"
Z
zryfish 已提交
44
	resourcev1alpha3 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha3"
45
	servicemeshv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/servicemesh/metrics/v1alpha2"
H
hongming 已提交
46
	tenantv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/tenant/v1alpha2"
47
	terminalv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/terminal/v1alpha2"
H
update  
hongming 已提交
48
	"kubesphere.io/kubesphere/pkg/models/iam/am"
H
update  
hongming 已提交
49
	"kubesphere.io/kubesphere/pkg/models/iam/im"
Z
zryfish 已提交
50 51 52
	"kubesphere.io/kubesphere/pkg/simple/client/cache"
	"kubesphere.io/kubesphere/pkg/simple/client/devops"
	"kubesphere.io/kubesphere/pkg/simple/client/k8s"
53
	"kubesphere.io/kubesphere/pkg/simple/client/ldap"
Z
zryfish 已提交
54 55 56 57
	"kubesphere.io/kubesphere/pkg/simple/client/logging"
	"kubesphere.io/kubesphere/pkg/simple/client/monitoring"
	"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
	"kubesphere.io/kubesphere/pkg/simple/client/s3"
R
runzexia 已提交
58
	"kubesphere.io/kubesphere/pkg/simple/client/sonarqube"
59 60 61 62 63
	"net"
	"net/http"
	rt "runtime"
	"strings"
	"time"
Z
zryfish 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
)

const (
	// ApiRootPath defines the root path of all KubeSphere apis.
	ApiRootPath = "/kapis"

	// MimeMergePatchJson is the mime header used in merge request
	MimeMergePatchJson = "application/merge-patch+json"

	//
	MimeJsonPatchJson = "application/json-patch+json"
)

type APIServer struct {

	// number of kubesphere apiserver
80
	ServerCount int
Z
zryfish 已提交
81 82

	//
83 84
	Server *http.Server

85
	Config *apiserverconfig.Config
Z
zryfish 已提交
86 87 88 89 90

	// webservice container, where all webservice defines
	container *restful.Container

	// kubeClient is a collection of all kubernetes(include CRDs) objects clientset
91
	KubernetesClient k8s.Client
Z
zryfish 已提交
92 93 94

	// informerFactory is a collection of all kubernetes(include CRDs) objects informers,
	// mainly for fast query
95
	InformerFactory informers.InformerFactory
Z
zryfish 已提交
96 97

	// cache is used for short lived objects, like session
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
	CacheClient cache.Interface

	// monitoring client set
	MonitoringClient monitoring.Interface

	//
	OpenpitrixClient openpitrix.Client

	//
	LoggingClient logging.Interface

	//
	DevopsClient devops.Interface

	//
	S3Client s3.Interface

	//
	LdapClient ldap.Interface
R
runzexia 已提交
117 118

	SonarClient sonarqube.SonarInterface
119 120 121 122 123 124 125 126 127 128 129 130 131
}

func (s *APIServer) PrepareRun() error {

	s.container = restful.NewContainer()
	s.container.Filter(logRequestAndResponse)
	s.container.Router(restful.CurlyRouter{})
	s.container.RecoverHandler(func(panicReason interface{}, httpWriter http.ResponseWriter) {
		logStackOnRecover(panicReason, httpWriter)
	})

	s.installKubeSphereAPIs()

Z
zryfish 已提交
132 133 134 135 136 137 138 139
	for _, ws := range s.container.RegisteredWebServices() {
		klog.V(2).Infof("%s", ws.RootPath())
	}

	s.Server.Handler = s.container

	s.buildHandlerChain()

140 141 142
	return nil
}

143 144 145
// Install all kubesphere api groups
// Installation happens before all informers start to cache objects, so
//   any attempt to list objects using listers will get empty results.
146
func (s *APIServer) installKubeSphereAPIs() {
147
	urlruntime.Must(configv1alpha2.AddToContainer(s.container, s.Config))
148 149
	urlruntime.Must(resourcev1alpha3.AddToContainer(s.container, s.InformerFactory))
	urlruntime.Must(loggingv1alpha2.AddToContainer(s.container, s.KubernetesClient, s.LoggingClient))
R
runzexia 已提交
150
	urlruntime.Must(monitoringv1alpha3.AddToContainer(s.container, s.KubernetesClient.Kubernetes(), s.MonitoringClient))
151
	urlruntime.Must(openpitrixv1.AddToContainer(s.container, s.InformerFactory, s.OpenpitrixClient))
152
	urlruntime.Must(networkv1alpha2.AddToContainer(s.container, s.Config.NetworkOptions.WeaveScopeHost))
153 154
	urlruntime.Must(operationsv1alpha2.AddToContainer(s.container, s.KubernetesClient.Kubernetes()))
	urlruntime.Must(resourcesv1alpha2.AddToContainer(s.container, s.KubernetesClient.Kubernetes(), s.InformerFactory))
H
hongming 已提交
155
	urlruntime.Must(tenantv1alpha2.AddToContainer(s.container, s.InformerFactory))
156
	urlruntime.Must(terminalv1alpha2.AddToContainer(s.container, s.KubernetesClient.Kubernetes(), s.KubernetesClient.Config()))
157 158 159 160 161 162 163 164
	urlruntime.Must(clusterkapisv1alpha1.AddToContainer(s.container,
		s.InformerFactory.KubernetesSharedInformerFactory(),
		s.InformerFactory.KubeSphereSharedInformerFactory(),
		s.Config.MultiClusterOptions.ProxyPublishService,
		s.Config.MultiClusterOptions.ProxyPublishAddress,
		s.Config.MultiClusterOptions.AgentImage))
	urlruntime.Must(iamapi.AddToContainer(s.container,
		im.NewOperator(s.KubernetesClient.KubeSphere(), s.InformerFactory),
H
hongming 已提交
165
		am.NewAMOperator(s.InformerFactory),
R
runzexia 已提交
166
		s.Config.AuthenticationOptions))
167 168 169
	urlruntime.Must(oauth.AddToContainer(s.container,
		token.NewJwtTokenIssuer(token.DefaultIssuerName, s.Config.AuthenticationOptions, s.CacheClient),
		s.Config.AuthenticationOptions))
Z
zryfish 已提交
170
	urlruntime.Must(servicemeshv1alpha2.AddToContainer(s.container))
171 172 173 174 175 176
	urlruntime.Must(devopsv1alpha2.AddToContainer(s.container,
		s.InformerFactory.KubeSphereSharedInformerFactory(),
		s.DevopsClient,
		s.SonarClient,
		s.KubernetesClient.KubeSphere(),
		s.S3Client))
177 178
}

Z
zryfish 已提交
179
func (s *APIServer) Run(stopCh <-chan struct{}) (err error) {
180

Z
zryfish 已提交
181
	err = s.waitForResourceSync(stopCh)
182 183 184 185 186 187
	if err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Z
zryfish 已提交
188

189 190 191 192 193
	go func() {
		<-stopCh
		_ = s.Server.Shutdown(ctx)
	}()

Z
zryfish 已提交
194
	klog.V(0).Infof("Start listening on %s", s.Server.Addr)
195
	if s.Server.TLSConfig != nil {
Z
zryfish 已提交
196
		err = s.Server.ListenAndServeTLS("", "")
197
	} else {
Z
zryfish 已提交
198
		err = s.Server.ListenAndServe()
199
	}
Z
zryfish 已提交
200 201

	return err
Z
zryfish 已提交
202 203
}

Z
zryfish 已提交
204 205 206 207
func (s *APIServer) buildHandlerChain() {
	requestInfoResolver := &request.RequestInfoFactory{
		APIPrefixes:          sets.NewString("api", "apis", "kapis", "kapi"),
		GrouplessAPIPrefixes: sets.NewString("api", "kapi"),
H
hongming 已提交
208 209 210 211 212 213 214
		GlobalResources: []schema.GroupResource{
			{Group: iamv1alpha2.SchemeGroupVersion.Group, Resource: iamv1alpha2.ResourcesPluralUser},
			{Group: iamv1alpha2.SchemeGroupVersion.Group, Resource: iamv1alpha2.ResourcesPluralGlobalRole},
			{Group: iamv1alpha2.SchemeGroupVersion.Group, Resource: iamv1alpha2.ResourcesPluralGlobalRoleBinding},
			{Group: tenantv1alpha1.SchemeGroupVersion.Group, Resource: tenantv1alpha1.ResourcePluralWorkspace},
			{Group: clusterv1alpha1.SchemeGroupVersion.Group, Resource: clusterv1alpha1.ResourcesPluralCluster},
		},
Z
zryfish 已提交
215 216 217
	}

	handler := s.Server.Handler
H
update  
hongming 已提交
218
	handler = filters.WithKubeAPIServer(handler, s.KubernetesClient.Config(), &errorResponder{})
R
runzexia 已提交
219

Z
zryfish 已提交
220 221 222 223
	if s.Config.MultiClusterOptions.Enable {
		clusterDispatcher := dispatch.NewClusterDispatch(s.InformerFactory.KubeSphereSharedInformerFactory().Cluster().V1alpha1().Clusters().Lister())
		handler = filters.WithMultipleClusterDispatcher(handler, clusterDispatcher)
	}
H
hongming 已提交
224

H
hongming 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238
	var authorizers authorizer.Authorizer

	switch s.Config.AuthorizationOptions.Mode {
	case authorizationoptions.AlwaysAllow:
		authorizers = authorizerfactory.NewAlwaysAllowAuthorizer()
	case authorizationoptions.AlwaysDeny:
		authorizers = authorizerfactory.NewAlwaysDenyAuthorizer()
	default:
		fallthrough
	case authorizationoptions.RBAC:
		excludedPaths := []string{"/oauth/*", "/kapis/config.kubesphere.io/*"}
		pathAuthorizer, _ := path.NewAuthorizer(excludedPaths)
		authorizers = unionauthorizer.New(pathAuthorizer, authorizerfactory.NewOPAAuthorizer(am.NewAMOperator(s.InformerFactory)), authorizerfactory.NewRBACAuthorizer(am.NewAMOperator(s.InformerFactory)))
	}
Z
zryfish 已提交
239

240 241 242
	handler = filters.WithAuthorization(handler, authorizers)

	// authenticators are unordered
H
update  
hongming 已提交
243
	authn := unionauth.New(anonymous.NewAuthenticator(),
H
hongming 已提交
244
		basictoken.New(basic.NewBasicAuthenticator(im.NewOperator(s.KubernetesClient.KubeSphere(), s.InformerFactory))),
245
		bearertoken.New(jwttoken.NewTokenAuthenticator(token.NewJwtTokenIssuer(token.DefaultIssuerName, s.Config.AuthenticationOptions, s.CacheClient))))
H
update  
hongming 已提交
246 247
	handler = filters.WithAuthentication(handler, authn)
	handler = filters.WithRequestInfo(handler, requestInfoResolver)
Z
zryfish 已提交
248 249 250
	s.Server.Handler = handler
}

251 252 253 254
func (s *APIServer) waitForResourceSync(stopCh <-chan struct{}) error {
	klog.V(0).Info("Start cache objects")

	discoveryClient := s.KubernetesClient.Kubernetes().Discovery()
H
hongming 已提交
255
	_, apiResourcesList, err := discoveryClient.ServerGroupsAndResources()
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	if err != nil {
		return err
	}

	isResourceExists := func(resource schema.GroupVersionResource) bool {
		for _, apiResource := range apiResourcesList {
			if apiResource.GroupVersion == resource.GroupVersion().String() {
				for _, rsc := range apiResource.APIResources {
					if rsc.Name == resource.Resource {
						return true
					}
				}
			}
		}
		return false
	}

	// resources we have to create informer first
	k8sGVRs := []schema.GroupVersionResource{
		{Group: "", Version: "v1", Resource: "namespaces"},
		{Group: "", Version: "v1", Resource: "nodes"},
		{Group: "", Version: "v1", Resource: "resourcequotas"},
		{Group: "", Version: "v1", Resource: "pods"},
		{Group: "", Version: "v1", Resource: "services"},
		{Group: "", Version: "v1", Resource: "persistentvolumeclaims"},
		{Group: "", Version: "v1", Resource: "secrets"},
		{Group: "", Version: "v1", Resource: "configmaps"},

		{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "roles"},
		{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "rolebindings"},
		{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "clusterroles"},
		{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "clusterrolebindings"},

		{Group: "apps", Version: "v1", Resource: "deployments"},
		{Group: "apps", Version: "v1", Resource: "daemonsets"},
		{Group: "apps", Version: "v1", Resource: "replicasets"},
		{Group: "apps", Version: "v1", Resource: "statefulsets"},
		{Group: "apps", Version: "v1", Resource: "controllerrevisions"},

		{Group: "storage.k8s.io", Version: "v1", Resource: "storageclasses"},

		{Group: "batch", Version: "v1", Resource: "jobs"},
		{Group: "batch", Version: "v1beta1", Resource: "cronjobs"},

		{Group: "extensions", Version: "v1beta1", Resource: "ingresses"},

		{Group: "autoscaling", Version: "v2beta2", Resource: "horizontalpodautoscalers"},
D
Duan Jiong 已提交
303 304

		{Group: "networking.k8s.io", Version: "v1", Resource: "networkpolicies"},
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	}

	for _, gvr := range k8sGVRs {
		if !isResourceExists(gvr) {
			klog.Warningf("resource %s not exists in the cluster", gvr)
		} else {
			_, err := s.InformerFactory.KubernetesSharedInformerFactory().ForResource(gvr)
			if err != nil {
				klog.Errorf("cannot create informer for %s", gvr)
				return err
			}
		}
	}

	s.InformerFactory.KubernetesSharedInformerFactory().Start(stopCh)
	s.InformerFactory.KubernetesSharedInformerFactory().WaitForCacheSync(stopCh)

	ksInformerFactory := s.InformerFactory.KubeSphereSharedInformerFactory()

	ksGVRs := []schema.GroupVersionResource{
		{Group: "tenant.kubesphere.io", Version: "v1alpha1", Resource: "workspaces"},
R
runzexia 已提交
326
		{Group: "iam.kubesphere.io", Version: "v1alpha2", Resource: "users"},
H
hongming 已提交
327 328 329 330
		{Group: "iam.kubesphere.io", Version: "v1alpha2", Resource: "globalroles"},
		{Group: "iam.kubesphere.io", Version: "v1alpha2", Resource: "globalrolebindings"},
		{Group: "iam.kubesphere.io", Version: "v1alpha2", Resource: "workspaceroles"},
		{Group: "iam.kubesphere.io", Version: "v1alpha2", Resource: "workspacerolebindings"},
Z
zryfish 已提交
331
		{Group: "cluster.kubesphere.io", Version: "v1alpha1", Resource: "clusters"},
332 333 334 335 336 337 338 339 340 341 342 343 344
	}

	devopsGVRs := []schema.GroupVersionResource{
		{Group: "devops.kubesphere.io", Version: "v1alpha1", Resource: "s2ibinaries"},
		{Group: "devops.kubesphere.io", Version: "v1alpha1", Resource: "s2ibuildertemplates"},
		{Group: "devops.kubesphere.io", Version: "v1alpha1", Resource: "s2iruns"},
		{Group: "devops.kubesphere.io", Version: "v1alpha1", Resource: "s2ibuilders"},
	}

	servicemeshGVRs := []schema.GroupVersionResource{
		{Group: "servicemesh.kubesphere.io", Version: "v1alpha2", Resource: "strategies"},
		{Group: "servicemesh.kubesphere.io", Version: "v1alpha2", Resource: "servicepolicies"},
	}
Z
zryfish 已提交
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
	// skip caching devops resources if devops not enabled
	if s.DevopsClient != nil {
		ksGVRs = append(ksGVRs, devopsGVRs...)
	}

	// skip caching servicemesh resources if servicemesh not enabled
	if s.KubernetesClient.Istio() != nil {
		ksGVRs = append(ksGVRs, servicemeshGVRs...)
	}

	for _, gvr := range ksGVRs {
		if !isResourceExists(gvr) {
			klog.Warningf("resource %s not exists in the cluster", gvr)
		} else {
			_, err := ksInformerFactory.ForResource(gvr)
			if err != nil {
				return err
			}
		}
	}

	ksInformerFactory.Start(stopCh)
	ksInformerFactory.WaitForCacheSync(stopCh)

	appInformerFactory := s.InformerFactory.ApplicationSharedInformerFactory()

	appGVRs := []schema.GroupVersionResource{
		{Group: "app.k8s.io", Version: "v1beta1", Resource: "applications"},
	}

	for _, gvr := range appGVRs {
		if !isResourceExists(gvr) {
			klog.Warningf("resource %s not exists in the cluster", gvr)
		} else {
Z
zryfish 已提交
380
			_, err = appInformerFactory.ForResource(gvr)
381 382 383 384 385 386 387 388 389
			if err != nil {
				return err
			}
		}
	}

	appInformerFactory.Start(stopCh)
	appInformerFactory.WaitForCacheSync(stopCh)

Z
zhangmin 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
	snapshotInformerFactory := s.InformerFactory.SnapshotSharedInformerFactory()
	snapshotGVRs := []schema.GroupVersionResource{
		{Group: "snapshot.storage.k8s.io", Version: "v1beta1", Resource: "volumesnapshotclasses"},
		{Group: "snapshot.storage.k8s.io", Version: "v1beta1", Resource: "volumesnapshots"},
		{Group: "snapshot.storage.k8s.io", Version: "v1beta1", Resource: "volumesnapshotcontents"},
	}
	for _, gvr := range snapshotGVRs {
		if !isResourceExists(gvr) {
			klog.Warningf("resource %s not exists in the cluster", gvr)
		} else {
			_, err = snapshotInformerFactory.ForResource(gvr)
			if err != nil {
				return err
			}
		}
	}
	snapshotInformerFactory.Start(stopCh)
	snapshotInformerFactory.WaitForCacheSync(stopCh)

409 410 411
	klog.V(0).Info("Finished caching objects")

	return nil
Z
zryfish 已提交
412 413 414

}

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
func logStackOnRecover(panicReason interface{}, w http.ResponseWriter) {
	var buffer bytes.Buffer
	buffer.WriteString(fmt.Sprintf("recover from panic situation: - %v\r\n", panicReason))
	for i := 2; ; i += 1 {
		_, file, line, ok := rt.Caller(i)
		if !ok {
			break
		}
		buffer.WriteString(fmt.Sprintf("    %s:%d\r\n", file, line))
	}
	klog.Errorln(buffer.String())

	headers := http.Header{}
	if ct := w.Header().Get("Content-Type"); len(ct) > 0 {
		headers.Set("Accept", ct)
	}

	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte("Internal server error"))
}
Z
zryfish 已提交
435

436 437 438 439 440 441 442 443 444 445 446 447
func logRequestAndResponse(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	start := time.Now()
	chain.ProcessFilter(req, resp)
	klog.V(4).Infof("%s - \"%s %s %s\" %d %d %dms",
		getRequestIP(req),
		req.Request.Method,
		req.Request.RequestURI,
		req.Request.Proto,
		resp.StatusCode(),
		resp.ContentLength(),
		time.Since(start)/time.Millisecond,
	)
Z
zryfish 已提交
448 449
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
func getRequestIP(req *restful.Request) string {
	address := strings.Trim(req.Request.Header.Get("X-Real-Ip"), " ")
	if address != "" {
		return address
	}

	address = strings.Trim(req.Request.Header.Get("X-Forwarded-For"), " ")
	if address != "" {
		return address
	}

	address, _, err := net.SplitHostPort(req.Request.RemoteAddr)
	if err != nil {
		return req.Request.RemoteAddr
	}

	return address
Z
zryfish 已提交
467
}
Z
zryfish 已提交
468 469 470 471 472 473 474

type errorResponder struct{}

func (e *errorResponder) Error(w http.ResponseWriter, req *http.Request, err error) {
	klog.Error(err)
	responsewriters.InternalError(w, req, err)
}