ingress-nginx-helm/internal/ingress/status/status.go

406 lines
11 KiB
Go
Raw Normal View History

/*
Copyright 2015 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 status
import (
"context"
"fmt"
2016-12-16 17:37:47 +00:00
"net"
"regexp"
"sort"
"strings"
"time"
2020-08-08 23:31:02 +00:00
"k8s.io/klog/v2"
pool "gopkg.in/go-playground/pool.v3"
2017-09-17 18:42:31 +00:00
apiv1 "k8s.io/api/core/v1"
v1 "k8s.io/api/networking/v1"
2017-09-17 18:42:31 +00:00
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2017-04-01 14:39:42 +00:00
"k8s.io/apimachinery/pkg/labels"
2018-06-23 13:10:27 +00:00
"k8s.io/apimachinery/pkg/util/wait"
2017-04-01 14:39:42 +00:00
clientset "k8s.io/client-go/kubernetes"
2017-11-07 22:02:12 +00:00
"k8s.io/ingress-nginx/internal/k8s"
"k8s.io/ingress-nginx/internal/task"
"k8s.io/ingress-nginx/pkg/apis/ingress"
)
// UpdateInterval defines the time interval, in seconds, in
// which the status should check if an update is required.
var UpdateInterval = 60
// Syncer is an interface that implements syncer
2019-03-08 00:20:34 +00:00
type Syncer interface {
Run(chan struct{})
Shutdown()
}
type ingressLister interface {
// ListIngresses returns the list of Ingresses
2020-09-25 21:45:13 +00:00
ListIngresses() []*ingress.Ingress
}
// Config is a structure that implements Client interfaces
type Config struct {
Client clientset.Interface
PublishService string
PublishStatusAddress string
UpdateStatusOnShutdown bool
UseNodeInternalIP bool
IngressLister ingressLister
}
// statusSync keeps the status IP in each Ingress rule updated executing a periodic check
// in all the defined rules. To simplify the process leader election is used so the update
// is executed only in one node (Ingress controllers can be scaled to more than one)
// If the controller is running with the flag --publish-service (with a valid service)
// the IP address behind the service is used, if it is running with the flag
// --publish-status-address, the address specified in the flag is used, if neither of the
// two flags are set, the source is the IP/s of the node/s
type statusSync struct {
Config
2019-03-08 00:20:34 +00:00
// workqueue used to keep in sync the status IP/s
// in the Ingress rules
syncQueue *task.Queue
}
2019-03-08 00:20:34 +00:00
// Start starts the loop to keep the status in sync
func (s *statusSync) Run(stopCh chan struct{}) {
2019-03-08 00:20:34 +00:00
go s.syncQueue.Run(time.Second, stopCh)
2019-03-08 00:20:34 +00:00
// trigger initial sync
s.syncQueue.EnqueueTask(task.GetDummyObject("sync status"))
2019-03-08 00:20:34 +00:00
// when this instance is the leader we need to enqueue
// an item to trigger the update of the Ingress status.
//nolint:staticcheck // TODO: will replace it since wait.PollUntil is deprecated
err := wait.PollUntil(time.Duration(UpdateInterval)*time.Second, func() (bool, error) {
2019-03-08 00:20:34 +00:00
s.syncQueue.EnqueueTask(task.GetDummyObject("sync status"))
return false, nil
}, stopCh)
if err != nil {
klog.ErrorS(err, "error running poll")
}
2017-08-15 21:34:36 +00:00
}
2019-03-08 00:20:34 +00:00
// Shutdown stops the sync. In case the instance is the leader it will remove the current IP
// if there is no other instances running.
func (s *statusSync) Shutdown() {
go s.syncQueue.Shutdown()
if !s.UpdateStatusOnShutdown {
2018-12-05 16:27:55 +00:00
klog.Warningf("skipping update of status of Ingress rules")
return
}
2017-07-14 13:30:58 +00:00
addrs, err := s.runningAddresses()
if err != nil {
2020-09-27 20:32:40 +00:00
klog.ErrorS(err, "error obtaining running IP address")
return
}
2016-12-16 17:37:47 +00:00
if len(addrs) > 1 {
// leave the job to the next leader
2020-09-27 20:32:40 +00:00
klog.InfoS("leaving status update for next leader")
return
}
if s.isRunningMultiplePods() {
2020-09-27 20:32:40 +00:00
klog.V(2).InfoS("skipping Ingress status update (multiple pods running - another one will be elected as master)")
return
}
2020-09-27 20:32:40 +00:00
klog.InfoS("removing value from ingress status", "address", addrs)
s.updateStatus([]v1.IngressLoadBalancerIngress{})
}
func (s *statusSync) sync(_ interface{}) error {
2017-03-31 12:46:51 +00:00
if s.syncQueue.IsShuttingDown() {
2020-09-27 20:32:40 +00:00
klog.V(2).InfoS("skipping Ingress status update (shutting down in progress)")
2017-03-31 12:46:51 +00:00
return nil
}
2017-07-14 13:30:58 +00:00
addrs, err := s.runningAddresses()
if err != nil {
return err
}
s.updateStatus(standardizeLoadBalancerIngresses(addrs))
return nil
}
func (s *statusSync) keyfunc(input interface{}) (interface{}, error) {
return input, nil
}
2019-03-08 00:20:34 +00:00
// NewStatusSyncer returns a new Syncer instance
2020-09-26 23:27:19 +00:00
func NewStatusSyncer(config Config) Syncer {
st := &statusSync{
2017-09-11 21:56:20 +00:00
Config: config,
}
st.syncQueue = task.NewCustomTaskQueue(st.sync, st.keyfunc)
return st
}
func nameOrIPToLoadBalancerIngress(nameOrIP string) v1.IngressLoadBalancerIngress {
if net.ParseIP(nameOrIP) != nil {
return v1.IngressLoadBalancerIngress{IP: nameOrIP}
}
return v1.IngressLoadBalancerIngress{Hostname: nameOrIP}
}
2017-07-14 13:30:58 +00:00
// runningAddresses returns a list of IP addresses and/or FQDN where the
2016-12-16 17:37:47 +00:00
// ingress controller is currently running
func (s *statusSync) runningAddresses() ([]v1.IngressLoadBalancerIngress, error) {
if s.PublishStatusAddress != "" {
re := regexp.MustCompile(`,\s*`)
multipleAddrs := re.Split(s.PublishStatusAddress, -1)
addrs := make([]v1.IngressLoadBalancerIngress, len(multipleAddrs))
for i, addr := range multipleAddrs {
addrs[i] = nameOrIPToLoadBalancerIngress(addr)
}
return addrs, nil
}
if s.PublishService != "" {
return statusAddressFromService(s.PublishService, s.Client)
}
// get information about all the pods running the ingress controller
pods, err := s.Client.CoreV1().Pods(k8s.IngressPodDetails.Namespace).List(context.TODO(), metav1.ListOptions{
LabelSelector: labels.SelectorFromSet(k8s.IngressPodDetails.Labels).String(),
})
if err != nil {
return nil, err
}
addrs := make([]v1.IngressLoadBalancerIngress, 0)
2020-12-04 12:40:42 +00:00
for i := range pods.Items {
pod := pods.Items[i]
// only Running pods are valid
if pod.Status.Phase != apiv1.PodRunning {
continue
}
2020-10-12 23:22:16 +00:00
// only Ready pods are valid
isPodReady := false
for _, cond := range pod.Status.Conditions {
if cond.Type == apiv1.PodReady && cond.Status == apiv1.ConditionTrue {
isPodReady = true
break
}
}
if !isPodReady {
klog.InfoS("POD is not ready", "pod", klog.KObj(&pod), "node", pod.Spec.NodeName)
continue
}
2017-11-06 01:22:49 +00:00
name := k8s.GetNodeIPOrName(s.Client, pod.Spec.NodeName, s.UseNodeInternalIP)
if !stringInIngresses(name, addrs) {
addrs = append(addrs, nameOrIPToLoadBalancerIngress(name))
}
}
2017-11-06 01:22:49 +00:00
2016-12-16 17:56:27 +00:00
return addrs, nil
}
func (s *statusSync) isRunningMultiplePods() bool {
// As a standard, app.kubernetes.io are "reserved well-known" labels.
// In our case, we add those labels as identifiers of the Ingress
// deployment in this namespace, so we can select it as a set of Ingress instances.
// As those labels are also generated as part of a HELM deployment, we can be "safe" they
// cover 95% of the cases
podLabel := make(map[string]string)
for k, v := range k8s.IngressPodDetails.Labels {
if k != "pod-template-hash" && k != "controller-revision-hash" && k != "pod-template-generation" {
podLabel[k] = v
}
}
pods, err := s.Client.CoreV1().Pods(k8s.IngressPodDetails.Namespace).List(context.TODO(), metav1.ListOptions{
LabelSelector: labels.SelectorFromSet(podLabel).String(),
})
if err != nil {
return false
}
return len(pods.Items) > 1
}
// standardizeLoadBalancerIngresses sorts the list of loadbalancer by
// IP
func standardizeLoadBalancerIngresses(lbi []v1.IngressLoadBalancerIngress) []v1.IngressLoadBalancerIngress {
2017-09-25 19:40:55 +00:00
sort.SliceStable(lbi, func(a, b int) bool {
return lbi[a].IP < lbi[b].IP
})
return lbi
}
// updateStatus changes the status information of Ingress rules
func (s *statusSync) updateStatus(newIngressPoint []v1.IngressLoadBalancerIngress) {
2020-09-25 21:45:13 +00:00
ings := s.IngressLister.ListIngresses()
p := pool.NewLimited(10)
defer p.Close()
batch := p.Batch()
sort.SliceStable(newIngressPoint, lessLoadBalancerIngress(newIngressPoint))
for _, ing := range ings {
curIPs := ing.Status.LoadBalancer.Ingress
sort.SliceStable(curIPs, lessLoadBalancerIngress(curIPs))
if ingressSliceEqual(curIPs, newIngressPoint) {
2020-09-27 20:32:40 +00:00
klog.V(3).InfoS("skipping update of Ingress (no change)", "namespace", ing.Namespace, "ingress", ing.Name)
continue
}
2017-11-05 01:18:28 +00:00
batch.Queue(runUpdate(ing, newIngressPoint, s.Client))
}
batch.QueueComplete()
batch.WaitAll()
}
func runUpdate(ing *ingress.Ingress, status []v1.IngressLoadBalancerIngress,
client clientset.Interface,
) pool.WorkFunc {
return func(wu pool.WorkUnit) (interface{}, error) {
if wu.IsCancelled() {
return nil, nil
}
Release v1 (#7470) * Drop v1beta1 from ingress nginx (#7156) * Drop v1beta1 from ingress nginx Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix intorstr logic in controller Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * fixing admission Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * more intorstr fixing * correct template rendering Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix e2e tests for v1 api Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix gofmt errors * This is finally working...almost there... Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Re-add removed validation of AdmissionReview * Prepare for v1.0.0-alpha.1 release Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Update changelog and matrix table for v1.0.0-alpha.1 (#7274) Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * add docs for syslog feature (#7219) * Fix link to e2e-tests.md in developer-guide (#7201) * Use ENV expansion for namespace in args (#7146) Update the DaemonSet namespace references to use the `POD_NAMESPACE` environment variable in the same way that the Deployment does. * chart: using Helm builtin capabilities check (#7190) Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> * Update proper default value for HTTP2MaxConcurrentStreams in Docs (#6944) It should be 128 as documented in https://github.com/kubernetes/ingress-nginx/blob/master/internal/ingress/controller/config/config.go#L780 * Fix MaxWorkerOpenFiles calculation on high cores nodes (#7107) * Fix MaxWorkerOpenFiles calculation on high cores nodes * Add e2e test for rlimit_nofile * Fix doc for max-worker-open-files * ingress/tcp: add additional error logging on failed (#7208) * Add file containing stable release (#7313) * Handle named (non-numeric) ports correctly (#7311) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Updated v1beta1 to v1 as its deprecated (#7308) * remove mercurial from build (#7031) * Retry to download maxmind DB if it fails (#7242) * Retry to download maxmind DB if it fails. Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Add retries count arg, move retry logic into DownloadGeoLite2DB function Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Reorder parameters in DownloadGeoLite2DB Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Remove hardcoded value Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Release v1.0.0-alpha.1 * Add changelog for v1.0.0-alpha.2 * controller: ignore non-service backends (#7332) * controller: ignore non-service backends Signed-off-by: Carlos Panato <ctadeu@gmail.com> * update per feedback Signed-off-by: Carlos Panato <ctadeu@gmail.com> * fix: allow scope/tcp/udp configmap namespace to altered (#7161) * Lower webhook timeout for digital ocean (#7319) * Lower webhook timeout for digital ocean * Set Digital Ocean value controller.admissionWebhooks.timeoutSeconds to 29 * update OWNERS and aliases files (#7365) (#7366) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Downgrade Lua modules for s390x (#7355) Downgrade Lua modules to last known working version. * Fix IngressClass logic for newer releases (#7341) * Fix IngressClass logic for newer releases Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Change e2e tests for the new IngressClass presence * Fix chart and admission tests Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix helm chart test Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix reviews * Remove ingressclass code from admission * update tag to v1.0.0-beta.1 * update readme and changelog for v1.0.0-beta.1 * Release v1.0.0-beta.1 - helm and manifests (#7422) * Change the order of annotation just to trigger a new helm release (#7425) * [cherry-pick] Add dev-v1 branch into helm releaser (#7428) * Add dev-v1 branch into helm releaser (#7424) * chore: add link for artifacthub.io/prerelease annotations Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * k8s job ci pipeline for dev-v1 br v1.22.0 (#7453) * k8s job ci pipeline for dev-v1 br v1.22.0 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * k8s job ci pipeline for dev-v1 br v1.21.2 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * remove v1.21.1 version Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * Add controller.watchIngressWithoutClass config option (#7459) Signed-off-by: Akshit Grover <akshit.grover2016@gmail.com> * Release new helm chart with certgen fixed (#7478) * Update go version, modules and remove ioutil * Release new helm chart with certgen fixed * changed appversion, chartversion, TAG, image (#7490) * Fix CI conflict * Fix CI conflict * Fix build.sh from rebase process * Fix controller_test post rebase Co-authored-by: Tianhao Guo <rggth09@gmail.com> Co-authored-by: Ray <61553+rctay@users.noreply.github.com> Co-authored-by: Bill Cassidy <cassid4@gmail.com> Co-authored-by: Jintao Zhang <tao12345666333@163.com> Co-authored-by: Sathish Ramani <rsathishx87@gmail.com> Co-authored-by: Mansur Marvanov <nanorobocop@gmail.com> Co-authored-by: Matt1360 <568198+Matt1360@users.noreply.github.com> Co-authored-by: Carlos Tadeu Panato Junior <ctadeu@gmail.com> Co-authored-by: Kundan Kumar <kundan.kumar@india.nec.com> Co-authored-by: Tom Hayward <thayward@infoblox.com> Co-authored-by: Sergey Shakuto <sshakuto@infoblox.com> Co-authored-by: Tore <tore.lonoy@gmail.com> Co-authored-by: Bouke Versteegh <info@boukeversteegh.nl> Co-authored-by: Shahid <shahid@us.ibm.com> Co-authored-by: James Strong <strong.james.e@gmail.com> Co-authored-by: Long Wu Yuan <longwuyuan@gmail.com> Co-authored-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Neha Lohia <nehapithadiya444@gmail.com> Co-authored-by: Akshit Grover <akshit.grover2016@gmail.com>
2021-08-21 20:42:00 +00:00
ingClient := client.NetworkingV1().Ingresses(ing.Namespace)
currIng, err := ingClient.Get(context.TODO(), ing.Name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("unexpected error searching Ingress %s/%s: %w", ing.Namespace, ing.Name, err)
}
2020-09-27 20:32:40 +00:00
klog.InfoS("updating Ingress status", "namespace", currIng.Namespace, "ingress", currIng.Name, "currentValue", currIng.Status.LoadBalancer.Ingress, "newValue", status)
currIng.Status.LoadBalancer.Ingress = status
_, err = ingClient.UpdateStatus(context.TODO(), currIng, metav1.UpdateOptions{})
if err != nil {
klog.Warningf("error updating ingress rule: %v", err)
}
return true, nil
}
}
func lessLoadBalancerIngress(addrs []v1.IngressLoadBalancerIngress) func(int, int) bool {
return func(a, b int) bool {
switch strings.Compare(addrs[a].Hostname, addrs[b].Hostname) {
case -1:
return true
case 1:
return false
}
return addrs[a].IP < addrs[b].IP
}
}
func ingressSliceEqual(lhs, rhs []v1.IngressLoadBalancerIngress) bool {
if len(lhs) != len(rhs) {
return false
}
for i := range lhs {
if lhs[i].IP != rhs[i].IP {
return false
}
if lhs[i].Hostname != rhs[i].Hostname {
return false
}
}
return true
}
func statusAddressFromService(service string, kubeClient clientset.Interface) ([]v1.IngressLoadBalancerIngress, error) {
ns, name, err := k8s.ParseNameNS(service)
if err != nil {
return nil, err
}
svc, err := kubeClient.CoreV1().Services(ns).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return nil, err
}
switch svc.Spec.Type {
case apiv1.ServiceTypeExternalName:
return []v1.IngressLoadBalancerIngress{{
Hostname: svc.Spec.ExternalName,
}}, nil
case apiv1.ServiceTypeClusterIP:
return []v1.IngressLoadBalancerIngress{{
IP: svc.Spec.ClusterIP,
}}, nil
case apiv1.ServiceTypeNodePort:
if svc.Spec.ExternalIPs == nil {
return []v1.IngressLoadBalancerIngress{{
IP: svc.Spec.ClusterIP,
}}, nil
}
addrs := make([]v1.IngressLoadBalancerIngress, 0, len(svc.Spec.ExternalIPs))
for _, ip := range svc.Spec.ExternalIPs {
addrs = append(addrs, v1.IngressLoadBalancerIngress{IP: ip})
2019-10-21 04:23:27 +00:00
}
return addrs, nil
case apiv1.ServiceTypeLoadBalancer:
addrs := make([]v1.IngressLoadBalancerIngress, 0, len(svc.Status.LoadBalancer.Ingress))
for i, ingress := range svc.Status.LoadBalancer.Ingress {
addrs = append(addrs, v1.IngressLoadBalancerIngress{})
if ingress.Hostname != "" {
addrs[i].Hostname = ingress.Hostname
}
if ingress.IP != "" {
addrs[i].IP = ingress.IP
}
}
for _, ip := range svc.Spec.ExternalIPs {
if !stringInIngresses(ip, addrs) {
addrs = append(addrs, v1.IngressLoadBalancerIngress{IP: ip})
}
}
return addrs, nil
}
return nil, fmt.Errorf("unable to extract IP address/es from service %v", service)
}
2020-10-26 14:24:55 +00:00
// stringInIngresses returns true if s is in list
func stringInIngresses(s string, list []v1.IngressLoadBalancerIngress) bool {
2020-10-26 14:24:55 +00:00
for _, v := range list {
if v.IP == s || v.Hostname == s {
2020-10-26 14:24:55 +00:00
return true
}
}
return false
}