Skip to content

Commit 2be51e1

Browse files
stttsbertinatto
authored andcommitted
UPSTREAM: <carry>: create termination events
UPSTREAM: <carry>: apiserver: log new connections during termination UPSTREAM: <carry>: apiserver: create LateConnections events on events in the last 20% of graceful termination time UPSTREAM: <carry>: apiserver: log source in LateConnections event UPSTREAM: <carry>: apiserver: skip local IPs and probes for LateConnections UPSTREAM: <carry>: only create valid LateConnections/GracefulTermination events UPSTREAM: <carry>: kube-apiserver: log non-probe requests before ready UPSTREAM: <carry>: apiserver: create hasBeenReadyCh channel UPSTREAM: <carry>: kube-apiserver: log non-probe requests before ready UPSTREAM: <carry>: kube-apiserver: log non-probe requests before ready UPSTREAM: <carry>: fix termination event(s) validation failures UPSTREAM: <carry>: during the rebase collapse to create termination event it makes recording termination events a non-blocking operation. previously closing delayedStopCh might have been delayed on preserving data in the storage. the delayedStopCh is important as it signals the HTTP server to start the shutdown procedure. it also sets a hard timeout of 3 seconds for the storage layer since we are bypassing the API layer. UPSTREAM: <carry>: rename termination events to use lifecycleSignals OpenShift-Rebase-Source: 15b2d2e UPSTREAM: <carry>: extend termination events - we tie the shutdown events with the UID of the first (shutdown initiated), this provides us with a more deterministic way to compute shutdown duration from these events - move code snippets from the upstream file to openshift specific patch file, it reduces chance of code conflict
1 parent 665a0e1 commit 2be51e1

File tree

5 files changed

+431
-2
lines changed

5 files changed

+431
-2
lines changed

pkg/controlplane/apiserver/config.go

