This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
forked from linki/chaoskube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
135 lines (112 loc) · 4.8 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
package main
import (
"encoding/json"
"math/rand"
"net/http"
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"github.com/metrosystems-cpe/chaoskube/internal"
)
var (
version = "undefined"
ckConf = &internal.ChaoskubeConfig{}
quit = make(chan bool) // channel used to send "kill" message to routine where monkey run.
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
kingpin.Flag("labels", "A set of labels to restrict the list of affected pods. Defaults to everything.").StringVar(&ckConf.Labels)
kingpin.Flag("annotations", "A set of annotations to restrict the list of affected pods. Defaults to everything.").StringVar(&ckConf.Annotations)
kingpin.Flag("namespaces", "A set of namespaces to restrict the list of affected pods. Defaults to everything.").StringVar(&ckConf.Namespaces)
kingpin.Flag("excluded-weekdays", "A list of weekdays when termination is suspended, e.g. Sat,Sun").StringVar(&ckConf.ExcludedWeekdays)
kingpin.Flag("excluded-times-of-day", "A list of time periods of a day when termination is suspended, e.g. 22:00-08:00").StringVar(&ckConf.ExcludedTimesOfDay)
kingpin.Flag("excluded-days-of-year", "A list of days of a year when termination is suspended, e.g. Apr1,Dec24").StringVar(&ckConf.ExcludedDaysOfYear)
kingpin.Flag("timezone", "The timezone by which to interpret the excluded weekdays and times of day, e.g. UTC, Local, Europe/Berlin. Defaults to UTC.").Default("UTC").StringVar(&ckConf.Timezone)
kingpin.Flag("master", "The address of the Kubernetes cluster to target").StringVar(&ckConf.Master)
kingpin.Flag("kubeconfig", "Path to a kubeconfig file").StringVar(&ckConf.Kubeconfig)
kingpin.Flag("interval", "Interval between Pod terminations").Default("10m").DurationVar(&ckConf.Interval)
kingpin.Flag("dry-run", "If true, don't actually do anything.").Default("true").BoolVar(&ckConf.DryRun)
kingpin.Flag("debug", "Enable debug logging.").BoolVar(&ckConf.Debug)
kingpin.Flag("httpServer", "Enable httpServer.").Default("true").BoolVar(&ckConf.HTTPServer)
kingpin.Flag("DDEvents", "toggle data dog events").Default("true").BoolVar(&ckConf.DDEvents)
}
func main() {
kingpin.Version(version)
kingpin.Parse()
if ckConf.Debug {
log.SetLevel(log.DebugLevel)
}
go startMonkey()
httpMuxServer()
}
// simple httpServer
func httpMuxServer() {
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/config", configHandler) //
mux.HandleFunc("/.well-known/live", healthHandler) // k8s pod process started
mux.HandleFunc("/.well-known/ready", healthHandler) // k8s pod is ready to accept traffic
mux.HandleFunc("/api/v1/update", updateConfigHandler) // k8s pod is ready to accept traffic
// log.WithFields("info", "http server").Info("http server started on :8080")
log.Infoln("http server started on :8080")
err := http.ListenAndServe(":8080", mux)
if err != nil {
log.Fatalf("ListenAndServe error: %v", err)
}
}
func updateConfigHandler(wr http.ResponseWriter, req *http.Request) {
newConf := internal.ChaoskubeConfig{}
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&newConf)
// TODO: Need to find a way to validate config :-?
if err != nil {
log.Infof("Fail to decode params. Error: %v", err)
wr.WriteHeader(http.StatusInternalServerError)
wr.Write([]byte(`{"Status": "Something went wrong. Check logs..."}`)) // Need better error message
} else {
log.Info("Config updated and will be used after monkey finishes sleep.")
ckConf = newConf.Diff(ckConf)
go func() {
// kill old monkey by pushing true on quit channel
quit <- true
// restart monkey with new config
go startMonkey()
}()
wr.WriteHeader(http.StatusOK)
wr.Write([]byte(`{"Status": "Config will be used after monkey finishes sleeping period"}`)) // Need better error message
}
}
func startMonkey() {
log.Infof("Start Monkey! dryRun: %v, Interval: %v", ckConf.DryRun, ckConf.Interval)
monkey := ckConf.NewMonkey()
for {
select {
case <-quit:
return
default:
if err := monkey.TerminateVictim(); err != nil {
log.Errorf("Failed to terminate victim: %v", err)
}
log.Debugf("Sleeping for %v", ckConf.Interval)
time.Sleep(ckConf.Interval)
}
}
}
// healthHandler to be used for k8s live and ready probe
func healthHandler(wr http.ResponseWriter, req *http.Request) {
wr.WriteHeader(http.StatusOK)
wr.Write([]byte(`{"Status": OK}`))
}
// configHandler manages chaoskube configuration
// method get --> gets monkey config
// method post --> updates config // -- not implemented
func configHandler(wr http.ResponseWriter, req *http.Request) {
wr.Header().Set("Access-Control-Allow-Origin", "*")
configData, err := json.Marshal(ckConf)
if err != nil {
http.Error(wr, err.Error(), http.StatusInternalServerError)
return
}
wr.Header().Set("Content-Type", "application/json")
wr.Write(configData)
}