elasticsearch_logging_discovery.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "context"
  16. "flag"
  17. "fmt"
  18. "net"
  19. "os"
  20. "strconv"
  21. "strings"
  22. "time"
  23. corev1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. clientset "k8s.io/client-go/kubernetes"
  26. restclient "k8s.io/client-go/rest"
  27. "k8s.io/client-go/tools/clientcmd"
  28. clientapi "k8s.io/client-go/tools/clientcmd/api"
  29. "k8s.io/klog"
  30. utilnet "k8s.io/utils/net"
  31. )
  32. func buildConfigFromEnvs(masterURL, kubeconfigPath string) (*restclient.Config, error) {
  33. if kubeconfigPath == "" && masterURL == "" {
  34. kubeconfig, err := restclient.InClusterConfig()
  35. if err != nil {
  36. return nil, err
  37. }
  38. return kubeconfig, nil
  39. }
  40. return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
  41. &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},
  42. &clientcmd.ConfigOverrides{ClusterInfo: clientapi.Cluster{Server: masterURL}}).ClientConfig()
  43. }
  44. func flattenSubsets(subsets []corev1.EndpointSubset) []string {
  45. ips := []string{}
  46. for _, ss := range subsets {
  47. for _, addr := range ss.Addresses {
  48. if utilnet.IsIPv6String(addr.IP) {
  49. ips = append(ips, fmt.Sprintf(`"[%s]"`, addr.IP))
  50. } else {
  51. ips = append(ips, fmt.Sprintf(`"%s"`, addr.IP))
  52. }
  53. }
  54. }
  55. return ips
  56. }
  57. func getAdvertiseAddress() (string, error) {
  58. addrs, err := net.InterfaceAddrs()
  59. if err != nil {
  60. return "", err
  61. }
  62. for _, addr := range addrs {
  63. if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  64. return ipnet.IP.String(), nil
  65. }
  66. }
  67. return "", fmt.Errorf("no non-loopback address is available")
  68. }
  69. func main() {
  70. flag.Parse()
  71. klog.Info("Kubernetes Elasticsearch logging discovery")
  72. advertiseAddress, err := getAdvertiseAddress()
  73. if err != nil {
  74. klog.Fatalf("Failed to get valid advertise address: %v", err)
  75. }
  76. fmt.Printf("network.host: \"%s\"\n\n", advertiseAddress)
  77. cc, err := buildConfigFromEnvs(os.Getenv("APISERVER_HOST"), os.Getenv("KUBE_CONFIG_FILE"))
  78. if err != nil {
  79. klog.Fatalf("Failed to make client: %v", err)
  80. }
  81. client, err := clientset.NewForConfig(cc)
  82. if err != nil {
  83. klog.Fatalf("Failed to make client: %v", err)
  84. }
  85. namespace := metav1.NamespaceSystem
  86. envNamespace := os.Getenv("NAMESPACE")
  87. if envNamespace != "" {
  88. if _, err := client.CoreV1().Namespaces().Get(context.TODO(), envNamespace, metav1.GetOptions{}); err != nil {
  89. klog.Fatalf("%s namespace doesn't exist: %v", envNamespace, err)
  90. }
  91. namespace = envNamespace
  92. }
  93. var elasticsearch *corev1.Service
  94. serviceName := os.Getenv("ELASTICSEARCH_SERVICE_NAME")
  95. if serviceName == "" {
  96. serviceName = "elasticsearch-logging"
  97. }
  98. // Look for endpoints associated with the Elasticsearch logging service.
  99. // First wait for the service to become available.
  100. for t := time.Now(); time.Since(t) < 5*time.Minute; time.Sleep(10 * time.Second) {
  101. elasticsearch, err = client.CoreV1().Services(namespace).Get(context.TODO(), serviceName, metav1.GetOptions{})
  102. if err == nil {
  103. break
  104. }
  105. }
  106. // If we did not find an elasticsearch logging service then log a warning
  107. // and return without adding any unicast hosts.
  108. if elasticsearch == nil {
  109. klog.Warningf("Failed to find the elasticsearch-logging service: %v", err)
  110. return
  111. }
  112. var endpoints *corev1.Endpoints
  113. addrs := []string{}
  114. // Wait for some endpoints.
  115. count, _ := strconv.Atoi(os.Getenv("MINIMUM_MASTER_NODES"))
  116. for t := time.Now(); time.Since(t) < 5*time.Minute; time.Sleep(10 * time.Second) {
  117. endpoints, err = client.CoreV1().Endpoints(namespace).Get(context.TODO(), serviceName, metav1.GetOptions{})
  118. if err != nil {
  119. continue
  120. }
  121. addrs = flattenSubsets(endpoints.Subsets)
  122. klog.Infof("Found %s", addrs)
  123. if len(addrs) > 0 && len(addrs) >= count {
  124. break
  125. }
  126. }
  127. // If there was an error finding endpoints then log a warning and quit.
  128. if err != nil {
  129. klog.Warningf("Error finding endpoints: %v", err)
  130. return
  131. }
  132. klog.Infof("Endpoints = %s", addrs)
  133. fmt.Printf("discovery.seed_hosts: [%s]\n", strings.Join(addrs, ", "))
  134. fmt.Printf("cluster.initial_master_nodes: [%s]\n", strings.Join(addrs, ", "))
  135. }