-
Notifications
You must be signed in to change notification settings - Fork 443
/
backend.go
772 lines (672 loc) · 26 KB
/
backend.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
/*
Copyright 2022 The Kubeflow 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 v1beta1
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"path/filepath"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"sigs.k8s.io/controller-runtime/pkg/client"
experimentv1beta1 "github.com/kubeflow/katib/pkg/apis/controller/experiments/v1beta1"
suggestionv1beta1 "github.com/kubeflow/katib/pkg/apis/controller/suggestions/v1beta1"
trialsv1beta1 "github.com/kubeflow/katib/pkg/apis/controller/trials/v1beta1"
api_pb_v1beta1 "github.com/kubeflow/katib/pkg/apis/manager/v1beta1"
consts "github.com/kubeflow/katib/pkg/controller.v1beta1/consts"
"github.com/kubeflow/katib/pkg/util/v1beta1/katibclient"
corev1 "k8s.io/api/core/v1"
common "github.com/kubeflow/katib/pkg/apis/controller/common/v1beta1"
mccommon "github.com/kubeflow/katib/pkg/metricscollector/v1beta1/common"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)
func NewKatibUIHandler(dbManagerAddr string) *KatibUIHandler {
kclient, err := katibclient.NewClient(client.Options{})
if err != nil {
log.Printf("NewClient for Katib failed: %v", err)
panic(err)
}
return &KatibUIHandler{
katibClient: kclient,
dbManagerAddr: dbManagerAddr,
}
}
// ServeIndex will return index.html for any non-API URL
func (k *KatibUIHandler) ServeIndex(buildDir string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
fp := filepath.Join(buildDir, "static/index.html")
log.Printf("Sending file %s for url: %s", fp, r.URL)
// never cache index.html
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0")
// return the contents of index.html
http.ServeFile(w, r, fp)
}
}
func (k *KatibUIHandler) connectManager() (*grpc.ClientConn, api_pb_v1beta1.DBManagerClient) {
conn, err := grpc.Dial(k.dbManagerAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Printf("Dial to GRPC failed: %v", err)
return nil, nil
}
c := api_pb_v1beta1.NewDBManagerClient(conn)
return conn, c
}
func (k *KatibUIHandler) CreateExperiment(w http.ResponseWriter, r *http.Request) {
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
log.Printf("Failed to decode body: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dataJSON, ok := data["postData"]
if !ok {
msg := "Couldn't load the 'postData' field of the request's data"
log.Println(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
jsonbody, err := json.Marshal(dataJSON)
if err != nil {
log.Printf("Marshal data for experiment failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
job := experimentv1beta1.Experiment{}
if err := json.Unmarshal(jsonbody, &job); err != nil {
log.Printf("Unmarshal experiment failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
namespace := job.ObjectMeta.Namespace
experimentName := job.ObjectMeta.Name
user, err := IsAuthorized(consts.ActionTypeCreate, namespace, consts.PluralExperiment, "", experimentName, experimentv1beta1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to create experiment: %s in namespace: %s \n", user, experimentName, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
err = k.katibClient.CreateRuntimeObject(&job)
if err != nil {
log.Printf("CreateRuntimeObject from parameters failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (k *KatibUIHandler) FetchExperiments(w http.ResponseWriter, r *http.Request) {
namespaces, ok := r.URL.Query()["namespace"]
if !ok {
log.Printf("No 'namespace' query parameter was provided.")
err := errors.New("no 'namespace' query parameter was provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
namespace := namespaces[0]
user, err := IsAuthorized(consts.ActionTypeList, namespace, consts.PluralExperiment, "", "", experimentv1beta1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to list experiments in namespace: %s \n", user, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
experiments, err := k.getExperiments([]string{namespace})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(experiments)
if err != nil {
log.Printf("Marshal experiments failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write experiments failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (k *KatibUIHandler) DeleteExperiment(w http.ResponseWriter, r *http.Request) {
namespaces, ok := r.URL.Query()["namespace"]
if !ok {
log.Printf("No 'namespace' query parameter was provided.")
err := errors.New("no 'namespace' query parameter was provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
experimentNames, ok := r.URL.Query()["experimentName"]
if !ok {
log.Printf("No experimentName provided in Query parameteres! Provide an 'experimentName' param")
err := errors.New("no experimentName provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
experimentName := experimentNames[0]
namespace := namespaces[0]
user, err := IsAuthorized(consts.ActionTypeDelete, namespace, consts.PluralExperiment, "", experimentName, experimentv1beta1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to delete experiment: %s in namespace: %s \n", user, experimentName, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
experiment, err := k.katibClient.GetExperiment(experimentName, namespace)
if err != nil {
log.Printf("GetExperiment failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = k.katibClient.DeleteRuntimeObject(experiment)
if err != nil {
log.Printf("DeleteRuntimeObject failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
isExperimentDeleted := false
var experiments []ExperimentView
// Waiting until experiment will be deleted
for !isExperimentDeleted {
// At first, try to list experiments in cluster scope
experiments, err = k.getExperiments([]string{""})
if err != nil {
// If failed, just try to list experiments from own namespace
experiments, err = k.getExperiments([]string{})
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
isExperimentDeleted = true
for _, experiment := range experiments {
if experiment.Name == experimentName {
isExperimentDeleted = false
break
}
}
}
response, err := json.Marshal(experiments)
if err != nil {
log.Printf("Marshal HP and NAS experiments failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write HP and NAS experiments failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// FetchTrialTemplates gets all trial templates in all namespaces
func (k *KatibUIHandler) FetchTrialTemplates(w http.ResponseWriter, r *http.Request) {
trialTemplatesViewList, err := k.getTrialTemplatesViewList(r)
if err != nil {
log.Printf("getTrialTemplatesViewList failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
TrialTemplatesResponse := TrialTemplatesResponse{
Data: trialTemplatesViewList,
}
response, err := json.Marshal(TrialTemplatesResponse)
if err != nil {
log.Printf("Marshal templates failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write template failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// AddTemplate adds template to ConfigMap
func (k *KatibUIHandler) AddTemplate(w http.ResponseWriter, r *http.Request) {
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
log.Printf("Failed to decode body: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
updatedConfigMapNamespace := data["updatedConfigMapNamespace"].(string)
updatedConfigMapName := data["updatedConfigMapName"].(string)
updatedConfigMapPath := data["updatedConfigMapPath"].(string)
updatedTemplateYaml := data["updatedTemplateYaml"].(string)
user, err := IsAuthorized(consts.ActionTypeCreate, updatedConfigMapNamespace, corev1.ResourceConfigMaps.String(), "", updatedConfigMapName, corev1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to add configmap: %s in namespace: %s \n", user, updatedConfigMapName, updatedConfigMapNamespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
newTemplates, err := k.updateTrialTemplates(updatedConfigMapNamespace, updatedConfigMapName, "", updatedConfigMapPath, updatedTemplateYaml, ActionTypeAdd, r)
if err != nil {
log.Printf("updateTrialTemplates failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
TrialTemplatesResponse := TrialTemplatesResponse{
Data: newTemplates,
}
response, err := json.Marshal(TrialTemplatesResponse)
if err != nil {
log.Printf("Marhal failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// EditTemplate edits template in ConfigMap
func (k *KatibUIHandler) EditTemplate(w http.ResponseWriter, r *http.Request) {
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
log.Printf("Failed to decode body: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
updatedConfigMapNamespace := data["updatedConfigMapNamespace"].(string)
updatedConfigMapName := data["updatedConfigMapName"].(string)
configMapPath := data["configMapPath"].(string)
updatedConfigMapPath := data["updatedConfigMapPath"].(string)
updatedTemplateYaml := data["updatedTemplateYaml"].(string)
user, err := IsAuthorized(consts.ActionTypeUpdate, updatedConfigMapNamespace, corev1.ResourceConfigMaps.String(), "", updatedConfigMapName, corev1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to edit configmap: %s in namespace: %s \n", user, updatedConfigMapName, updatedConfigMapNamespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
newTemplates, err := k.updateTrialTemplates(updatedConfigMapNamespace, updatedConfigMapName, configMapPath, updatedConfigMapPath, updatedTemplateYaml, ActionTypeEdit, r)
if err != nil {
log.Printf("updateTrialTemplates failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
TrialTemplatesResponse := TrialTemplatesResponse{
Data: newTemplates,
}
response, err := json.Marshal(TrialTemplatesResponse)
if err != nil {
log.Printf("Marhal failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// DeleteTemplate deletes template in ConfigMap
func (k *KatibUIHandler) DeleteTemplate(w http.ResponseWriter, r *http.Request) {
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
log.Printf("Failed to decode body: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
updatedConfigMapNamespace := data["updatedConfigMapNamespace"].(string)
updatedConfigMapName := data["updatedConfigMapName"].(string)
updatedConfigMapPath := data["updatedConfigMapPath"].(string)
user, err := IsAuthorized(consts.ActionTypeDelete, updatedConfigMapNamespace, corev1.ResourceConfigMaps.String(), "", updatedConfigMapName, corev1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to delete configmap: %s in namespace: %s \n", user, updatedConfigMapName, updatedConfigMapNamespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
newTemplates, err := k.updateTrialTemplates(updatedConfigMapNamespace, updatedConfigMapName, "", updatedConfigMapPath, "", ActionTypeDelete, r)
if err != nil {
log.Printf("updateTrialTemplates failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
TrialTemplatesResponse := TrialTemplatesResponse{
Data: newTemplates,
}
response, err := json.Marshal(TrialTemplatesResponse)
if err != nil {
log.Printf("Marhal failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (k *KatibUIHandler) FetchNamespaces(w http.ResponseWriter, r *http.Request) {
// Get all available namespaces
namespaces, err := k.getAvailableNamespaces()
if err != nil {
log.Printf("GetAvailableNamespaces failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(namespaces)
if err != nil {
log.Printf("Marshal namespaces failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write namespaces failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// FetchExperiment gets experiment in specific namespace.
func (k *KatibUIHandler) FetchExperiment(w http.ResponseWriter, r *http.Request) {
namespaces, ok := r.URL.Query()["namespace"]
if !ok {
log.Printf("No 'namespace' query parameter was provided.")
err := errors.New("no 'namespace' query parameter was provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
experimentNames, ok := r.URL.Query()["experimentName"]
if !ok {
log.Printf("No experimentName provided in Query parameteres! Provide an 'experimentName' param")
err := errors.New("no experimentName provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
experimentName := experimentNames[0]
namespace := namespaces[0]
user, err := IsAuthorized(consts.ActionTypeGet, namespace, consts.PluralExperiment, "", experimentName, experimentv1beta1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to get experiment: %s in namespace: %s \n", user, experimentName, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
experiment, err := k.katibClient.GetExperiment(experimentName, namespace)
if err != nil {
log.Printf("GetExperiment failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(experiment)
if err != nil {
log.Printf("Marshal Experiment failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write Experiment failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// FetchSuggestion gets suggestion in specific namespace
func (k *KatibUIHandler) FetchSuggestion(w http.ResponseWriter, r *http.Request) {
namespaces, ok := r.URL.Query()["namespace"]
if !ok {
log.Printf("No namespace provided in Query parameters! Provide a 'namespace' param")
err := errors.New("no 'namespace' provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
suggestionNames, ok := r.URL.Query()["suggestionName"]
if !ok {
log.Printf("No experimentName provided in Query parameteres! Provide an 'experimentName' param")
err := errors.New("no experimentName provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
suggestionName := suggestionNames[0]
namespace := namespaces[0]
user, err := IsAuthorized(consts.ActionTypeGet, namespace, consts.PluralSuggestion, "", suggestionName, suggestionv1beta1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to get suggestion: %s in namespace: %s \n", user, suggestionName, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
suggestion, err := k.katibClient.GetSuggestion(suggestionName, namespace)
if err != nil {
log.Printf("GetSuggestion failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(suggestion)
if err != nil {
log.Printf("Marshal Suggestion failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write Suggestion failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// FetchTrial gets trial in specific namespace.
func (k *KatibUIHandler) FetchTrial(w http.ResponseWriter, r *http.Request) {
namespaces, ok := r.URL.Query()["namespace"]
if !ok {
log.Printf("No namespace provided in Query parameters! Provide a 'namespace' param")
err := errors.New("no 'namespace' provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
trialNames, ok := r.URL.Query()["trialName"]
if !ok {
log.Printf("No trialName provided in Query parameters! Provide a 'trialName' param")
err := errors.New("no 'trialName' provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
trialName := trialNames[0]
namespace := namespaces[0]
user, err := IsAuthorized(consts.ActionTypeGet, namespace, consts.PluralTrial, "", trialName, trialsv1beta1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to get trial: %s from namespace: %s \n", user, trialName, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
trial, err := k.katibClient.GetTrial(trialName, namespace)
if err != nil {
log.Printf("GetTrial failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(trial)
if err != nil {
log.Printf("Marshal Trial failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write trial failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// FetchTrialLogs fetches logs for a trial in specific namespace.
func (k *KatibUIHandler) FetchTrialLogs(w http.ResponseWriter, r *http.Request) {
namespaces, ok := r.URL.Query()["namespace"]
if !ok {
log.Printf("No namespace provided in Query parameters! Provide a 'namespace' param")
err := errors.New("no 'namespace' provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
trialNames, ok := r.URL.Query()["trialName"]
if !ok {
log.Printf("No trialName provided in Query parameters! Provide a 'trialName' param")
err := errors.New("no 'trialName' provided")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
trialName := trialNames[0]
namespace := namespaces[0]
user, err := IsAuthorized(consts.ActionTypeGet, namespace, consts.PluralTrial, "", trialName, trialsv1beta1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to get trial: %s in namespace: %s \n", user, trialName, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
trial := &trialsv1beta1.Trial{}
if err := k.katibClient.GetClient().Get(context.Background(), types.NamespacedName{Name: trialName, Namespace: namespace}, trial); err != nil {
log.Printf("GetLogs failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// TODO: Use controller-runtime client instead of kubernetes client to get logs, once this is available
clientset, err := createKubernetesClientset()
if err != nil {
log.Printf("GetLogs failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
podName, err := fetchMasterPodName(clientset, trial)
if err != nil {
log.Printf("GetLogs failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user, err = IsAuthorized(consts.ActionTypeGet, namespace, corev1.ResourcePods.String(), "log", podName, corev1.SchemeGroupVersion, k.katibClient.GetClient(), r)
if user == "" && err != nil {
log.Printf("No user provided in kubeflow-userid header.")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
log.Printf("The user: %s is not authorized to get pod logs: %s in namespace: %s \n", user, podName, namespace)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
podLogOpts := corev1.PodLogOptions{}
podLogOpts.Container = trial.Spec.PrimaryContainerName
if trial.Spec.MetricsCollector.Collector.Kind == common.StdOutCollector {
podLogOpts.Container = mccommon.MetricLoggerCollectorContainerName
}
logs, err := fetchPodLogs(clientset, namespace, podName, podLogOpts)
if err != nil {
log.Printf("GetLogs failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(logs)
if err != nil {
log.Printf("Marshal logs failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err = w.Write(response); err != nil {
log.Printf("Write logs failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// createKubernetesClientset returns kubernetes clientset
func createKubernetesClientset() (*kubernetes.Clientset, error) {
cfg, err := config.GetConfig()
if err != nil {
return nil, err
}
clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
return clientset, nil
}
// fetchMasterPodName returns name of the master pod for a trial
func fetchMasterPodName(clientset *kubernetes.Clientset, trial *trialsv1beta1.Trial) (string, error) {
selectionLabel := consts.LabelTrialName + "=" + trial.ObjectMeta.Name
for primaryKey, primaryValue := range trial.Spec.PrimaryPodLabels {
selectionLabel = selectionLabel + "," + primaryKey + "=" + primaryValue
}
podList, err := clientset.CoreV1().Pods(trial.ObjectMeta.Namespace).List(context.Background(), metav1.ListOptions{LabelSelector: selectionLabel})
if err != nil {
return "", err
}
if len(podList.Items) == 0 {
return "", errors.New(`Failed to find logs for this Trial. Make sure you've set "spec.trialTemplate.retain"
field to "true" in the Experiment definition. If this error persists then the Pod's logs are not currently
persisted in the cluster.`)
}
// If Pod is Running or Succeeded Pod, return it.
for _, pod := range podList.Items {
if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodRunning {
return pod.Name, nil
}
}
// Otherwise, return the first Failed Pod.
for _, pod := range podList.Items {
if pod.Status.Phase == corev1.PodFailed {
return pod.Name, nil
}
}
// Otherwise, return error since Pod is in the Pending state.
return "", errors.New("Failed to get logs for this Trial. Pod is in the Pending or Unknown state.")
}
// fetchPodLogs returns logs of a pod for the given job name and namespace
func fetchPodLogs(clientset *kubernetes.Clientset, namespace string, podName string, podLogOpts corev1.PodLogOptions) (string, error) {
req := clientset.CoreV1().Pods(namespace).GetLogs(podName, &podLogOpts)
podLogs, err := req.Stream(context.Background())
if err != nil {
return "", err
}
defer podLogs.Close()
buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
return "", err
}
str := buf.String()
return str, nil
}