+8
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import (
2828
"k8s.io/kubernetes/openshift-kube-apiserver/admission/admissionenablement"
2929
"k8s.io/kubernetes/openshift-kube-apiserver/enablement"
3030
"k8s.io/kubernetes/openshift-kube-apiserver/openshiftkubeapiserver"
31+
eventstorage "k8s.io/kubernetes/pkg/registry/core/event/storage"
3132

3233
"k8s.io/apimachinery/pkg/api/meta"
3334
"k8s.io/apimachinery/pkg/runtime"
@@ -292,6 +293,13 @@ func CreateConfig(
292293
opts.Metrics.Apply()
293294
serviceaccount.RegisterMetrics()
294295

296+
var eventStorage *eventstorage.REST
297+
eventStorage, err := eventstorage.NewREST(genericConfig.RESTOptionsGetter, uint64(opts.EventTTL.Seconds()))
298+
if err != nil {
299+
return nil, nil, err
300+
}
301+
genericConfig.EventSink = eventRegistrySink{eventStorage}
302+
295303
config := &Config{
296304
Generic: genericConfig,
297305
Extra: Extra{
+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
Copyright 2024 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 apiserver
18+
19+
import (
20+
"context"
21+
"fmt"
22+
"time"
23+
24+
corev1 "k8s.io/api/core/v1"
25+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26+
"k8s.io/apiserver/pkg/endpoints/request"
27+
genericapiserver "k8s.io/apiserver/pkg/server"
28+
"k8s.io/kubernetes/pkg/apis/core"
29+
v1 "k8s.io/kubernetes/pkg/apis/core/v1"
30+
eventstorage "k8s.io/kubernetes/pkg/registry/core/event/storage"
31+
)
32+
33+
// eventRegistrySink wraps an event registry in order to be used as direct event sync, without going through the API.
34+
type eventRegistrySink struct {
35+
*eventstorage.REST
36+
}
37+
38+
var _ genericapiserver.EventSink = eventRegistrySink{}
39+
40+
func (s eventRegistrySink) Create(v1event *corev1.Event) (*corev1.Event, error) {
41+
ctx := request.WithNamespace(request.WithRequestInfo(request.NewContext(), &request.RequestInfo{APIVersion: "v1"}), v1event.Namespace)
42+
// since we are bypassing the API set a hard timeout for the storage layer
43+
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
44+
defer cancel()
45+
46+
var event core.Event
47+
if err := v1.Convert_v1_Event_To_core_Event(v1event, &event, nil); err != nil {
48+
return nil, err
49+
}
50+
51+
obj, err := s.REST.Create(ctx, &event, nil, &metav1.CreateOptions{})
52+
if err != nil {
53+
return nil, err
54+
}
55+
ret, ok := obj.(*core.Event)
56+
if !ok {
57+
return nil, fmt.Errorf("expected corev1.Event, got %T", obj)
58+
}
59+
60+
var v1ret corev1.Event
61+
if err := v1.Convert_core_Event_To_v1_Event(ret, &v1ret, nil); err != nil {
62+
return nil, err
63+
}
64+
65+
return &v1ret, nil
66+
}

staging/src/k8s.io/apiserver/pkg/server/config.go

+39
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ import (
7272
utilflowcontrol "k8s.io/apiserver/pkg/util/flowcontrol"
7373
flowcontrolrequest "k8s.io/apiserver/pkg/util/flowcontrol/request"
7474
"k8s.io/client-go/informers"
75+
"k8s.io/client-go/kubernetes"
76+
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
7577
restclient "k8s.io/client-go/rest"
7678
basecompatibility "k8s.io/component-base/compatibility"
7779
"k8s.io/component-base/featuregate"
@@ -287,6 +289,9 @@ type Config struct {
287289
// rejected with a 429 status code and a 'Retry-After' response.
288290
ShutdownSendRetryAfter bool
289291

292+
// EventSink receives events about the life cycle of the API server, e.g. readiness, serving, signals and termination.
293+
EventSink EventSink
294+
290295
//===========================================================================
291296
// values below here are targets for removal
292297
//===========================================================================
@@ -723,6 +728,10 @@ func (c *Config) Complete(informers informers.SharedInformerFactory) CompletedCo
723728
c.DiscoveryAddresses = discovery.DefaultAddresses{DefaultAddress: c.ExternalAddress}
724729
}
725730

731+
if c.EventSink == nil {
732+
c.EventSink = nullEventSink{}
733+
}
734+
726735
AuthorizeClientBearerToken(c.LoopbackClientConfig, &c.Authentication, &c.Authorization)
727736

728737
if c.RequestInfoResolver == nil {
@@ -750,6 +759,22 @@ func (c *Config) Complete(informers informers.SharedInformerFactory) CompletedCo
750759
// Complete fills in any fields not set that are required to have valid data and can be derived
751760
// from other fields. If you're going to `ApplyOptions`, do that first. It's mutating the receiver.
752761
func (c *RecommendedConfig) Complete() CompletedConfig {
762+
if c.ClientConfig != nil {
763+
ref, err := eventReference()
764+
if err != nil {
765+
klog.Warningf("Failed to derive event reference, won't create events: %v", err)
766+
c.EventSink = nullEventSink{}
767+
} else {
768+
ns := ref.Namespace
769+
if len(ns) == 0 {
770+
ns = "default"
771+
}
772+
c.EventSink = clientEventSink{
773+
&v1.EventSinkImpl{Interface: kubernetes.NewForConfigOrDie(c.ClientConfig).CoreV1().Events(ns)},
774+
}
775+
}
776+
}
777+
753778
return c.Config.Complete(c.SharedInformerFactory)
754779
}
755780

@@ -854,7 +879,19 @@ func (c completedConfig) New(name string, delegationTarget DelegationTarget) (*G
854879
FeatureGate: c.FeatureGate,
855880

856881
muxAndDiscoveryCompleteSignals: map[string]<-chan struct{}{},
882+
883+
OpenShiftGenericAPIServerPatch: OpenShiftGenericAPIServerPatch{
884+
eventSink: c.EventSink,
885+
},
886+
}
887+
888+
ref, err := eventReference()
889+
if err != nil {
890+
klog.Warningf("Failed to derive event reference, won't create events: %v", err)
891+
s.OpenShiftGenericAPIServerPatch.eventSink = nullEventSink{}
857892
}
893+
s.RegisterDestroyFunc(c.EventSink.Destroy)
894+
s.eventRef = ref
858895

859896
manager := c.AggregatedDiscoveryGroupManager
860897
if manager == nil {
@@ -1062,6 +1099,8 @@ func DefaultBuildHandlerChain(apiHandler http.Handler, c *Config) http.Handler {
10621099
handler = genericapifilters.WithRequestDeadline(handler, c.AuditBackend, c.AuditPolicyRuleEvaluator,
10631100
c.LongRunningFunc, c.Serializer, c.RequestTimeout)
10641101
handler = genericfilters.WithWaitGroup(handler, c.LongRunningFunc, c.NonLongRunningRequestWaitGroup)
1102+
handler = WithNonReadyRequestLogging(handler, c.lifecycleSignals.HasBeenReady)
1103+
handler = WithLateConnectionFilter(handler)
10651104
if c.ShutdownWatchTerminationGracePeriod > 0 {
10661105
handler = genericfilters.WithWatchTerminationDuringShutdown(handler, c.lifecycleSignals, c.WatchRequestWaitGroup)
10671106
}

staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go

+34-2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030

3131
"golang.org/x/time/rate"
3232
apidiscoveryv2 "k8s.io/api/apidiscovery/v2"
33+
corev1 "k8s.io/api/core/v1"
3334
"k8s.io/apimachinery/pkg/api/meta"
3435
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
3536
"k8s.io/apimachinery/pkg/runtime"
@@ -295,6 +296,9 @@ type GenericAPIServer struct {
295296
// This grace period is orthogonal to other grace periods, and
296297
// it is not overridden by any other grace period.
297298
ShutdownWatchTerminationGracePeriod time.Duration
299+
300+
// OpenShift patch
301+
OpenShiftGenericAPIServerPatch
298302
}
299303

300304
// DelegationTarget is an interface which allows for composition of API servers with top level handling that works
@@ -547,7 +551,10 @@ func (s preparedGenericAPIServer) RunWithContext(ctx context.Context) error {
547551

548552
go func() {
549553
defer delayedStopCh.Signal()
550-
defer klog.V(1).InfoS("[graceful-termination] shutdown event", "name", delayedStopCh.Name())
554+
defer func() {
555+
klog.V(1).InfoS("[graceful-termination] shutdown event", "name", delayedStopCh.Name())
556+
s.Eventf(corev1.EventTypeNormal, delayedStopCh.Name(), "The minimal shutdown duration of %v finished", s.ShutdownDelayDuration)
557+
}()
551558

552559
<-stopCh
553560

@@ -556,10 +563,28 @@ func (s preparedGenericAPIServer) RunWithContext(ctx context.Context) error {
556563
// and stop sending traffic to this server.
557564
shutdownInitiatedCh.Signal()
558565
klog.V(1).InfoS("[graceful-termination] shutdown event", "name", shutdownInitiatedCh.Name())
566+
s.Eventf(corev1.EventTypeNormal, shutdownInitiatedCh.Name(), "Received signal to terminate, becoming unready, but keeping serving")
559567

560568
time.Sleep(s.ShutdownDelayDuration)
561569
}()
562570

571+
lateStopCh := make(chan struct{})
572+
if s.ShutdownDelayDuration > 0 {
573+
go func() {
574+
defer close(lateStopCh)
575+
576+
<-stopCh
577+
578+
time.Sleep(s.ShutdownDelayDuration * 8 / 10)
579+
}()
580+
}
581+
582+
s.SecureServingInfo.Listener = &terminationLoggingListener{
583+
Listener: s.SecureServingInfo.Listener,
584+
lateStopCh: lateStopCh,
585+
}
586+
unexpectedRequestsEventf.Store(s.Eventf)
587+
563588
// close socket after delayed stopCh
564589
shutdownTimeout := s.ShutdownTimeout
565590
if s.ShutdownSendRetryAfter {
@@ -608,13 +633,17 @@ func (s preparedGenericAPIServer) RunWithContext(ctx context.Context) error {
608633
<-listenerStoppedCh
609634
httpServerStoppedListeningCh.Signal()
610635
klog.V(1).InfoS("[graceful-termination] shutdown event", "name", httpServerStoppedListeningCh.Name())
636+
s.Eventf(corev1.EventTypeNormal, httpServerStoppedListeningCh.Name(), "HTTP Server has stopped listening")
611637
}()
612638

613639
// we don't accept new request as soon as both ShutdownDelayDuration has
614640
// elapsed and preshutdown hooks have completed.
615641
preShutdownHooksHasStoppedCh := s.lifecycleSignals.PreShutdownHooksStopped
616642
go func() {
617-
defer klog.V(1).InfoS("[graceful-termination] shutdown event", "name", notAcceptingNewRequestCh.Name())
643+
defer func() {
644+
klog.V(1).InfoS("[graceful-termination] shutdown event", "name", notAcceptingNewRequestCh.Name())
645+
s.Eventf(corev1.EventTypeNormal, drainedCh.Name(), "All non long-running request(s) in-flight have drained")
646+
}()
618647
defer notAcceptingNewRequestCh.Signal()
619648

620649
// wait for the delayed stopCh before closing the handler chain
@@ -701,6 +730,7 @@ func (s preparedGenericAPIServer) RunWithContext(ctx context.Context) error {
701730
defer func() {
702731
preShutdownHooksHasStoppedCh.Signal()
703732
klog.V(1).InfoS("[graceful-termination] pre-shutdown hooks completed", "name", preShutdownHooksHasStoppedCh.Name())
733+
s.Eventf(corev1.EventTypeNormal, "TerminationPreShutdownHooksFinished", "All pre-shutdown hooks have been finished")
704734
}()
705735
err = s.RunPreShutdownHooks()
706736
}()
@@ -721,6 +751,8 @@ func (s preparedGenericAPIServer) RunWithContext(ctx context.Context) error {
721751
<-stoppedCh
722752

723753
klog.V(1).Info("[graceful-termination] apiserver is exiting")
754+
s.Eventf(corev1.EventTypeNormal, "TerminationGracefulTerminationFinished", "All pending requests processed")
755+
724756
return nil
725757
}
726758

0 commit comments

Comments
 (0)