Merge pull request #4646 from wm775825/master

Add service-name-resolution-detector
This commit is contained in:
karmada-bot 2024-02-28 21:01:14 +08:00 committed by GitHub
commit 7b3a6a3452
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
18 changed files with 1660 additions and 0 deletions

View File

@ -0,0 +1,171 @@
# service-name-resolution-detector-example
The service name resolution detector is an example to detect coredns failure in member cluster.
It is deployed as DaemonSet in member cluster, each pod of which periodically looks up `kubernetes.default` service and
exports the status to node condition. The type of condition is named as `ServiceNameResolutionReady`.
There will be a leader who also collects all nodes conditions, figure out failure and sync the status to cluster conditions.
Here is a manifest you may need. And there are some notes:
- replace `<your-image-addr>` to your custom image address.
- replace `<your-cluster-name>` to the name of cluster where pods deployed.
- replace `<karmada-kubeconfig>` to contents of kubeconfig of karmada control plane.
- replace `<context-of-control-plane>` to the context of karmada kubeconfig, which refers to karmada control plane.
```yaml
kind: DaemonSet
apiVersion: apps/v1
metadata:
name: service-name-resolution-detector
namespace: kube-system
labels:
app: service-name-resolution-detector
spec:
selector:
matchLabels:
app: service-name-resolution-detector
template:
metadata:
labels:
app: service-name-resolution-detector
spec:
containers:
- image: <your-image-addr>
name: service-name-resolution-detector
command:
- service-name-resolution-detector
--karmada-kubeconfig=/tmp/config
--karmada-context=<context-of-control-plane>
--cluster-name=<your-cluster-name>
--host-name=${HOST_NAME}
--bind-address=${POD_ADDRESS}
--healthz-port=8081
--detectors=*
--coredns-detect-period=5s
--coredns-success-threshold=30s
--coredns-failure-threshold=30s
--coredns-stale-threshold=60s
env:
- name: POD_ADDRESS
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: status.podIP
- name: POD_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.namespace
- name: HOST_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: spec.nodeName
livenessProbe:
httpGet:
path: /healthz
port: 8081
scheme: HTTP
initialDelaySeconds: 3
timeoutSeconds: 3
periodSeconds: 5
successThreshold: 1
failureThreshold: 3
readinessProbe:
httpGet:
path: /healthz
port: 8081
scheme: HTTP
initialDelaySeconds: 3
timeoutSeconds: 3
periodSeconds: 5
successThreshold: 1
failureThreshold: 3
volumeMounts:
- mountPath: /tmp
name: karmada-config
serviceAccountName: service-name-resolution-detector
volumes:
- configMap:
name: karmada-kubeconfig
items:
- key: kubeconfig
path: config
name: karmada-config
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: service-name-resolution-detector
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: service-name-resolution-detector-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: system:service-name-resolution-detector
subjects:
- kind: ServiceAccount
name: service-name-resolution-detector
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: system:service-name-resolution-detector
rules:
- apiGroups:
- ""
resources:
- nodes
verbs:
- get
- list
- watch
- apiGroups:
- ""
resources:
- nodes/status
verbs:
- patch
- update
- apiGroups:
- ""
- events.k8s.io
resources:
- events
verbs:
- create
- patch
- update
- apiGroups:
- coordination.k8s.io
resources:
- leases
verbs:
- get
- list
- watch
- create
- patch
- update
- delete
---
apiVersion: v1
kind: ConfigMap
metadata:
name: karmada-kubeconfig
namespace: kube-system
data:
kubeconfig: |+
<karmada-kubeconfig>
```

View File

@ -0,0 +1,40 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"context"
"github.com/karmada-io/karmada/pkg/servicenameresolutiondetector/coredns"
)
func startCorednsDetector(ctx context.Context, detectorContext detectorContext) (bool, error) {
detector, err := coredns.NewCorednsDetector(
detectorContext.memberClient,
detectorContext.controlPlaneClient,
detectorContext.sharedInformers,
detectorContext.lec,
detectorContext.corednsConfig,
detectorContext.hostName,
detectorContext.clusterName,
)
if err != nil {
return false, err
}
go detector.Run(ctx)
return true, nil
}

View File

