-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
api.go
1215 lines (1075 loc) · 50 KB
/
api.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the KubeVirt project
*
* 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.
*
* Copyright 2018 Red Hat, Inc.
*
*/
package virt_api
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"k8s.io/kube-openapi/pkg/common/restfuladapter"
"k8s.io/kube-openapi/pkg/validation/spec"
kvtls "kubevirt.io/kubevirt/pkg/util/tls"
restful "github.com/emicklei/go-restful/v3"
"github.com/prometheus/client_golang/prometheus/promhttp"
flag "github.com/spf13/pflag"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/tools/cache"
certificate2 "k8s.io/client-go/util/certificate"
"k8s.io/client-go/util/flowcontrol"
aggregatorclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
builderv3 "k8s.io/kube-openapi/pkg/builder3"
"kubevirt.io/kubevirt/pkg/util/ratelimiter"
v1 "kubevirt.io/api/core/v1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/client-go/log"
clientutil "kubevirt.io/client-go/util"
virtversion "kubevirt.io/client-go/version"
v12 "kubevirt.io/client-go/api"
"kubevirt.io/kubevirt/pkg/certificates/bootstrap"
"kubevirt.io/kubevirt/pkg/controller"
"kubevirt.io/kubevirt/pkg/healthz"
metrics "kubevirt.io/kubevirt/pkg/monitoring/metrics/virt-api"
"kubevirt.io/kubevirt/pkg/monitoring/profiler"
mime "kubevirt.io/kubevirt/pkg/rest"
"kubevirt.io/kubevirt/pkg/rest/filter"
"kubevirt.io/kubevirt/pkg/service"
"kubevirt.io/kubevirt/pkg/util"
"kubevirt.io/kubevirt/pkg/util/openapi"
"kubevirt.io/kubevirt/pkg/virt-api/definitions"
"kubevirt.io/kubevirt/pkg/virt-api/rest"
"kubevirt.io/kubevirt/pkg/virt-api/webhooks"
mutating_webhook "kubevirt.io/kubevirt/pkg/virt-api/webhooks/mutating-webhook"
validating_webhook "kubevirt.io/kubevirt/pkg/virt-api/webhooks/validating-webhook"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
"kubevirt.io/kubevirt/pkg/virt-operator/resource/generate/components"
virtoperatorutils "kubevirt.io/kubevirt/pkg/virt-operator/util"
)
const (
// Default port that virt-api listens on.
defaultPort = 443
// Default address that virt-api listens on.
defaultHost = "0.0.0.0"
DefaultConsoleServerPort = 8186
defaultCAConfigMapName = "kubevirt-ca"
defaultTlsCertFilePath = "/etc/virt-api/certificates/tls.crt"
defaultTlsKeyFilePath = "/etc/virt-api/certificates/tls.key"
defaultHandlerCertFilePath = "/etc/virt-handler/clientcertificates/tls.crt"
defaultHandlerKeyFilePath = "/etc/virt-handler/clientcertificates/tls.key"
httpStatusNotFoundMessage = "Not Found"
httpStatusBadRequestMessage = "Bad Request"
httpStatusInternalServerError = "Internal Server Error"
)
type VirtApi interface {
Compose()
Run()
AddFlags()
ConfigureOpenAPIService()
Execute()
}
type virtAPIApp struct {
service.ServiceListen
SwaggerUI string
SubresourcesOnly bool
virtCli kubecli.KubevirtClient
aggregatorClient *aggregatorclient.Clientset
authorizor rest.VirtApiAuthorizor
certsDirectory string
clusterConfig *virtconfig.ClusterConfig
namespace string
host string
tlsConfig *tls.Config
certificate *tls.Certificate
consoleServerPort int
certmanager certificate2.Manager
handlerTLSConfiguration *tls.Config
handlerCertManager certificate2.Manager
caConfigMapName string
tlsCertFilePath string
tlsKeyFilePath string
handlerCertFilePath string
handlerKeyFilePath string
externallyManaged bool
reloadableRateLimiter *ratelimiter.ReloadableRateLimiter
reloadableWebhookRateLimiter *ratelimiter.ReloadableRateLimiter
// indicates if controllers were started with or without CDI/DataSource support
hasCDIDataSource bool
// the channel used to trigger re-initialization.
reInitChan chan string
}
var (
_ service.Service = &virtAPIApp{}
apiHealthVersion = new(healthz.KubeApiHealthzVersion)
)
func NewVirtApi() VirtApi {
app := &virtAPIApp{}
app.BindAddress = defaultHost
app.Port = defaultPort
return app
}
func (app *virtAPIApp) Execute() {
app.reloadableRateLimiter = ratelimiter.NewReloadableRateLimiter(flowcontrol.NewTokenBucketRateLimiter(virtconfig.DefaultVirtAPIQPS, virtconfig.DefaultVirtAPIBurst))
app.reloadableWebhookRateLimiter = ratelimiter.NewReloadableRateLimiter(flowcontrol.NewTokenBucketRateLimiter(virtconfig.DefaultVirtWebhookClientQPS, virtconfig.DefaultVirtWebhookClientBurst))
clientConfig, err := kubecli.GetKubevirtClientConfig()
if err != nil {
panic(err)
}
clientConfig.RateLimiter = app.reloadableRateLimiter
app.virtCli, err = kubecli.GetKubevirtClientFromRESTConfig(clientConfig)
if err != nil {
panic(err)
}
authorizor, err := rest.NewAuthorizor(app.reloadableWebhookRateLimiter)
if err != nil {
panic(err)
}
app.aggregatorClient = aggregatorclient.NewForConfigOrDie(clientConfig)
app.authorizor = authorizor
app.certsDirectory, err = os.MkdirTemp("", "certsdir")
if err != nil {
panic(err)
}
app.namespace, err = clientutil.GetNamespace()
if err != nil {
panic(err)
}
app.ConfigureOpenAPIService()
app.reInitChan = make(chan string, 10)
// setup monitoring
err = metrics.SetupMetrics()
if err != nil {
panic(err)
}
app.Run()
}
func subresourceAPIGroup() metav1.APIGroup {
apiGroup := metav1.APIGroup{
Name: "subresource.kubevirt.io",
PreferredVersion: metav1.GroupVersionForDiscovery{
GroupVersion: v1.SubresourceGroupVersions[0].Group + "/" + v1.SubresourceGroupVersions[0].Version,
Version: v1.SubresourceGroupVersions[0].Version,
},
}
for _, version := range v1.SubresourceGroupVersions {
apiGroup.Versions = append(apiGroup.Versions, metav1.GroupVersionForDiscovery{
GroupVersion: version.Group + "/" + version.Version,
Version: version.Version,
})
}
apiGroup.ServerAddressByClientCIDRs = append(apiGroup.ServerAddressByClientCIDRs, metav1.ServerAddressByClientCIDR{
ClientCIDR: "0.0.0.0/0",
ServerAddress: "",
})
apiGroup.Kind = "APIGroup"
return apiGroup
}
func (app *virtAPIApp) composeSubresources() {
var subwss []*restful.WebService
for _, version := range v1.SubresourceGroupVersions {
subresourcesvmGVR := schema.GroupVersionResource{Group: version.Group, Version: version.Version, Resource: "virtualmachines"}
subresourcesvmiGVR := schema.GroupVersionResource{Group: version.Group, Version: version.Version, Resource: "virtualmachineinstances"}
expandvmspecGVR := schema.GroupVersionResource{Group: version.Group, Version: version.Version, Resource: "expand-vm-spec"}
subws := new(restful.WebService)
subws.Doc(fmt.Sprintf("KubeVirt \"%s\" Subresource API.", version.Version))
subws.Path(definitions.GroupVersionBasePath(version))
subresourceApp := rest.NewSubresourceAPIApp(app.virtCli, app.consoleServerPort, app.handlerTLSConfiguration, app.clusterConfig)
restartRouteBuilder := subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("restart")).
To(subresourceApp.RestartVMRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.RestartOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Restart").
Doc("Restart a VirtualMachine object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusNotFound, httpStatusNotFoundMessage, "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, "")
restartRouteBuilder.ParameterNamed("body").Required(false)
subws.Route(restartRouteBuilder)
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("migrate")).
To(subresourceApp.MigrateVMRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.MigrateOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Migrate").
Doc("Migrate a running VirtualMachine to another node.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusNotFound, httpStatusNotFoundMessage, "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("start")).
To(subresourceApp.StartVMRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.StartOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Start").
Doc("Start a VirtualMachine object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusNotFound, httpStatusNotFoundMessage, "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
stopRouteBuilder := subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("stop")).
To(subresourceApp.StopVMRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.StopOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Stop").
Doc("Stop a VirtualMachine object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusNotFound, httpStatusNotFoundMessage, "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, "")
stopRouteBuilder.ParameterNamed("body").Required(false)
subws.Route(stopRouteBuilder)
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("expand-spec")).
To(subresourceApp.ExpandSpecVMRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"vm-ExpandSpec").
Produces(restful.MIME_JSON).
Doc("Get VirtualMachine object with expanded instancetype and preference.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusNotFound, httpStatusNotFoundMessage, "").
Returns(http.StatusInternalServerError, httpStatusInternalServerError, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("freeze")).
To(subresourceApp.FreezeVMIRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.FreezeUnfreezeTimeout{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Freeze").
Doc("Freeze a VirtualMachineInstance object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusInternalServerError, httpStatusInternalServerError, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("unfreeze")).
To(subresourceApp.UnfreezeVMIRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Unfreeze").
Doc("Unfreeze a VirtualMachineInstance object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusInternalServerError, httpStatusInternalServerError, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("softreboot")).
To(subresourceApp.SoftRebootVMIRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"SoftReboot").
Doc("Soft reboot a VirtualMachineInstance object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusInternalServerError, httpStatusInternalServerError, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("pause")).
To(subresourceApp.PauseVMIRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.PauseOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Pause").
Doc("Pause a VirtualMachineInstance object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusNotFound, httpStatusNotFoundMessage, "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("unpause")).
To(subresourceApp.UnpauseVMIRequestHandler). // handles VMIs as well
Consumes(mime.MIME_ANY).
Reads(v1.UnpauseOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Unpause").
Doc("Unpause a VirtualMachineInstance object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusNotFound, httpStatusNotFoundMessage, "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR) + definitions.SubResourcePath("console")).
To(subresourceApp.ConsoleRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version + "Console").
Doc("Open a websocket connection to a serial console on the specified VirtualMachineInstance."))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR) + definitions.SubResourcePath("vnc")).
To(subresourceApp.VNCRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version + "VNC").
Doc("Open a websocket connection to connect to VNC on the specified VirtualMachineInstance."))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR) + definitions.SubResourcePath("vnc/screenshot")).
To(subresourceApp.VNCScreenshotRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).Param(definitions.MoveCursorParam(subws)).
Operation(version.Version + "VNCScreenshot").
Doc("Get a PNG VNC screenshot of the specified VirtualMachineInstance."))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR) + definitions.SubResourcePath("usbredir")).
To(subresourceApp.USBRedirRequestHandler).
Param(definitions.NamespaceParam(subws)).
Param(definitions.NameParam(subws)).
Operation(version.Version + "usbredir").
Doc("Open a websocket connection to connect to USB device on the specified VirtualMachineInstance."))
// VMI endpoint
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR) + definitions.SubResourcePath("portforward") + definitions.PortPath).
To(subresourceApp.PortForwardRequestHandler(subresourceApp.FetchVirtualMachineInstance)).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Param(definitions.PortForwardPortParameter(subws)).
Operation(version.Version + "vmi-PortForward").
Doc("Open a websocket connection forwarding traffic to the specified VirtualMachineInstance and port."))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR) + definitions.SubResourcePath("portforward") + definitions.PortPath + definitions.ProtocolPath).
To(subresourceApp.PortForwardRequestHandler(subresourceApp.FetchVirtualMachineInstance)).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Param(definitions.PortForwardPortParameter(subws)).
Param(definitions.PortForwardProtocolParameter(subws)).
Operation(version.Version + "vmi-PortForwardWithProtocol").
Doc("Open a websocket connection forwarding traffic of the specified protocol (either tcp or udp) to the specified VirtualMachineInstance and port."))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR) + definitions.SubResourcePath("vsock")).
To(subresourceApp.VSOCKRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).Param(definitions.VSOCKPortParameter(subws)).Param(definitions.VSOCKTLSParameter(subws)).
Operation(version.Version + "VSOCK").
Doc("Open a websocket connection forwarding traffic to the specified VirtualMachineInstance and port via VSOCK."))
// VM endpoint
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmGVR) + definitions.SubResourcePath("portforward") + definitions.PortPath).
To(subresourceApp.PortForwardRequestHandler(subresourceApp.FetchVirtualMachineInstanceForVM)).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Param(definitions.PortForwardPortParameter(subws)).
Operation(version.Version + "vm-PortForward").
Doc("Open a websocket connection forwarding traffic to the running VMI for the specified VirtualMachine and port."))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmGVR) + definitions.SubResourcePath("portforward") + definitions.PortPath + definitions.ProtocolPath).
To(subresourceApp.PortForwardRequestHandler(subresourceApp.FetchVirtualMachineInstanceForVM)).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Param(definitions.PortForwardPortParameter(subws)).
Param(definitions.PortForwardProtocolParameter(subws)).
Operation(version.Version + "vm-PortForwardWithProtocol").
Doc("Open a websocket connection forwarding traffic of the specified protocol (either tcp or udp) to the specified VirtualMachine and port."))
subws.Route(subws.PUT(definitions.NamespacedResourceBasePath(expandvmspecGVR)).
To(subresourceApp.ExpandSpecRequestHandler).
Param(definitions.NamespaceParam(subws)).
Operation(version.Version+"ExpandSpec").
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Doc("Expands instancetype and preference into the passed VirtualMachine object.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, "").
Returns(http.StatusInternalServerError, httpStatusInternalServerError, ""))
subws.Route(subws.GET(definitions.SubResourcePath("version")).Produces(restful.MIME_JSON).
To(func(request *restful.Request, response *restful.Response) {
response.WriteAsJson(virtversion.Get())
}).Operation(version.Version + "Version"))
subws.Route(subws.GET(definitions.SubResourcePath("start-cluster-profiler")).Produces(restful.MIME_JSON).
To(subresourceApp.StartClusterProfilerHandler).
Operation(version.Version + "start-cluster-profiler"))
subws.Route(subws.GET(definitions.SubResourcePath("stop-cluster-profiler")).Produces(restful.MIME_JSON).
To(subresourceApp.StopClusterProfilerHandler).
Operation(version.Version + "stop-cluster-profiler"))
subws.Route(subws.GET(definitions.SubResourcePath("dump-cluster-profiler")).Produces(restful.MIME_JSON).
To(subresourceApp.DumpClusterProfilerHandler).
Operation(version.Version + "dump-cluster-profiler"))
subws.Route(subws.GET(definitions.SubResourcePath("guestfs")).Produces(restful.MIME_JSON).
To(app.GetGsInfo()).
Operation(version.Version+"Guestfs").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.GET(definitions.SubResourcePath("healthz")).
To(healthz.KubeConnectionHealthzFuncFactory(app.clusterConfig, apiHealthVersion)).
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Operation(version.Version+"CheckHealth").
Doc("Health endpoint").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusInternalServerError, "Unhealthy", ""))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("guestosinfo")).
To(subresourceApp.GuestOSInfo).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Operation(version.Version+"Guestosinfo").
Doc("Get guest agent os information").
Writes(v1.VirtualMachineInstanceGuestAgentInfo{}).
Returns(http.StatusOK, "OK", v1.VirtualMachineInstanceGuestAgentInfo{}))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("userlist")).
To(subresourceApp.UserList).
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Userlist").
Doc("Get list of active users via guest agent").
Writes(v1.VirtualMachineInstanceGuestOSUserList{}).
Returns(http.StatusOK, "OK", v1.VirtualMachineInstanceGuestOSUserList{}))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("filesystemlist")).
To(subresourceApp.FilesystemList).
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"Filesystemlist").
Doc("Get list of active filesystems on guest machine via guest agent").
Writes(v1.VirtualMachineInstanceFileSystemList{}).
Returns(http.StatusOK, "OK", v1.VirtualMachineInstanceFileSystemList{}))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("addvolume")).
To(subresourceApp.VMIAddVolumeRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.AddVolumeOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"vmi-addvolume").
Doc("Add a volume and disk to a running Virtual Machine Instance").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("removevolume")).
To(subresourceApp.VMIRemoveVolumeRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.RemoveVolumeOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"vmi-removevolume").
Doc("Removes a volume and disk from a running Virtual Machine Instance").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("addvolume")).
To(subresourceApp.VMAddVolumeRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.AddVolumeOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"vm-addvolume").
Doc("Add a volume and disk to a running Virtual Machine.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("removevolume")).
To(subresourceApp.VMRemoveVolumeRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.RemoveVolumeOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"vm-removevolume").
Doc("Removes a volume and disk from a running Virtual Machine.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("memorydump")).
To(subresourceApp.MemoryDumpVMRequestHandler).
Consumes(mime.MIME_ANY).
Reads(v1.VirtualMachineMemoryDumpRequest{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"MemoryDump").
Doc("Dumps a VirtualMachineInstance memory.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusInternalServerError, httpStatusInternalServerError, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmGVR)+definitions.SubResourcePath("removememorydump")).
To(subresourceApp.RemoveMemoryDumpVMRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"RemoveMemoryDump").
Doc("Remove memory dump association.").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusInternalServerError, httpStatusInternalServerError, ""))
// AMD SEV endpoints
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("sev/fetchcertchain")).
To(subresourceApp.SEVFetchCertChainRequestHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Operation(version.Version+"SEVFetchCertChain").
Doc("Fetch SEV certificate chain from the node where Virtual Machine is scheduled").
Writes(v1.SEVPlatformInfo{}).
Returns(http.StatusOK, "OK", v1.SEVPlatformInfo{}))
subws.Route(subws.GET(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("sev/querylaunchmeasurement")).
To(subresourceApp.SEVQueryLaunchMeasurementHandler).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Operation(version.Version+"SEVQueryLaunchMeasurement").
Doc("Query SEV launch measurement from a Virtual Machine").
Writes(v1.SEVMeasurementInfo{}).
Returns(http.StatusOK, "OK", v1.SEVMeasurementInfo{}))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("sev/setupsession")).
To(subresourceApp.SEVSetupSessionHandler).
Consumes(mime.MIME_ANY).
Reads(v1.SEVSessionOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"SEVSetupSession").
Doc("Setup SEV session parameters for a Virtual Machine").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
subws.Route(subws.PUT(definitions.NamespacedResourcePath(subresourcesvmiGVR)+definitions.SubResourcePath("sev/injectlaunchsecret")).
To(subresourceApp.SEVInjectLaunchSecretHandler).
Consumes(mime.MIME_ANY).
Reads(v1.SEVSecretOptions{}).
Param(definitions.NamespaceParam(subws)).Param(definitions.NameParam(subws)).
Operation(version.Version+"SEVInjectLaunchSecret").
Doc("Inject SEV launch secret into a Virtual Machine").
Returns(http.StatusOK, "OK", "").
Returns(http.StatusBadRequest, httpStatusBadRequestMessage, ""))
// Return empty api resource list.
// K8s expects to be able to retrieve a resource list for each aggregated
// app in order to discover what resources it provides. Without returning
// an empty list here, there's a bug in the k8s resource discovery that
// breaks kubectl's ability to reference short names for resources.
subws.Route(subws.GET("/").
Produces(restful.MIME_JSON).Writes(metav1.APIResourceList{}).
To(func(request *restful.Request, response *restful.Response) {
list := &metav1.APIResourceList{}
list.Kind = "APIResourceList"
list.GroupVersion = version.Group + "/" + version.Version
list.APIVersion = version.Version
list.APIResources = []metav1.APIResource{
{
Name: "expand-vm-spec",
Namespaced: true,
},
{
Name: "virtualmachineinstances/vnc",
Namespaced: true,
},
{
Name: "virtualmachineinstances/console",
Namespaced: true,
},
{
Name: "virtualmachineinstances/portforward",
Namespaced: true,
},
{
Name: "virtualmachineinstances/pause",
Namespaced: true,
},
{
Name: "virtualmachineinstances/unpause",
Namespaced: true,
},
{
Name: "virtualmachineinstances/freeze",
Namespaced: true,
},
{
Name: "virtualmachineinstances/unfreeze",
Namespaced: true,
},
{
Name: "virtualmachineinstances/softreboot",
Namespaced: true,
},
{
Name: "virtualmachines/start",
Namespaced: true,
},
{
Name: "virtualmachines/stop",
Namespaced: true,
},
{
Name: "virtualmachines/restart",
Namespaced: true,
},
{
Name: "virtualmachines/migrate",
Namespaced: true,
},
{
Name: "virtualmachines/expand-spec",
Namespaced: true,
},
{
Name: "virtualmachineinstances/guestosinfo",
Namespaced: true,
},
{
Name: "virtualmachineinstances/userlist",
Namespaced: true,
},
{
Name: "virtualmachineinstances/filesystemlist",
Namespaced: true,
},
{
Name: "virtualmachineinstances/addvolume",
Namespaced: true,
},
{
Name: "virtualmachineinstances/removevolume",
Namespaced: true,
},
{
Name: "virtualmachineinstances/sev/fetchcertchain",
Namespaced: true,
},
{
Name: "virtualmachineinstances/sev/querylaunchmeasurement",
Namespaced: true,
},
{
Name: "virtualmachineinstances/sev/setupsession",
Namespaced: true,
},
{
Name: "virtualmachineinstances/sev/injectlaunchsecret",
Namespaced: true,
},
}
response.WriteAsJson(list)
}).
Operation(version.Version+"getAPISubResources").
Doc("Get a KubeVirt API resources").
Returns(http.StatusOK, "OK", metav1.APIResourceList{}).
Returns(http.StatusNotFound, httpStatusNotFoundMessage, ""))
restful.Add(subws)
subwss = append(subwss, subws)
}
ws := new(restful.WebService)
// K8s needs the ability to query the root paths
ws.Route(ws.GET("/").
Produces(restful.MIME_JSON).Writes(metav1.RootPaths{}).
To(func(request *restful.Request, response *restful.Response) {
paths := []string{
"/apis",
"/openapi/v2",
}
for _, version := range v1.SubresourceGroupVersions {
paths = append(paths, definitions.GroupBasePath(version))
paths = append(paths, definitions.GroupVersionBasePath(version))
}
response.WriteAsJson(&metav1.RootPaths{
Paths: paths,
})
}).
Operation("getRootPaths").
Doc("Get KubeVirt API root paths").
Returns(http.StatusOK, "OK", metav1.RootPaths{}).
Returns(http.StatusNotFound, httpStatusNotFoundMessage, ""))
ws.Route(ws.GET("/healthz").To(healthz.KubeConnectionHealthzFuncFactory(app.clusterConfig, apiHealthVersion)).Doc("Health endpoint"))
componentProfiler := profiler.NewProfileManager(app.clusterConfig)
ws.Route(ws.GET("/start-profiler").To(componentProfiler.HandleStartProfiler).Doc("start profiler endpoint"))
ws.Route(ws.GET("/stop-profiler").To(componentProfiler.HandleStopProfiler).Doc("stop profiler endpoint"))
ws.Route(ws.GET("/dump-profiler").To(componentProfiler.HandleDumpProfiler).Doc("dump profiler results endpoint"))
// K8s needs the ability to query info about a specific API group
ws.Route(ws.GET(definitions.GroupBasePath(v1.SubresourceGroupVersions[0])).
Produces(restful.MIME_JSON).Writes(metav1.APIGroup{}).
To(func(request *restful.Request, response *restful.Response) {
response.WriteAsJson(subresourceAPIGroup())
}).
Operation(v1.SubresourceGroupVersions[0].Version+"GetSubAPIGroup").
Doc("Get a KubeVirt API Group").
Returns(http.StatusOK, "OK", metav1.APIGroup{}).
Returns(http.StatusNotFound, httpStatusNotFoundMessage, ""))
// K8s needs the ability to query the list of API groups this endpoint supports
ws.Route(ws.GET("apis").
Produces(restful.MIME_JSON).Writes(metav1.APIGroupList{}).
To(func(request *restful.Request, response *restful.Response) {
list := &metav1.APIGroupList{}
list.Kind = "APIGroupList"
list.Groups = append(list.Groups, subresourceAPIGroup())
response.WriteAsJson(list)
}).
Operation("getAPIGroupList").
Doc("Get a KubeVirt API GroupList").
Returns(http.StatusOK, "OK", metav1.APIGroupList{}).
Returns(http.StatusNotFound, httpStatusNotFoundMessage, ""))
once := sync.Once{}
var openapispec *spec.Swagger
ws.Route(ws.GET("openapi/v2").
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
To(func(request *restful.Request, response *restful.Response) {
once.Do(func() {
openapispec = openapi.LoadOpenAPISpec([]*restful.WebService{ws, subwss[0]})
openapispec.Info.Version = virtversion.Get().String()
})
response.WriteAsJson(openapispec)
}))
restful.Add(ws)
}
func (app *virtAPIApp) Compose() {
app.composeSubresources()
restful.Filter(filter.RequestLoggingFilter())
restful.Filter(restful.OPTIONSFilter())
restful.Filter(func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
allowed, reason, err := app.authorizor.Authorize(req)
if err != nil {
log.Log.Reason(err).Error("internal error during auth request")
resp.WriteHeader(http.StatusInternalServerError)
return
} else if allowed {
// request is permitted, so proceed with filter chain.
chain.ProcessFilter(req, resp)
return
}
resp.WriteErrorString(http.StatusUnauthorized, reason)
})
}
func (app *virtAPIApp) ConfigureOpenAPIService() {
config := openapi.CreateConfig()
config.GetDefinitions = v12.GetOpenAPIDefinitions
spec, err := builderv3.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(restful.RegisteredWebServices()), config)
if err != nil {
panic(err)
}
ws := new(restful.WebService)
ws.Path("/swaggerapi")
ws.Produces(restful.MIME_JSON)
f := func(req *restful.Request, resp *restful.Response) {
resp.WriteAsJson(spec)
}
ws.Route(ws.GET("/").To(f))
restful.DefaultContainer.Add(ws)
http.Handle("/swagger-ui/", http.StripPrefix("/swagger-ui/", http.FileServer(http.Dir(app.SwaggerUI))))
}
func deserializeStrings(in string) ([]string, error) {
if len(in) == 0 {
return nil, nil
}
var ret []string
if err := json.Unmarshal([]byte(in), &ret); err != nil {
return nil, err
}
return ret, nil
}
func (app *virtAPIApp) readRequestHeader() error {
authConfigMap, err := app.virtCli.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(context.Background(), util.ExtensionAPIServerAuthenticationConfigMap, metav1.GetOptions{})
if err != nil {
return err
}
// The request-header CA is mandatory. It can be retrieved from the configmap as we do here, or it must be provided
// via flag on start of this apiserver. Since we don't do the latter, the former is mandatory for us
// see https://github.com/kubernetes-incubator/apiserver-builder-alpha/blob/master/docs/concepts/auth.md#requestheader-authentication
_, ok := authConfigMap.Data[util.RequestHeaderClientCAFileKey]
if !ok {
return fmt.Errorf("requestheader-client-ca-file not found in extension-apiserver-authentication ConfigMap")
}
// This config map also contains information about what
// headers our authorizor should inspect
headers, ok := authConfigMap.Data["requestheader-username-headers"]
if ok {
headerList, err := deserializeStrings(headers)
if err != nil {
return err
}
app.authorizor.AddUserHeaders(headerList)
}
headers, ok = authConfigMap.Data["requestheader-group-headers"]
if ok {
headerList, err := deserializeStrings(headers)
if err != nil {
return err
}
app.authorizor.AddGroupHeaders(headerList)
}
headers, ok = authConfigMap.Data["requestheader-extra-headers-prefix"]
if ok {
headerList, err := deserializeStrings(headers)
if err != nil {
return err
}
app.authorizor.AddExtraPrefixHeaders(headerList)
}
return nil
}
func (app *virtAPIApp) prepareCertManager() {
app.certmanager = bootstrap.NewFileCertificateManager(app.tlsCertFilePath, app.tlsKeyFilePath)
app.handlerCertManager = bootstrap.NewFileCertificateManager(app.handlerCertFilePath, app.handlerKeyFilePath)
}
func (app *virtAPIApp) registerValidatingWebhooks(informers *webhooks.Informers) {
http.HandleFunc(components.VMICreateValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMICreate(w, r, app.clusterConfig)
})
http.HandleFunc(components.VMIUpdateValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMIUpdate(w, r, app.clusterConfig)
})
http.HandleFunc(components.VMValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMs(w, r, app.clusterConfig, app.virtCli, informers)
})
http.HandleFunc(components.VMIRSValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMIRS(w, r, app.clusterConfig)
})
http.HandleFunc(components.VMPoolValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMPool(w, r, app.clusterConfig)
})
http.HandleFunc(components.VMIPresetValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMIPreset(w, r)
})
http.HandleFunc(components.MigrationCreateValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeMigrationCreate(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.MigrationUpdateValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeMigrationUpdate(w, r)
})
http.HandleFunc(components.VMSnapshotValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMSnapshots(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.VMRestoreValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMRestores(w, r, app.clusterConfig, app.virtCli, informers)
})
http.HandleFunc(components.VMExportValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVMExports(w, r, app.clusterConfig)
})
http.HandleFunc(components.VMInstancetypeValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVmInstancetypes(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.VMClusterInstancetypeValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVmClusterInstancetypes(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.VMPreferenceValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVmPreferences(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.VMClusterPreferenceValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVmClusterPreferences(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.StatusValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeStatusValidation(w, r, app.clusterConfig, app.virtCli, informers)
})
http.HandleFunc(components.LauncherEvictionValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServePodEvictionInterceptor(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.MigrationPolicyCreateValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeMigrationPolicies(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.VMCloneCreateValidatePath, func(w http.ResponseWriter, r *http.Request) {
validating_webhook.ServeVirtualMachineClones(w, r, app.clusterConfig, app.virtCli)
})
}
func (app *virtAPIApp) registerMutatingWebhook(informers *webhooks.Informers) {
http.HandleFunc(components.VMMutatePath, func(w http.ResponseWriter, r *http.Request) {
mutating_webhook.ServeVMs(w, r, app.clusterConfig, app.virtCli)
})
http.HandleFunc(components.VMIMutatePath, func(w http.ResponseWriter, r *http.Request) {
mutating_webhook.ServeVMIs(w, r, app.clusterConfig, informers)
})
http.HandleFunc(components.MigrationMutatePath, func(w http.ResponseWriter, r *http.Request) {
mutating_webhook.ServeMigrationCreate(w, r)
})
http.HandleFunc(components.VMCloneCreateMutatePath, func(w http.ResponseWriter, r *http.Request) {
mutating_webhook.ServeClones(w, r)
})
}
func (app *virtAPIApp) setupTLS(k8sCAManager kvtls.ClientCAManager, kubevirtCAManager kvtls.ClientCAManager) {
// A VerifyClientCertIfGiven request means we're not guaranteed
// a client has been authenticated unless they provide a peer
// cert.
//
// Make sure to verify in subresource endpoint that peer cert
// was provided before processing request. If the peer cert is
// given on the connection, then we can be guaranteed that it
// was signed by the client CA in our pool.
//
// There is another ClientAuth type called 'RequireAndVerifyClientCert'
// We can't use this type here because during the aggregated api status
// check it attempts to hit '/' on our api endpoint to verify an http
// response is given. That status request won't send a peer cert regardless
// if the TLS handshake requests it. As a result, the TLS handshake fails
// and our aggregated endpoint never becomes available.
app.tlsConfig = kvtls.SetupTLSWithCertManager(k8sCAManager, app.certmanager, tls.VerifyClientCertIfGiven, app.clusterConfig)
app.handlerTLSConfiguration = kvtls.SetupTLSForVirtHandlerClients(kubevirtCAManager, app.handlerCertManager, app.externallyManaged)
}
func (app *virtAPIApp) startTLS(informerFactory controller.KubeInformerFactory) error {
errors := make(chan error)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
)
authConfigMapInformer := informerFactory.ApiAuthConfigMap()
kubevirtCAConfigInformer := informerFactory.KubeVirtCAConfigMap()
k8sCAManager := kvtls.NewKubernetesClientCAManager(authConfigMapInformer.GetStore())
kubevirtCAInformer := kvtls.NewCAManager(kubevirtCAConfigInformer.GetStore(), app.namespace, app.caConfigMapName)
app.setupTLS(k8sCAManager, kubevirtCAInformer)
app.Compose()
http.Handle("/metrics", promhttp.Handler())
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", app.BindAddress, app.Port),
TLSConfig: app.tlsConfig,
// Disable HTTP/2
// See CVE-2023-44487
TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
}
// start TLS server
go func() {
errors <- server.ListenAndServeTLS("", "")
}()
// start graceful shutdown handler
go func() {
select {