forked from svalabs/gargantua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
492 lines (416 loc) · 15.1 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package main
import (
"context"
"crypto/tls"
"flag"
"github.com/hobbyfarm/gargantua/v3/pkg/preinstall"
"github.com/hobbyfarm/gargantua/v3/pkg/settingclient"
"github.com/hobbyfarm/gargantua/v3/pkg/settingserver"
"github.com/hobbyfarm/gargantua/v3/pkg/webhook/validation"
"os"
"github.com/ebauman/crder"
"github.com/hobbyfarm/gargantua/v3/pkg/crd"
"github.com/hobbyfarm/gargantua/v3/pkg/rbac"
"github.com/hobbyfarm/gargantua/v3/pkg/rbacclient"
"github.com/hobbyfarm/gargantua/v3/pkg/rbacserver"
tls2 "github.com/hobbyfarm/gargantua/v3/pkg/tls"
"github.com/hobbyfarm/gargantua/v3/pkg/webhook/conversion"
"github.com/hobbyfarm/gargantua/v3/pkg/webhook/conversion/user"
"golang.org/x/sync/errgroup"
apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/client-go/informers"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"github.com/hobbyfarm/gargantua/v3/pkg/scheduledeventserver"
"github.com/hobbyfarm/gargantua/v3/pkg/vmtemplateserver"
"net/http"
"sync"
"time"
"github.com/golang/glog"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/hobbyfarm/gargantua/v3/pkg/accesscode"
"github.com/hobbyfarm/gargantua/v3/pkg/authclient"
"github.com/hobbyfarm/gargantua/v3/pkg/authserver"
hfClientset "github.com/hobbyfarm/gargantua/v3/pkg/client/clientset/versioned"
hfInformers "github.com/hobbyfarm/gargantua/v3/pkg/client/informers/externalversions"
"github.com/hobbyfarm/gargantua/v3/pkg/controllers/scheduledevent"
"github.com/hobbyfarm/gargantua/v3/pkg/controllers/session"
"github.com/hobbyfarm/gargantua/v3/pkg/controllers/tfpcontroller"
"github.com/hobbyfarm/gargantua/v3/pkg/controllers/vmclaimcontroller"
"github.com/hobbyfarm/gargantua/v3/pkg/controllers/vmsetcontroller"
"github.com/hobbyfarm/gargantua/v3/pkg/courseclient"
"github.com/hobbyfarm/gargantua/v3/pkg/courseserver"
"github.com/hobbyfarm/gargantua/v3/pkg/environmentserver"
"github.com/hobbyfarm/gargantua/v3/pkg/predefinedserviceserver"
"github.com/hobbyfarm/gargantua/v3/pkg/progressserver"
"github.com/hobbyfarm/gargantua/v3/pkg/scenarioclient"
"github.com/hobbyfarm/gargantua/v3/pkg/scenarioserver"
"github.com/hobbyfarm/gargantua/v3/pkg/sessionserver"
"github.com/hobbyfarm/gargantua/v3/pkg/shell"
"github.com/hobbyfarm/gargantua/v3/pkg/signals"
"github.com/hobbyfarm/gargantua/v3/pkg/userserver"
"github.com/hobbyfarm/gargantua/v3/pkg/util"
"github.com/hobbyfarm/gargantua/v3/pkg/vmclaimserver"
"github.com/hobbyfarm/gargantua/v3/pkg/vmclient"
"github.com/hobbyfarm/gargantua/v3/pkg/vmserver"
"github.com/hobbyfarm/gargantua/v3/pkg/vmsetserver"
wranglerRbac "github.com/rancher/wrangler/pkg/generated/controllers/rbac"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
const (
ClientGoQPS = 100
ClientGoBurst = 100
)
var (
localMasterUrl string
localKubeconfig string
disableControllers bool
shellServer bool
installRBACRoles bool
webhookTLSCert string
webhookTLSKey string
webhookTLSCA string
)
func init() {
flag.StringVar(&localKubeconfig, "kubeconfig", "", "Path to kubeconfig of local cluster. Only required if out-of-cluster.")
flag.StringVar(&localMasterUrl, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
flag.BoolVar(&disableControllers, "disablecontrollers", false, "Disable the controllers")
flag.BoolVar(&shellServer, "shellserver", false, "Be a shell server")
flag.BoolVar(&installRBACRoles, "installrbacroles", false, "Install default RBAC Roles")
flag.StringVar(&webhookTLSCert, "webhook-tls-cert", "/webhook-secret/tls.crt", "Path to TLS certificate for webhook server")
flag.StringVar(&webhookTLSKey, "webhook-tls-key", "/webhook-secret/tls.key", "Path to TLS key for webhook server")
flag.StringVar(&webhookTLSCA, "webhook-tls-ca", "/webhook-secret/ca", "Path to CA cert for webhook server")
}
func main() {
//var signal chan struct{}
//signal = make(chan struct{})
stopCh := signals.SetupSignalHandler()
ctx := context.Background()
flag.Parse()
glog.V(2).Infof("Starting Gargantua")
r := mux.NewRouter()
cfg, err := rest.InClusterConfig()
if err != nil {
cfg, err = clientcmd.BuildConfigFromFlags(localMasterUrl, localKubeconfig)
if err != nil {
glog.Fatalf("Error building kubeconfig: %s", err.Error())
}
}
namespace := util.GetReleaseNamespace()
var ca string
if !shellServer {
ca, err := os.ReadFile(webhookTLSCA)
if err != nil {
glog.Fatalf("error reading ca certificate: %s", err.Error())
}
crds := crd.GenerateCRDs(string(ca), crd.ServiceReference{
Namespace: namespace,
Name: "hobbyfarm-webhook",
})
glog.Info("installing/updating CRDs")
err = crder.InstallUpdateCRDs(cfg, crds...)
if err != nil {
glog.Fatalf("failed installing/updating crds: %s", err.Error())
}
glog.Info("finished installing/updating CRDs")
}
// self manage default rbac roles
if installRBACRoles {
err = rbac.Create(ctx, cfg)
if err != nil {
glog.Fatalf("Error installing RBAC roles: %s", err.Error())
}
glog.V(9).Infof("Successfully installed RBAC Roles")
}
cfg.QPS = ClientGoQPS
cfg.Burst = ClientGoBurst
hfClient, err := hfClientset.NewForConfig(cfg)
if err != nil {
glog.Fatal(err)
}
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
glog.Fatalf("Error building kubernetes clientset: %s", err.Error())
}
apiExtensionsClient, err := apiextensions.NewForConfig(cfg)
if err != nil {
glog.Fatalf("error building apiextensions clientset: %s", err.Error())
}
hfInformerFactory := hfInformers.NewSharedInformerFactoryWithOptions(hfClient, time.Second*30, hfInformers.WithNamespace(namespace))
kubeInformerFactory := informers.NewSharedInformerFactoryWithOptions(kubeClient, time.Second*30, informers.WithNamespace(namespace))
rbacControllerFactory := wranglerRbac.NewFactoryFromConfigOrDie(cfg)
rbacClient, err := rbacclient.NewRbacClient(namespace, kubeInformerFactory)
if err != nil {
glog.Fatal(err)
}
authClient, err := authclient.NewAuthClient(hfClient, hfInformerFactory, rbacClient)
if err != nil {
glog.Fatal(err)
}
rbacServer := rbacserver.NewRbacServer(kubeClient, authClient, rbacClient)
acClient, err := accesscode.NewAccessCodeClient(hfClient, ctx)
if err != nil {
glog.Fatal(err)
}
authServer, err := authserver.NewAuthServer(authClient, hfClient, ctx, acClient, rbacClient)
if err != nil {
glog.Fatal(err)
}
courseServer, err := courseserver.NewCourseServer(authClient, acClient, hfClient, hfInformerFactory, ctx)
if err != nil {
glog.Fatal(err)
}
courseClient, err := courseclient.NewCourseClient(courseServer)
if err != nil {
glog.Fatal(err)
}
scenarioServer, err := scenarioserver.NewScenarioServer(authClient, acClient, hfClient, hfInformerFactory, ctx, courseClient)
if err != nil {
glog.Fatal(err)
}
scenarioClient, err := scenarioclient.NewScenarioClient(scenarioServer)
if err != nil {
glog.Fatal(err)
}
sessionServer, err := sessionserver.NewSessionServer(authClient, acClient, scenarioClient, courseClient, hfClient, hfInformerFactory, ctx)
if err != nil {
glog.Fatal(err)
}
vmServer, err := vmserver.NewVMServer(authClient, hfClient, hfInformerFactory, ctx)
if err != nil {
glog.Fatal(err)
}
vmSetServer, err := vmsetserver.NewVMSetServer(authClient, hfClient, hfInformerFactory, ctx)
if err != nil {
glog.Fatal(err)
}
vmClient, err := vmclient.NewVirtualMachineClient(vmServer)
if err != nil {
glog.Fatal(err)
}
vmClaimServer, err := vmclaimserver.NewVMClaimServer(authClient, hfClient, hfInformerFactory)
if err != nil {
glog.Fatal(err)
}
shellProxy, err := shell.NewShellProxy(authClient, vmClient, hfClient, kubeClient, ctx)
if err != nil {
glog.Fatal(err)
}
environmentServer, err := environmentserver.NewEnvironmentServer(authClient, hfClient, ctx)
if err != nil {
glog.Fatal(err)
}
scheduledEventServer, err := scheduledeventserver.NewScheduledEventServer(authClient, hfClient, ctx)
if err != nil {
glog.Fatal(err)
}
userServer, err := userserver.NewUserServer(authClient, hfClient, ctx)
if err != nil {
glog.Fatal(err)
}
vmTemplateServer, err := vmtemplateserver.NewVirtualMachineTemplateServer(authClient, hfClient, ctx)
if err != nil {
glog.Fatal(err)
}
predefinedServiceServer, err := predefinedservicesserver.NewPredefinedServiceServer(authClient, hfClient, ctx)
if err != nil {
glog.Fatal(err)
}
progressServer, err := progressserver.NewProgressServer(authClient, hfClient, ctx)
if err != nil {
glog.Fatal(err)
}
settingServer, err := settingserver.NewSettingServer(hfClient, authClient, ctx)
if err != nil {
glog.Fatal(err)
}
settingclient.WatchSettings(ctx, hfClient, hfInformerFactory)
if shellServer {
glog.V(2).Infof("Starting as a shell server")
shellProxy.SetupRoutes(r)
} else {
sessionServer.SetupRoutes(r)
authServer.SetupRoutes(r)
courseServer.SetupRoutes(r)
scenarioServer.SetupRoutes(r)
vmServer.SetupRoutes(r)
vmSetServer.SetupRoutes(r)
//shellProxy.SetupRoutes(r)
vmClaimServer.SetupRoutes(r)
environmentServer.SetupRoutes(r)
scheduledEventServer.SetupRoutes(r)
userServer.SetupRoutes(r)
vmTemplateServer.SetupRoutes(r)
progressServer.SetupRoutes(r)
rbacServer.SetupRoutes(r)
predefinedServiceServer.SetupRoutes(r)
settingServer.SetupRoutes(r)
}
corsHeaders := handlers.AllowedHeaders([]string{"Authorization", "Content-Type"})
corsOrigins := handlers.AllowedOrigins([]string{"*"})
corsMethods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS", "DELETE"})
/*
glog.V(6).Infof("Waiting for informers to synchronize")
if ok := cache.WaitForCacheSync(stopCh,
hfInformerFactory.Hobbyfarm().V1().Users().Informer().HasSynced,
hfInformerFactory.Hobbyfarm().V1().VirtualMachines().Informer().HasSynced,
hfInformerFactory.Hobbyfarm().V1().Sessions().Informer().HasSynced,
hfInformerFactory.Hobbyfarm().V1().Scenarios().Informer().HasSynced,
hfInformerFactory.Hobbyfarm().V1().VirtualMachineClaims().Informer().HasSynced,
hfInformerFactory.Hobbyfarm().V1().AccessCodes().Informer().HasSynced,
hfInformerFactory.Hobbyfarm().V1().VirtualMachineTemplates().Informer().HasSynced,
//hfInformerFactory.Hobbyfarm().V1().Environments().Informer().HasSynced,
hfInformerFactory.Hobbyfarm().V1().VirtualMachineSets().Informer().HasSynced,
); !ok {
glog.Fatalf("failed to wait for caches to sync")
}
glog.V(6).Infof("Informers have synchronized")
*/
var wg sync.WaitGroup
// shell server does not serve webhook endpoint, so don't start it
if !shellServer {
user.Init()
webhookRouter := mux.NewRouter()
conversion.New(webhookRouter, apiExtensionsClient, string(ca))
validationEndpoints := webhookRouter.PathPrefix("/validation").Subrouter()
validation.SetupValidationServer(hfClient, validationEndpoints)
webhookPort := os.Getenv("WEBHOOK_PORT")
if webhookPort == "" {
webhookPort = "444"
}
glog.Info("webhook listening on " + webhookPort)
wg.Add(1)
go func() {
defer wg.Done()
cert, err := tls2.ReadKeyPair(webhookTLSCert, webhookTLSKey)
if err != nil {
glog.Fatalf("error generating x509keypair from conversion cert and key: %s", err)
}
server := http.Server{
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{*cert},
},
Addr: ":" + webhookPort,
Handler: handlers.CORS(corsHeaders, corsOrigins, corsMethods)(webhookRouter),
}
glog.Fatal(server.ListenAndServeTLS("", ""))
}()
if !shellServer {
// install resources
preinstall.Preinstall(ctx, hfClient)
}
}
wg.Add(1)
http.Handle("/", r)
apiPort := os.Getenv("PORT")
if apiPort == "" {
apiPort = "80"
}
glog.Info("apiserver listening on " + apiPort)
go func() {
defer wg.Done()
glog.Fatal(http.ListenAndServe(":"+apiPort, handlers.CORS(corsHeaders, corsOrigins, corsMethods)(r)))
}()
if !disableControllers {
lock, err := getLock("controller-manager", cfg)
if err != nil {
glog.Fatal(err)
}
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: lock,
ReleaseOnCancel: true,
LeaseDuration: 10 * time.Second,
RenewDeadline: 5 * time.Second,
RetryPeriod: 2 * time.Second,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(c context.Context) {
err = bootStrapControllers(kubeClient, hfClient, hfInformerFactory, kubeInformerFactory, rbacControllerFactory, acClient, ctx, stopCh)
if err != nil {
glog.Fatal(err)
}
},
OnStoppedLeading: func() {
// Need to start informer factory since even when not leader to ensure api layer
// keeps working.
hfInformerFactory.Start(stopCh)
glog.Info("waiting to be elected leader")
},
OnNewLeader: func(current_id string) {
hfInformerFactory.Start(stopCh)
if current_id == lock.Identity() {
glog.Info("currently the leader")
return
}
glog.Infof("current leader is %s", current_id)
},
},
})
} else {
// default fire up hfInformer as this is still needed by the shell server
hfInformerFactory.Start(stopCh)
kubeInformerFactory.Start(stopCh)
}
wg.Wait()
}
func bootStrapControllers(kubeClient *kubernetes.Clientset, hfClient *hfClientset.Clientset,
hfInformerFactory hfInformers.SharedInformerFactory, kubeInformerFactory informers.SharedInformerFactory, rbacControllerFactory *wranglerRbac.Factory, acClient *accesscode.AccessCodeClient,
ctx context.Context, stopCh <-chan struct{}) error {
g, gctx := errgroup.WithContext(ctx)
glog.V(2).Infof("Starting controllers")
sessionController, err := session.NewSessionController(hfClient, hfInformerFactory, gctx)
if err != nil {
return err
}
scheduledEventController, err := scheduledevent.NewScheduledEventController(hfClient, hfInformerFactory, gctx)
if err != nil {
return err
}
vmClaimController, err := vmclaimcontroller.NewVMClaimController(hfClient, hfInformerFactory, acClient, gctx)
if err != nil {
return err
}
tfpController, err := tfpcontroller.NewTerraformProvisionerController(kubeClient, hfClient, hfInformerFactory, gctx)
if err != nil {
return err
}
vmSetController, err := vmsetcontroller.NewVirtualMachineSetController(hfClient, hfInformerFactory, gctx)
if err != nil {
return err
}
g.Go(func() error {
return sessionController.Run(stopCh)
})
g.Go(func() error {
return scheduledEventController.Run(stopCh)
})
g.Go(func() error {
return vmClaimController.Run(stopCh)
})
g.Go(func() error {
return tfpController.Run(stopCh)
})
g.Go(func() error {
return vmSetController.Run(stopCh)
})
g.Go(func() error {
return rbacControllerFactory.Start(ctx, 1)
})
hfInformerFactory.Start(stopCh)
kubeInformerFactory.Start(stopCh)
if err = g.Wait(); err != nil {
glog.Errorf("error starting up the controllers: %v", err)
return err
}
return nil
}
func getLock(lockName string, cfg *rest.Config) (resourcelock.Interface, error) {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
ns := util.GetReleaseNamespace()
return resourcelock.NewFromKubeconfig(resourcelock.ConfigMapsLeasesResourceLock, ns, lockName, resourcelock.ResourceLockConfig{Identity: hostname}, cfg, 15*time.Second)
}