@ -0,0 +1,59 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package options
import (
"time"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// CorednsOptions contains options for coredns detector.
type CorednsOptions struct {
PeriodSeconds time.Duration
SuccessThreshold time.Duration
FailureThreshold time.Duration
StaleThreshold time.Duration
}
// NewCorednsOptions return default options for coredns detector.
func NewCorednsOptions() *CorednsOptions {
return &CorednsOptions{}
}
// AddFlags adds flags of coredns detector to the specified FlagSet.
func (o *CorednsOptions) AddFlags(fs *pflag.FlagSet) {
fs.DurationVar(&o.PeriodSeconds, "coredns-detect-period", 5*time.Second,
"Specifies how often detector detects coredns health status.")
fs.DurationVar(&o.SuccessThreshold, "coredns-success-threshold", 30*time.Second,
"The duration of successes for the coredns to be considered healthy after recovery.")
fs.DurationVar(&o.FailureThreshold, "coredns-failure-threshold", 30*time.Second,
"The duration of failure for the coredns to be considered unhealthy.")
fs.DurationVar(&o.StaleThreshold, "coredns-stale-threshold", time.Minute,
"If the node condition of coredns has not been updated for coredns-stale-threshold, it should be considered unknown.")
}
// Complete fills in fields required to have valid data.
func (o *CorednsOptions) Complete() error {
return nil
}
// Validate checks options and return a slice of found errs.
func (o *CorednsOptions) Validate() field.ErrorList {
return field.ErrorList{}
}

View File

@ -0,0 +1,141 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package options
import (
"fmt"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/spf13/pflag"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/leaderelection/resourcelock"
componentbaseconfig "k8s.io/component-base/config"
componentbaseoptions "k8s.io/component-base/config/options"
"github.com/karmada-io/karmada/pkg/karmadactl/util/apiclient"
)
// GenericOptions contains some generic options.
type GenericOptions struct {
KarmadaKubeConfig string
KarmadaContext string
KarmadaConfig *rest.Config
MemberClusterConfig *rest.Config
ClusterName string
Hostname string
BindAddress string
HealthzPort int
Detectors []string
LeaderElection componentbaseconfig.LeaderElectionConfiguration
}
// NewGenericOptions return default generic options.
func NewGenericOptions() *GenericOptions {
return &GenericOptions{
LeaderElection: componentbaseconfig.LeaderElectionConfiguration{
LeaderElect: true,
ResourceLock: resourcelock.LeasesResourceLock,
ResourceName: "cluster-problem-detector",
ResourceNamespace: "kube-system",
LeaseDuration: metav1.Duration{Duration: 15 * time.Second},
RetryPeriod: metav1.Duration{Duration: 2 * time.Second},
RenewDeadline: metav1.Duration{Duration: 10 * time.Second},
},
}
}
// AddFlags adds flags of generic options to the specified FlagSet.
func (o *GenericOptions) AddFlags(fs *pflag.FlagSet, allDetectors []string) {
fs.StringVar(&o.KarmadaKubeConfig, "karmada-kubeconfig", o.KarmadaKubeConfig, "Path to karmada control plane kubeconfig file.")
fs.StringVar(&o.KarmadaContext, "karmada-context", "", "Name of the cluster context in karmada control plane kubeconfig file.")
fs.StringVar(&o.ClusterName, "cluster-name", o.ClusterName, "Name of member cluster that the agent serves for.")
fs.StringVar(&o.Hostname, "host-name", o.Hostname, "Name of host that the agent runs on, used as lock holder identity.")
fs.StringVar(&o.BindAddress, "bind-address", "127.0.0.1", "The IP address on which to listen.")
fs.IntVar(&o.HealthzPort, "healthz-port", o.HealthzPort, "The port on which to serve health check.")
fs.StringSliceVar(&o.Detectors, "detectors", []string{"*"}, fmt.Sprintf(
"A list of detectors to enable. '*' enables all on-by-default detectors, 'foo' enables the detector named 'foo', '-foo' disables the detector named 'foo'. All detectors: %s.",
strings.Join(allDetectors, ", "),
))
componentbaseoptions.BindLeaderElectionFlags(&o.LeaderElection, fs)
}
// Complete fills in fields required to have valid data.
func (o *GenericOptions) Complete() error {
if o == nil {
return nil
}
controlPlaneRestConfig, err := apiclient.RestConfig(o.KarmadaContext, o.KarmadaKubeConfig)
if err != nil {
return fmt.Errorf("failed to build kubeconfig of karmada control plane: %v", err)
}
o.KarmadaConfig = controlPlaneRestConfig
memberClusterRestConfig, err := rest.InClusterConfig()
if err != nil {
return fmt.Errorf("failed to build in-cluster config: %v", err)
}
o.MemberClusterConfig = memberClusterRestConfig
hostName, err := os.Hostname()
if err != nil {
return fmt.Errorf("failed to get hostname: %v", err)
}
if len(o.Hostname) == 0 {
o.Hostname = hostName
}
return nil
}
// Validate checks options and return a slice of found errs.
func (o *GenericOptions) Validate() field.ErrorList {
errs := field.ErrorList{}
if err := validateAPIServerAddr(o.MemberClusterConfig.Host); err != nil {
errs = append(errs, field.InternalError(field.NewPath("InClusterConfig"), err))
}
return errs
}
func validateAPIServerAddr(addr string) error {
server, err := url.Parse(addr)
if err != nil {
return err
}
host, _, err := net.SplitHostPort(server.Host)
if err != nil {
return err
}
// The host must be an IP rather than a domain name.
if net.ParseIP(host) == nil {
return fmt.Errorf("server address of member cluster kubeconfig must be an IP")
}
return nil
}

View File

@ -0,0 +1,77 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package options
import (
"k8s.io/apimachinery/pkg/util/validation/field"
cliflag "k8s.io/component-base/cli/flag"
"github.com/karmada-io/karmada/pkg/sharedcli/klogflag"
)
// Options contains everything necessary to create and run cluster-problem-detector.
type Options struct {
Generic *GenericOptions
Coredns *CorednsOptions
}
// NewOptions return default options.
func NewOptions() *Options {
return &Options{
Generic: NewGenericOptions(),
Coredns: NewCorednsOptions(),
}
}
// Flags return all flag sets for options.
func (o *Options) Flags(allDetectors []string) cliflag.NamedFlagSets {
fss := cliflag.NamedFlagSets{}
o.Generic.AddFlags(fss.FlagSet("generic"), allDetectors)
o.Coredns.AddFlags(fss.FlagSet("coredns"))
klogflag.Add(fss.FlagSet("logs"))
return fss
}
// Complete fills in fields required to have valid data.
func (o *Options) Complete() error {
if o == nil {
return nil
}
if err := o.Generic.Complete(); err != nil {
return err
}
if err := o.Coredns.Complete(); err != nil {
return err
}
return nil
}
// Validate checks options and return a slice of found errs.
func (o *Options) Validate() field.ErrorList {
total := field.ErrorList{}
if errs := o.Generic.Validate(); len(errs) != 0 {
total = append(total, errs...)
}
if errs := o.Coredns.Validate(); len(errs) != 0 {
total = append(total, errs...)
}
return total
}

View File

@ -0,0 +1,226 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"context"
"fmt"
"net/http"
"time"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/leaderelection"
componentbaseconfig "k8s.io/component-base/config"
"k8s.io/component-base/term"
ctrlmgrhealthz "k8s.io/controller-manager/pkg/healthz"
"k8s.io/klog/v2"
"github.com/karmada-io/karmada/cmd/service-name-resolution-detector-example/app/options"
"github.com/karmada-io/karmada/cmd/service-name-resolution-detector-example/names"
karmada "github.com/karmada-io/karmada/pkg/generated/clientset/versioned"
"github.com/karmada-io/karmada/pkg/servicenameresolutiondetector/coredns"
"github.com/karmada-io/karmada/pkg/sharedcli"
)
// NewDetector creates a *cobra.Command object with default parameters.
func NewDetector(ctx context.Context) *cobra.Command {
opts := options.NewOptions()
cmd := &cobra.Command{
Use: "service-name-resolution-detector-example",
Long: `The service-name-resolution-detector-example is an agent deployed in member clusters. It can periodically detect health
condition of components in member cluster(such as coredns), and sync conditions to Karmada control plane.`,
RunE: func(cmd *cobra.Command, args []string) error {
if err := opts.Complete(); err != nil {
return err
}
if errs := opts.Validate(); len(errs) != 0 {
return errs.ToAggregate()
}
if err := runCmd(ctx, opts); err != nil {
return err
}
return nil
},
}
fss := opts.Flags(KnownDetectors())
fs := cmd.Flags()
for _, f := range fss.FlagSets {
fs.AddFlagSet(f)
}
cols, _, _ := term.TerminalSize(cmd.OutOrStdout())
sharedcli.SetUsageAndHelpFunc(cmd, fss, cols)
return cmd
}
func runCmd(ctx context.Context, opts *options.Options) error {
logger := klog.FromContext(ctx)
logger.Info("start cluster problem detector")
var checks []healthz.HealthChecker
var electionChecker *leaderelection.HealthzAdaptor
if opts.Generic.LeaderElection.LeaderElect {
electionChecker = leaderelection.NewLeaderHealthzAdaptor(20 * time.Second)
checks = append(checks, electionChecker)
}
detectorCtx, err := createDetectorContext(opts)
if err != nil {
logger.Error(err, "Error building detector context")
return err
}
for name, initFn := range NewDetectorInitializers() {
if !detectorCtx.IsDetectorEnabled(name) {
logger.Info("Warning: detector is disabled", "detector", name)
continue
}
logger.V(1).Info("Starting detector", "detector", name)
started, err := initFn(klog.NewContext(ctx, klog.LoggerWithName(logger, name)), detectorCtx)
if err != nil {
logger.Error(err, "Error starting detector", "detector", name)
return err
}
if !started {
logger.Info("Warning: skipping detector", "detector", name)
continue
}
checks = append(checks, ctrlmgrhealthz.NamedPingChecker(name))
logger.Info("Started detector", "detector", name)
}
detectorCtx.sharedInformers.Start(ctx.Done())
defer detectorCtx.sharedInformers.Shutdown()
for t, s := range detectorCtx.sharedInformers.WaitForCacheSync(ctx.Done()) {
if !s {
logger.Error(err, "Error starting informer", "informer", t)
return fmt.Errorf("informer %v not start", t)
}
}
go startHealthzServer(ctx, ctrlmgrhealthz.NewMutableHealthzHandler(checks...), opts.Generic.BindAddress, opts.Generic.HealthzPort)
<-ctx.Done()
return nil
}
var detectorsDisabledByDefault = sets.NewString()
// KnownDetectors return names of all detectors.
func KnownDetectors() []string {
return sets.StringKeySet(NewDetectorInitializers()).List()
}
type detectorContext struct {
controlPlaneClient karmada.Interface
memberClient kubernetes.Interface
sharedInformers informers.SharedInformerFactory
lec componentbaseconfig.LeaderElectionConfiguration
hostName string
clusterName string
detectors []string
corednsConfig *coredns.Config
}
func createDetectorContext(opts *options.Options) (detectorContext, error) {
controlPlaneClient := karmada.NewForConfigOrDie(opts.Generic.KarmadaConfig)
memberClient := kubernetes.NewForConfigOrDie(opts.Generic.MemberClusterConfig)
sharedInformers := informers.NewSharedInformerFactory(memberClient, 10*time.Minute)
detectorCtx := detectorContext{
controlPlaneClient: controlPlaneClient,
memberClient: memberClient,
sharedInformers: sharedInformers,
lec: opts.Generic.LeaderElection,
hostName: opts.Generic.Hostname,
clusterName: opts.Generic.ClusterName,
detectors: opts.Generic.Detectors,
corednsConfig: &coredns.Config{
PeriodSeconds: opts.Coredns.PeriodSeconds,
SuccessThreshold: opts.Coredns.SuccessThreshold,
FailureThreshold: opts.Coredns.FailureThreshold,
StaleThreshold: opts.Coredns.StaleThreshold,
},
}
return detectorCtx, nil
}
func (c detectorContext) IsDetectorEnabled(name string) bool {
hasStar := false
for _, detector := range c.detectors {
if detector == name {
return true
}
if detector == "-"+name {
return false
}
if detector == "*" {
hasStar = true
}
}
// if we get here, there was no explicit choice
if !hasStar {
// nothing on by default
return false
}
return !detectorsDisabledByDefault.Has(name)
}
// InitFunc inits a detector.
type InitFunc func(ctx context.Context, detectorContext detectorContext) (started bool, err error)
// NewDetectorInitializers registers init functions for all detectors.
func NewDetectorInitializers() map[string]InitFunc {
detectors := map[string]InitFunc{}
register := func(name string, fn InitFunc) {
if _, ok := detectors[name]; !ok {
detectors[name] = fn
} else {
panic(fmt.Sprintf("detector name %q was registered twice", name))
}
}
register(names.CorednsDetector, startCorednsDetector)
return detectors
}
func startHealthzServer(ctx context.Context, handler *ctrlmgrhealthz.MutableHealthzHandler, addr string, port int) {
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", addr, port),
Handler: handler,
MaxHeaderBytes: 1 << 20,
IdleTimeout: 90 * time.Second,
ReadHeaderTimeout: 32 * time.Second,
}
go func() {
err := server.ListenAndServe()
if err != nil {
klog.FromContext(ctx).Error(err, "Error starting healthz server")
}
}()
}

