This repository has been archived by the owner on Sep 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhosts.go
106 lines (94 loc) · 2.2 KB
/
hosts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/v1"
)
const (
etcdDir = "/var/etcd"
etcdHostsFilename = "etcd-hosts.checkpoint"
)
type hostInfo struct {
HostName string
IP string
}
func runHostsCheckpointer(kubecli kubernetes.Interface) {
ticker := time.NewTicker(10 * time.Second)
for {
select {
case <-ticker.C:
hosts, err := getHosts(kubecli)
if err != nil {
log.Printf("failed to checkpoint etcd hosts: %v", err)
continue
}
if len(hosts) == 0 {
continue
}
fp := filepath.Join(etcdDir, etcdHostsFilename)
err = saveHostsCheckpoint(fp, hosts)
if err != nil {
log.Printf("failed to update etcd hosts file (%s): %v", fp, err)
}
}
}
}
func getHosts(kubecli kubernetes.Interface) ([]*hostInfo, error) {
ls := map[string]string{
cluterLabel: clusterName,
appLabel: appName,
}
// TODO: use client side cache
lo := metav1.ListOptions{LabelSelector: labels.SelectorFromSet(ls).String()}
podList, err := kubecli.Core().Pods(api.NamespaceSystem).List(lo)
if err != nil {
return nil, fmt.Errorf("failed to list running self hosted etcd pods: %v", err)
}
var hs []*hostInfo
for i := range podList.Items {
pod := &podList.Items[i]
switch pod.Status.Phase {
case v1.PodRunning:
h := &hostInfo{
HostName: pod.Name,
IP: pod.Status.PodIP,
}
hs = append(hs, h)
}
}
return hs, nil
}
func saveHostsCheckpoint(filepath string, hosts []*hostInfo) error {
f, err := ioutil.TempFile(etcdDir, "tmp-etcd-hosts")
if err != nil {
return err
}
defer os.Remove(f.Name())
b := getHostsBytes(hosts)
if _, err := f.Write(b); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), filepath)
}
func getHostsBytes(hosts []*hostInfo) []byte {
var buf bytes.Buffer
for _, h := range hosts {
buf.WriteString(fmt.Sprintf("%s %s.%s.%s.svc.cluster.local\n", h.IP, h.HostName, clusterName, api.NamespaceSystem))
}
return buf.Bytes()
}