forked from sorenmat/k8s-rds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
264 lines (233 loc) · 6.89 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package main
import (
"fmt"
"log"
"time"
"github.com/sorenmat/k8s-rds/client"
"github.com/sorenmat/k8s-rds/crd"
"github.com/sorenmat/k8s-rds/kube"
"github.com/sorenmat/k8s-rds/local"
"github.com/sorenmat/k8s-rds/provider"
"github.com/sorenmat/k8s-rds/rds"
"github.com/spf13/cobra"
apiextcs "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
const Failed = "Failed"
// return rest config, if path not specified assume in cluster config
func getClientConfig(kubeconfig string) (*rest.Config, error) {
cfg, err := rest.InClusterConfig()
if err != nil {
if kubeconfig != "" {
return clientcmd.BuildConfigFromFlags("", kubeconfig)
}
}
return cfg, err
}
func getKubectl() (*kubernetes.Clientset, error) {
config, err := rest.InClusterConfig()
if err != nil {
log.Println("Appears we are not running in a cluster")
config, err = clientcmd.BuildConfigFromFlags("", kube.Config())
if err != nil {
return nil, err
}
} else {
log.Println("Seems like we are running in a Kubernetes cluster!!")
}
kubectl, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
return kubectl, nil
}
func main() {
var (
provider string
excludeNamespaces []string
includeNamespaces []string
)
var rootCmd = &cobra.Command{
Use: "k8s-rds",
Short: "Kubernetes database provisioner",
Long: `Kubernetes database provisioner`,
Run: func(cmd *cobra.Command, args []string) {
execute(provider, excludeNamespaces, includeNamespaces)
},
}
rootCmd.PersistentFlags().StringVar(&provider, "provider", "aws", "Type of provider (aws, local)")
rootCmd.PersistentFlags().StringSliceVar(&excludeNamespaces, "exclude-namespaces", nil, "list of namespaces to exclude. Mutually exclusive with --include-namespaces.")
rootCmd.PersistentFlags().StringSliceVar(&includeNamespaces, "include-namespaces", nil, "list of namespaces to include. Mutually exclusive with --exclude-namespaces.")
if len(excludeNamespaces) > 0 && len(includeNamespaces) > 0 {
panic("--include-namespaces and --exclude-namespaces are mutually exclusive")
}
err := rootCmd.Execute()
if err != nil {
panic(err)
}
}
func execute(dbprovider string, excludeNamespaces, includeNamespaces []string) {
log.Println("Starting k8s-rds")
config, err := getClientConfig(kube.Config())
if err != nil {
panic(err.Error())
}
// create clientset and create our CRD, this only need to run once
clientset, err := apiextcs.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// note: if the CRD exist our CreateCRD function is set to exit without an error
err = crd.CreateCRD(clientset)
if err != nil {
panic(err)
}
// Create a new clientset which include our CRD schema
crdcs, scheme, err := crd.NewClient(config)
if err != nil {
panic(err)
}
// Create a CRD client interface
crdclient := client.CrdClient(crdcs, scheme, "")
log.Println("Watching for database changes...")
_, controller := cache.NewInformer(
crdclient.NewListWatch(),
&crd.Database{},
time.Minute*2,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
db := obj.(*crd.Database)
if excluded(db, excludeNamespaces, includeNamespaces) {
return
}
client := client.CrdClient(crdcs, scheme, db.Namespace) // add the database namespace to the client
err = handleCreateDatabase(db, client, dbprovider)
if err != nil {
log.Printf("database creation failed: %v", err)
err := updateStatus(db, crd.DatabaseStatus{Message: fmt.Sprintf("%v", err), State: Failed}, client)
if err != nil {
log.Printf("database CRD status update failed: %v", err)
}
}
},
DeleteFunc: func(obj interface{}) {
db := obj.(*crd.Database)
if excluded(db, excludeNamespaces, includeNamespaces) {
return
}
log.Printf("deleting database: %s \n", db.Name)
r, err := getProvider(db, dbprovider)
if err != nil {
log.Println(err)
return
}
err = r.DeleteDatabase(db)
if err != nil {
log.Println(err)
}
err = r.DeleteService(db.Namespace, db.Name)
if err != nil {
log.Println(err)
}
log.Printf("Deletion of database %v done\n", db.Name)
},
UpdateFunc: func(oldObj, newObj interface{}) {
},
},
)
stop := make(chan struct{})
go controller.Run(stop)
// Wait forever
select {}
}
func getProvider(db *crd.Database, dbprovider string) (provider.DatabaseProvider, error) {
kubectl, err := getKubectl()
if err != nil {
log.Println(err)
return nil, err
}
switch dbprovider {
case "aws":
r, err := rds.New(db, kubectl)
if err != nil {
return nil, err
}
return r, nil
case "local":
r, err := local.New(db, kubectl)
if err != nil {
return nil, err
}
return r, nil
}
return nil, fmt.Errorf("unable to find provider for %v", dbprovider)
}
func handleCreateDatabase(db *crd.Database, crdclient *client.Crdclient, dbprovider string) error {
// we don't need to skip when it is a local provider without running pod
if db.Status.State == "Created" && dbprovider == "aws" {
log.Printf("database %v already created, skipping\n", db.Name)
return nil
}
// validate dbname is only alpha numeric
// This check is needed in case local provider with already created db
if db.Status.State != "Created" {
err := updateStatus(db, crd.DatabaseStatus{Message: "Creating", State: "Creating"}, crdclient)
if err != nil {
return fmt.Errorf("database CRD status update failed: %v", err)
}
}
log.Println("trying to get kubectl")
r, err := getProvider(db, dbprovider)
if err != nil {
return err
}
hostname, err := r.CreateDatabase(db)
if err != nil {
return err
}
log.Printf("Creating service '%v' for %v\n", db.Name, hostname)
err = r.CreateService(db.Namespace, hostname, db.Name)
if err != nil {
return err
}
err = updateStatus(db, crd.DatabaseStatus{Message: "Created", State: "Created"}, crdclient)
if err != nil {
return err
}
log.Printf("Creation of database %v done\n", db.Name)
return nil
}
func updateStatus(db *crd.Database, status crd.DatabaseStatus, crdclient *client.Crdclient) error {
db, err := crdclient.Get(db.Name)
if err != nil {
return err
}
db.Status = status
_, err = crdclient.Update(db)
if err != nil {
return err
}
return nil
}
func excluded(db *crd.Database, excludeNamespaces, includeNamespaces []string) bool {
if len(excludeNamespaces) > 0 && stringInSlice(db.Namespace, excludeNamespaces) {
log.Printf("database %s is in excluded namespace %s. Ignoring...", db.Name, db.Namespace)
return true
}
if len(includeNamespaces) > 0 && !stringInSlice(db.Namespace, includeNamespaces) {
log.Printf("database %s is in a non included namespace %s. Ignoring...", db.Name, db.Namespace)
return true
}
return false
}
func stringInSlice(str string, slice []string) bool {
for _, s := range slice {
if str == s {
return true
}
}
return false
}