View File

@ -0,0 +1,33 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"os"
"k8s.io/component-base/cli"
controllerruntime "sigs.k8s.io/controller-runtime"
"github.com/karmada-io/karmada/cmd/service-name-resolution-detector-example/app"
)
func main() {
ctx := controllerruntime.SetupSignalHandler()
cmd := app.NewDetector(ctx)
code := cli.Run(cmd)
os.Exit(code)
}

View File

@ -0,0 +1,22 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package names
const (
// CorednsDetector detector for coredns
CorednsDetector = "coredns-detector"
)

1
go.mod
View File

@ -42,6 +42,7 @@ require (
k8s.io/code-generator v0.28.5
k8s.io/component-base v0.28.5
k8s.io/component-helpers v0.28.5
k8s.io/controller-manager v0.28.5
k8s.io/klog/v2 v2.100.1
k8s.io/kube-aggregator v0.28.5
k8s.io/kube-openapi v0.0.0-20230717233707-2695361300d9

2
go.sum
View File

@ -1425,6 +1425,8 @@ k8s.io/component-base v0.28.5 h1:uFCW7USa8Fpme8dVtn2ZrdVaUPBRDwYJ+kNrV9OO1Cc=
k8s.io/component-base v0.28.5/go.mod h1:gw2d8O28okS9RrsPuJnD2mFl2It0HH9neHiGi2xoXcY=
k8s.io/component-helpers v0.28.5 h1:m5exEWY9K09MZbBZxijH53Y/bGwEqi8P2YDCxJgqRqk=
k8s.io/component-helpers v0.28.5/go.mod h1:Ymn6cHZraT1gqikjzmWppZt1D8Msku3Ks499nSIfyes=
k8s.io/controller-manager v0.28.5 h1:RRJHgMLO5jzTjAbW4Lwsk5/f+EMLvSsYwu90+CMx278=
k8s.io/controller-manager v0.28.5/go.mod h1:XjK8aEaT3JbAXQ2nhDB7m7m2eVQLZbm6UVCOtihacRU=
k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0=
k8s.io/gengo v0.0.0-20200114144118-36b2048a9120/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0=
k8s.io/gengo v0.0.0-20220902162205-c0856e24416d h1:U9tB195lKdzwqicbJvyJeOXV7Klv+wNAWENRnXEGi08=

View File

@ -0,0 +1,290 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package coredns
import (
"context"
"fmt"
"net"
"os"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
componentbaseconfig "k8s.io/component-base/config"
"k8s.io/klog/v2"
karmada "github.com/karmada-io/karmada/pkg/generated/clientset/versioned"
"github.com/karmada-io/karmada/pkg/servicenameresolutiondetector/store"
)
const (
name = "coredns-detector"
condType = "ServiceDomainNameResolutionReady"
serviceDomainNameResolutionReady = "ServiceDomainNameResolutionReady"
serviceDomainNameResolutionFailed = "ServiceDomainNameResolutionFailed"
)
var localReference = &corev1.ObjectReference{
APIVersion: "v1",
Kind: "Pod",
Name: os.Getenv("POD_NAME"),
Namespace: os.Getenv("POD_NAMESPACE"),
}
// Config contains config of coredns detector.
type Config struct {
PeriodSeconds time.Duration
SuccessThreshold time.Duration
FailureThreshold time.Duration
StaleThreshold time.Duration
}
// Detector detects DNS failure and syncs conditions to control plane periodically.
type Detector struct {
memberClusterClient kubernetes.Interface
karmadaClient karmada.Interface
lec leaderelection.LeaderElectionConfig
periodSeconds time.Duration
conditionCache store.ConditionCache
conditionStore store.ConditionStore
cacheSynced []cache.InformerSynced
nodeName string
clusterName string
queue workqueue.RateLimitingInterface
eventBroadcaster record.EventBroadcaster
eventRecorder record.EventRecorder
}
// NewCorednsDetector returns an instance of coredns detector.
func NewCorednsDetector(memberClusterClient kubernetes.Interface, karmadaClient karmada.Interface, informers informers.SharedInformerFactory,
baselec componentbaseconfig.LeaderElectionConfiguration, cfg *Config, hostName, clusterName string) (*Detector, error) {
broadcaster := record.NewBroadcaster()
recorder := broadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: name})
var rl resourcelock.Interface
var err error
if baselec.LeaderElect {
rl, err = resourcelock.New(
baselec.ResourceLock,
baselec.ResourceNamespace,
baselec.ResourceName+"-"+name,
memberClusterClient.CoreV1(),
memberClusterClient.CoordinationV1(),
resourcelock.ResourceLockConfig{Identity: hostName},
)
if err != nil {
return nil, err
}
}
nodeInformer := informers.Core().V1().Nodes()
return &Detector{
memberClusterClient: memberClusterClient,
karmadaClient: karmadaClient,
nodeName: hostName,
clusterName: clusterName,
periodSeconds: cfg.PeriodSeconds,
conditionCache: store.NewConditionCache(cfg.SuccessThreshold, cfg.FailureThreshold),
conditionStore: store.NewNodeConditionStore(memberClusterClient.CoreV1().Nodes(), nodeInformer.Lister(), condType, cfg.StaleThreshold),
cacheSynced: []cache.InformerSynced{nodeInformer.Informer().HasSynced},
eventBroadcaster: broadcaster,
eventRecorder: recorder,
queue: workqueue.NewRateLimitingQueueWithConfig(workqueue.DefaultControllerRateLimiter(), workqueue.RateLimitingQueueConfig{Name: name}),
lec: leaderelection.LeaderElectionConfig{
Lock: rl,
LeaseDuration: baselec.LeaseDuration.Duration,
RenewDeadline: baselec.RenewDeadline.Duration,
RetryPeriod: baselec.RetryPeriod.Duration,
}}, nil
}
// Run starts the detector.
func (d *Detector) Run(ctx context.Context) {
defer runtime.HandleCrash()
d.eventBroadcaster.StartStructuredLogging(0)
d.eventBroadcaster.StartRecordingToSink(&v1.EventSinkImpl{Interface: d.memberClusterClient.CoreV1().Events("")})
defer d.eventBroadcaster.Shutdown()
defer d.queue.ShutDown()
logger := klog.FromContext(ctx)
logger.Info("Starting coredns detector")
defer logger.Info("Shutting down coredns detector")
if !cache.WaitForCacheSync(ctx.Done(), d.cacheSynced...) {
return
}
go func() {
wait.Until(func() {
defer runtime.HandleCrash()
observed := lookupOnce(logger)
curr, err := d.conditionStore.Load(d.nodeName)
if err != nil {
d.eventRecorder.Eventf(localReference, corev1.EventTypeWarning, "LoadCorednsConditionFailed", "failed to load condition: %v", err)
return
}
cond := d.conditionCache.ThresholdAdjustedCondition(d.nodeName, curr, observed)
if err = d.conditionStore.Store(d.nodeName, cond); err != nil {
d.eventRecorder.Eventf(localReference, corev1.EventTypeWarning, "StoreCorednsConditionFailed", "failed to store condition: %v", err)
return
}
d.queue.Add(0)
}, d.periodSeconds, ctx.Done())
}()
if d.lec.Lock != nil {
d.lec.Callbacks = leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
wait.UntilWithContext(ctx, d.worker, time.Second)
},
OnStoppedLeading: func() {
logger.Error(nil, "leader election lost")
klog.FlushAndExit(klog.ExitFlushTimeout, 1)
},
}
leaderelection.RunOrDie(ctx, d.lec)
} else {
wait.UntilWithContext(ctx, d.worker, time.Second)
}
}
func (d *Detector) worker(ctx context.Context) {
for d.processNextWorkItem(ctx) {
}
}
func (d *Detector) processNextWorkItem(ctx context.Context) bool {
key, quit := d.queue.Get()
if quit {
return false
}
defer d.queue.Done(key)
if err := d.sync(ctx); err != nil {
runtime.HandleError(fmt.Errorf("failed to sync corendns condition to control plane, requeuing: %v", err))
d.queue.AddRateLimited(key)
} else {
d.queue.Forget(key)
}
return true
}
func lookupOnce(logger klog.Logger) *metav1.Condition {
logger.Info("lookup service name once")
observed := &metav1.Condition{Type: condType, LastTransitionTime: metav1.Now()}
if _, err := net.LookupHost("kubernetes.default"); err != nil {
logger.Error(err, "nslookup failed")
observed.Status = metav1.ConditionFalse
observed.Reason = serviceDomainNameResolutionFailed
observed.Message = err.Error()
} else {
observed.Status = metav1.ConditionTrue
}
return observed
}
func (d *Detector) sync(ctx context.Context) error {
logger := klog.FromContext(ctx)
skip, alarm, err := d.shouldAlarm()
if err != nil {
return err
}
if skip {
logger.Info("skip syncing to control plane since nodes with condition Unknown")
return nil
}
cond, err := d.newClusterCondition(alarm)
if err != nil {
return err
}
cluster, err := d.karmadaClient.ClusterV1alpha1().Clusters().Get(ctx, d.clusterName, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
logger.Info(fmt.Sprintf("cluster %s not found, skip sync coredns condition", d.clusterName))
return nil
}
return err
}
if !cluster.DeletionTimestamp.IsZero() {
logger.Info(fmt.Sprintf("cluster %s is deleting, skip sync coredns condition", d.clusterName))
return nil
}
meta.SetStatusCondition(&cluster.Status.Conditions, *cond)
_, err = d.karmadaClient.ClusterV1alpha1().Clusters().UpdateStatus(ctx, cluster, metav1.UpdateOptions{})
return err
}
func (d *Detector) newClusterCondition(alarm bool) (*metav1.Condition, error) {
cond := &metav1.Condition{Type: condType}
if alarm {
cond.Status = metav1.ConditionFalse
cond.Reason = serviceDomainNameResolutionFailed
cond.Message = "service domain name resolution is unready"
} else {
cond.Status = metav1.ConditionTrue
cond.Reason = serviceDomainNameResolutionReady
cond.Message = "service domain name resolution is ready"
}
return cond, nil
}
func (d *Detector) shouldAlarm() (skip bool, alarm bool, err error) {
conditions, err := d.conditionStore.ListAll()
if err != nil {
return false, false, err
}
if len(conditions) == 0 {
return true, false, nil
}
hasUnknown, allFalse := false, true
for _, cond := range conditions {
switch cond.Status {
case metav1.ConditionUnknown:
hasUnknown = true
case metav1.ConditionFalse:
default:
allFalse = false
}
}
return hasUnknown, allFalse, nil
}

