This repository has been archived by the owner on Mar 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 741
/
main.go
229 lines (193 loc) · 6.68 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// Copyright 2016 The etcd-operator 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 (
"context"
"flag"
"fmt"
"net/http"
"os"
"runtime"
"time"
"github.com/coreos/etcd-operator/pkg/chaos"
"github.com/coreos/etcd-operator/pkg/client"
"github.com/coreos/etcd-operator/pkg/controller"
"github.com/coreos/etcd-operator/pkg/util/constants"
"github.com/coreos/etcd-operator/pkg/util/k8sutil"
"github.com/coreos/etcd-operator/pkg/util/probe"
"github.com/coreos/etcd-operator/pkg/util/retryutil"
"github.com/coreos/etcd-operator/version"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"golang.org/x/time/rate"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/client-go/tools/record"
)
var (
namespace string
name string
listenAddr string
gcInterval time.Duration
chaosLevel int
printVersion bool
createCRD bool
clusterWide bool
)
func init() {
flag.StringVar(&listenAddr, "listen-addr", "0.0.0.0:8080", "The address on which the HTTP server will listen to")
// chaos level will be removed once we have a formal tool to inject failures.
flag.IntVar(&chaosLevel, "chaos-level", -1, "DO NOT USE IN PRODUCTION - level of chaos injected into the etcd clusters created by the operator.")
flag.BoolVar(&printVersion, "version", false, "Show version and quit")
flag.BoolVar(&createCRD, "create-crd", true, "The operator will not create the EtcdCluster CRD when this flag is set to false.")
flag.DurationVar(&gcInterval, "gc-interval", 10*time.Minute, "GC interval")
flag.BoolVar(&clusterWide, "cluster-wide", false, "Enable operator to watch clusters in all namespaces")
flag.Parse()
}
func main() {
namespace = os.Getenv(constants.EnvOperatorPodNamespace)
if len(namespace) == 0 {
logrus.Fatalf("must set env (%s)", constants.EnvOperatorPodNamespace)
}
name = os.Getenv(constants.EnvOperatorPodName)
if len(name) == 0 {
logrus.Fatalf("must set env (%s)", constants.EnvOperatorPodName)
}
if printVersion {
fmt.Println("etcd-operator Version:", version.Version)
fmt.Println("Git SHA:", version.GitSHA)
fmt.Println("Go Version:", runtime.Version())
fmt.Printf("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
os.Exit(0)
}
logrus.Infof("etcd-operator Version: %v", version.Version)
logrus.Infof("Git SHA: %s", version.GitSHA)
logrus.Infof("Go Version: %s", runtime.Version())
logrus.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
id, err := os.Hostname()
if err != nil {
logrus.Fatalf("failed to get hostname: %v", err)
}
kubecli := k8sutil.MustNewKubeClient()
http.HandleFunc(probe.HTTPReadyzEndpoint, probe.ReadyzHandler)
http.Handle("/metrics", prometheus.Handler())
go http.ListenAndServe(listenAddr, nil)
rl, err := resourcelock.New(resourcelock.EndpointsResourceLock,
namespace,
"etcd-operator",
kubecli.CoreV1(),
resourcelock.ResourceLockConfig{
Identity: id,
EventRecorder: createRecorder(kubecli, name, namespace),
})
if err != nil {
logrus.Fatalf("error creating lock: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: rl,
LeaseDuration: 15 * time.Second,
RenewDeadline: 10 * time.Second,
RetryPeriod: 2 * time.Second,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: run,
OnStoppedLeading: func() {
logrus.Fatalf("leader election lost")
},
},
})
panic("unreachable")
}
func run(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
cfg := newControllerConfig()
startChaos(context.Background(), cfg.KubeCli, cfg.Namespace, chaosLevel)
c := controller.New(cfg)
err := c.Start()
logrus.Fatalf("controller Start() failed: %v", err)
}
func newControllerConfig() controller.Config {
kubecli := k8sutil.MustNewKubeClient()
serviceAccount, err := getMyPodServiceAccount(kubecli)
if err != nil {
logrus.Fatalf("fail to get my pod's service account: %v", err)
}
cfg := controller.Config{
Namespace: namespace,
ClusterWide: clusterWide,
ServiceAccount: serviceAccount,
KubeCli: kubecli,
KubeExtCli: k8sutil.MustNewKubeExtClient(),
EtcdCRCli: client.MustNewInCluster(),
CreateCRD: createCRD,
}
return cfg
}
func getMyPodServiceAccount(kubecli kubernetes.Interface) (string, error) {
var sa string
err := retryutil.Retry(5*time.Second, 100, func() (bool, error) {
pod, err := kubecli.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
if err != nil {
logrus.Errorf("fail to get operator pod (%s): %v", name, err)
return false, nil
}
sa = pod.Spec.ServiceAccountName
return true, nil
})
return sa, err
}
func startChaos(ctx context.Context, kubecli kubernetes.Interface, ns string, chaosLevel int) {
m := chaos.NewMonkeys(kubecli)
ls := labels.SelectorFromSet(map[string]string{"app": "etcd"})
switch chaosLevel {
case 1:
logrus.Info("chaos level = 1: randomly kill one etcd pod every 30 seconds at 50%")
c := &chaos.CrashConfig{
Namespace: ns,
Selector: ls,
KillRate: rate.Every(30 * time.Second),
KillProbability: 0.5,
KillMax: 1,
}
go func() {
time.Sleep(60 * time.Second) // don't start until quorum up
m.CrushPods(ctx, c)
}()
case 2:
logrus.Info("chaos level = 2: randomly kill at most five etcd pods every 30 seconds at 50%")
c := &chaos.CrashConfig{
Namespace: ns,
Selector: ls,
KillRate: rate.Every(30 * time.Second),
KillProbability: 0.5,
KillMax: 5,
}
go m.CrushPods(ctx, c)
default:
}
}
func createRecorder(kubecli kubernetes.Interface, name, namespace string) record.EventRecorder {
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(logrus.Infof)
eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: v1core.New(kubecli.Core().RESTClient()).Events(namespace)})
return eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: name})
}