View File

@ -0,0 +1,104 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package store
import (
"sync"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type detectCondition struct {
// condition is the last observed condition of the detection.
condition metav1.Condition
// thresholdStartTime is the time that the condition changed.
thresholdStartTime time.Time
}
// ConditionCache caches observed conditions until threshold.
type ConditionCache struct {
conditionMap sync.Map
// successThreshold is the duration of successes for the condition to be considered healthy after recovery.
successThreshold time.Duration
// failureThreshold is the duration of failure for the condition to be considered unhealthy.
failureThreshold time.Duration
}
// NewConditionCache returns a cache for condition.
func NewConditionCache(successThreshold, failureThreshold time.Duration) ConditionCache {
return ConditionCache{
conditionMap: sync.Map{},
successThreshold: successThreshold,
failureThreshold: failureThreshold,
}
}
// ThresholdAdjustedCondition adjusts conditions according to the threshold.
func (c *ConditionCache) ThresholdAdjustedCondition(key string, curr, observed *metav1.Condition) *metav1.Condition {
saved := c.get(key)
if saved == nil {
// first detect
c.update(key, &detectCondition{
condition: *observed.DeepCopy(),
thresholdStartTime: time.Now(),
})
return observed
}
if curr == nil {
return observed
}
now := time.Now()
if saved.condition.Status != observed.Status {
// condition status changed, record the threshold start time
saved = &detectCondition{
condition: *observed.DeepCopy(),
thresholdStartTime: now,
}
c.update(key, saved)
}
var threshold time.Duration
if observed.Status == metav1.ConditionTrue {
threshold = c.successThreshold
} else {
threshold = c.failureThreshold
}
// we only care about true/not true
// for unknown->false, just return the observed ready condition
if ((observed.Status == metav1.ConditionTrue && curr.Status != metav1.ConditionTrue) ||
(observed.Status != metav1.ConditionTrue && curr.Status == metav1.ConditionTrue)) &&
now.Before(saved.thresholdStartTime.Add(threshold)) {
// retain old status until threshold exceeded.
return curr
}
return observed
}
func (c *ConditionCache) get(key string) *detectCondition {
condition, ok := c.conditionMap.Load(key)
if !ok {
return nil
}
return condition.(*detectCondition)
}
func (c *ConditionCache) update(key string, data *detectCondition) {
c.conditionMap.Store(key, data)
}

View File

@ -0,0 +1,153 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package store
import (
"context"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
listcorev1 "k8s.io/client-go/listers/core/v1"
"github.com/karmada-io/karmada/pkg/util/helper"
)
type nodeStore struct {
nodeClient typedcorev1.NodeInterface
nodeLister listcorev1.NodeLister
conditionType corev1.NodeConditionType
staleThreshold time.Duration
}
// NewNodeConditionStore returns a store for node conditions.
func NewNodeConditionStore(client typedcorev1.NodeInterface, lister listcorev1.NodeLister, conditionType string, staleThreshold time.Duration) ConditionStore {
return &nodeStore{
nodeClient: client,
nodeLister: lister,
conditionType: corev1.NodeConditionType(conditionType),
staleThreshold: staleThreshold,
}
}
func (n *nodeStore) Load(key string) (*metav1.Condition, error) {
node, err := n.nodeLister.Get(key)
if err != nil {
return nil, err
}
return NodeCondition2MetaV1Condition(FindNodeStatusCondition(node.Status.Conditions, n.conditionType)), nil
}
func (n *nodeStore) Store(key string, cond *metav1.Condition) error {
node, err := n.nodeLister.Get(key)
if err != nil {
return err
}
// do not modify on node returned from lister
node = node.DeepCopy()
SetNodeStatusCondition(&node.Status.Conditions, MetaV1Condition2NodeCondition(*cond))
_, err = n.nodeClient.UpdateStatus(context.Background(), node, metav1.UpdateOptions{})
return err
}
func (n *nodeStore) ListAll() ([]metav1.Condition, error) {
nodes, err := n.nodeLister.List(labels.Everything())
if err != nil {
return nil, err
}
conditions := make([]metav1.Condition, 0, len(nodes))
for _, node := range nodes {
if !helper.NodeReady(node) {
// skip node if not ready
continue
}
nodeCond := FindNodeStatusCondition(node.Status.Conditions, n.conditionType)
if nodeCond == nil || time.Since(nodeCond.LastHeartbeatTime.Time) > n.staleThreshold {
// if the node condition was absent or was too stale, we regard it as Unknown.
nodeCond = &corev1.NodeCondition{Type: n.conditionType, Status: corev1.ConditionUnknown}
}
conditions = append(conditions, *NodeCondition2MetaV1Condition(nodeCond))
}
return conditions, nil
}
// MetaV1Condition2NodeCondition converts metav1.Condition to corev1.NodeCondition.
func MetaV1Condition2NodeCondition(cond metav1.Condition) corev1.NodeCondition {
return corev1.NodeCondition{
Type: corev1.NodeConditionType(cond.Type),
Status: corev1.ConditionStatus(cond.Status),
LastTransitionTime: cond.LastTransitionTime,
Reason: cond.Reason,
Message: cond.Message,
}
}
// NodeCondition2MetaV1Condition converts corev1.NodeCondition to metav1.Condition.
func NodeCondition2MetaV1Condition(cond *corev1.NodeCondition) *metav1.Condition {
if cond == nil {
return nil
}
return &metav1.Condition{
Type: string(cond.Type),
Status: metav1.ConditionStatus(cond.Status),
LastTransitionTime: cond.LastTransitionTime,
Reason: cond.Reason,
Message: cond.Message,
}
}
// SetNodeStatusCondition set the condition into node conditions.
func SetNodeStatusCondition(conditions *[]corev1.NodeCondition, newCondition corev1.NodeCondition) {
if conditions == nil {
return
}
existingCondition := FindNodeStatusCondition(*conditions, newCondition.Type)
if existingCondition == nil {
if newCondition.LastTransitionTime.IsZero() {
newCondition.LastTransitionTime = metav1.Now()
}
newCondition.LastHeartbeatTime = metav1.Now()
*conditions = append(*conditions, newCondition)
return
}
if existingCondition.Status != newCondition.Status {
existingCondition.Status = newCondition.Status
if !newCondition.LastTransitionTime.IsZero() {
existingCondition.LastTransitionTime = newCondition.LastTransitionTime
} else {
existingCondition.LastTransitionTime = metav1.NewTime(time.Now())
}
}
existingCondition.Reason = newCondition.Reason
existingCondition.Message = newCondition.Message
existingCondition.LastHeartbeatTime = metav1.Now()
}
// FindNodeStatusCondition returns the condition with the specific type.
func FindNodeStatusCondition(conditions []corev1.NodeCondition, conditionType corev1.NodeConditionType) *corev1.NodeCondition {
for i := range conditions {
if conditions[i].Type == conditionType {
return &conditions[i]
}
}
return nil
}

View File

@ -0,0 +1,26 @@
/*
Copyright 2024 The Karmada Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package store
import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
// ConditionStore provides an interface to load or store conditions.
type ConditionStore interface {
Load(key string) (*metav1.Condition, error)
Store(key string, cond *metav1.Condition) error
ListAll() ([]metav1.Condition, error)
}

201
vendor/k8s.io/controller-manager/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,68 @@
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthz
import (
"net/http"
"sync"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/apiserver/pkg/server/mux"
)
// MutableHealthzHandler returns a http.Handler that handles "/healthz"
// following the standard healthz mechanism.
//
// This handler can register health checks after its creation, which
// is originally not allowed with standard healthz handler.
type MutableHealthzHandler struct {
// handler is the underlying handler that will be replaced every time
// new checks are added.
handler http.Handler
// mutex is a RWMutex that allows concurrent health checks (read)
// but disallow replacing the handler at the same time (write).
mutex sync.RWMutex
checks []healthz.HealthChecker
}
func (h *MutableHealthzHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
h.mutex.RLock()
defer h.mutex.RUnlock()
h.handler.ServeHTTP(writer, request)
}
// AddHealthChecker adds health check(s) to the handler.
//
// Every time this function is called, the handler have to be re-initiated.
// It is advised to add as many checks at once as possible.
func (h *MutableHealthzHandler) AddHealthChecker(checks ...healthz.HealthChecker) {
h.mutex.Lock()
defer h.mutex.Unlock()
h.checks = append(h.checks, checks...)
newMux := mux.NewPathRecorderMux("healthz")
healthz.InstallHandler(newMux, h.checks...)
h.handler = newMux
}
func NewMutableHealthzHandler(checks ...healthz.HealthChecker) *MutableHealthzHandler {
h := &MutableHealthzHandler{}
h.AddHealthChecker(checks...)
return h
}

View File

@ -0,0 +1,43 @@
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package healthz
import (
"net/http"
"k8s.io/apiserver/pkg/server/healthz"
)
// NamedPingChecker returns a health check with given name
// that returns no error when checked.
func NamedPingChecker(name string) healthz.HealthChecker {
return NamedHealthChecker(name, healthz.PingHealthz)
}
// NamedHealthChecker creates a named health check from
// an unnamed one.
func NamedHealthChecker(name string, check UnnamedHealthChecker) healthz.HealthChecker {
return healthz.NamedCheck(name, check.Check)
}
// UnnamedHealthChecker is an unnamed healthz checker.
// The name of the check can be set by the controller manager.
type UnnamedHealthChecker interface {
Check(req *http.Request) error
}
var _ UnnamedHealthChecker = (healthz.HealthChecker)(nil)

3
vendor/modules.txt vendored
View File

@ -1535,6 +1535,9 @@ k8s.io/component-helpers/apimachinery/lease
k8s.io/component-helpers/node/topology
k8s.io/component-helpers/scheduling/corev1
k8s.io/component-helpers/scheduling/corev1/nodeaffinity
# k8s.io/controller-manager v0.28.5
## explicit; go 1.20
k8s.io/controller-manager/pkg/healthz
# k8s.io/gengo v0.0.0-20220902162205-c0856e24416d
## explicit; go 1.13
k8s.io/gengo/args