-
Notifications
You must be signed in to change notification settings - Fork 90
/
config.go
1376 lines (1196 loc) · 47.8 KB
/
config.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
package handlers
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/pkg/errors"
downstreamtypes "github.com/replicatedhq/kots/pkg/api/downstream/types"
apptypes "github.com/replicatedhq/kots/pkg/app/types"
"github.com/replicatedhq/kots/pkg/config"
kotsconfig "github.com/replicatedhq/kots/pkg/config"
"github.com/replicatedhq/kots/pkg/crypto"
"github.com/replicatedhq/kots/pkg/helm"
kotsadmconfig "github.com/replicatedhq/kots/pkg/kotsadmconfig"
configtypes "github.com/replicatedhq/kots/pkg/kotsadmconfig/types"
configvalidation "github.com/replicatedhq/kots/pkg/kotsadmconfig/validation"
"github.com/replicatedhq/kots/pkg/kotsutil"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/midstream"
"github.com/replicatedhq/kots/pkg/preflight"
registrytypes "github.com/replicatedhq/kots/pkg/registry/types"
"github.com/replicatedhq/kots/pkg/render"
"github.com/replicatedhq/kots/pkg/replicatedapp"
"github.com/replicatedhq/kots/pkg/store"
storetypes "github.com/replicatedhq/kots/pkg/store/types"
"github.com/replicatedhq/kots/pkg/template"
"github.com/replicatedhq/kots/pkg/util"
"github.com/replicatedhq/kots/pkg/version"
kotsv1beta1 "github.com/replicatedhq/kotskinds/apis/kots/v1beta1"
"github.com/replicatedhq/kotskinds/multitype"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/scheme"
)
type UpdateAppConfigRequest struct {
Sequence int64 `json:"sequence"`
CreateNewVersion bool `json:"createNewVersion"`
ConfigGroups []kotsv1beta1.ConfigGroup `json:"configGroups"`
}
type LiveAppConfigRequest struct {
Sequence int64 `json:"sequence"`
ConfigGroups []kotsv1beta1.ConfigGroup `json:"configGroups"`
}
type UpdateAppConfigResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
RequiredItems []string `json:"requiredItems,omitempty"`
ValidationErrors []configtypes.ConfigGroupValidationError `json:"validationErrors,omitempty"`
}
type LiveAppConfigResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
ConfigGroups []kotsv1beta1.ConfigGroup `json:"configGroups"`
ValidationErrors []configtypes.ConfigGroupValidationError `json:"validationErrors,omitempty"`
}
type CurrentAppConfigResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
DownstreamVersion *downstreamtypes.DownstreamVersion `json:"downstreamVersion"`
ConfigGroups []kotsv1beta1.ConfigGroup `json:"configGroups"`
ValidationErrors []configtypes.ConfigGroupValidationError `json:"validationErrors,omitempty"`
}
type DownloadFileFromConfigResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
func (h *Handler) DownloadFileFromConfig(w http.ResponseWriter, r *http.Request) {
downloadFileFromConfigResponse := DownloadFileFromConfigResponse{
Success: false,
}
foundApp, err := store.GetStore().GetAppFromSlug(mux.Vars(r)["appSlug"])
if err != nil {
logger.Error(err)
downloadFileFromConfigResponse.Error = "failed to get app from app slug"
JSON(w, http.StatusInternalServerError, downloadFileFromConfigResponse)
return
}
sequence, err := strconv.Atoi(mux.Vars(r)["sequence"])
if err != nil {
logger.Error(err)
downloadFileFromConfigResponse.Error = "failed to parse app sequence"
JSON(w, http.StatusInternalServerError, downloadFileFromConfigResponse)
return
}
filename := mux.Vars(r)["filename"]
if filename == "" {
logger.Error(err)
downloadFileFromConfigResponse.Error = "failed to parse filename, parameter was empty"
JSON(w, http.StatusInternalServerError, downloadFileFromConfigResponse)
return
}
archiveDir, err := ioutil.TempDir("", "kotsadmconfig")
if err != nil {
logger.Error(err)
downloadFileFromConfigResponse.Error = "failed to create temp directory"
JSON(w, http.StatusInternalServerError, downloadFileFromConfigResponse)
}
defer os.RemoveAll(archiveDir)
configValue, err := getAppConfigValueForFile(foundApp, int64(sequence), filename, archiveDir)
if err != nil {
logger.Error(err)
downloadFileFromConfigResponse.Error = "failed to get app config"
JSON(w, http.StatusInternalServerError, downloadFileFromConfigResponse)
return
}
decoded, err := base64.StdEncoding.DecodeString(configValue)
if err != nil {
logger.Error(err)
downloadFileFromConfigResponse.Error = "failed to decode config value"
JSON(w, http.StatusInternalServerError, downloadFileFromConfigResponse)
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
w.Header().Set("Content-Length", strconv.Itoa(len(decoded)))
w.WriteHeader(http.StatusOK)
w.Write(decoded)
}
func (h *Handler) UpdateAppConfig(w http.ResponseWriter, r *http.Request) {
updateAppConfigResponse := UpdateAppConfigResponse{
Success: false,
}
updateAppConfigRequest := UpdateAppConfigRequest{}
if err := json.NewDecoder(r.Body).Decode(&updateAppConfigRequest); err != nil {
logger.Error(err)
updateAppConfigResponse.Error = "failed to decode request body"
JSON(w, http.StatusBadRequest, updateAppConfigResponse)
return
}
if util.IsHelmManaged() {
// TODO: will need to consider flow for when ConfigSpec changes
appSlug := mux.Vars(r)["appSlug"]
helmApp := helm.GetHelmApp(appSlug)
if helmApp == nil {
w.WriteHeader(http.StatusNotFound)
return
}
requiredItems, requiredItemsTitles := getMissingRequiredConfig(updateAppConfigRequest.ConfigGroups)
if len(requiredItems) > 0 {
updateAppConfigResponse.RequiredItems = requiredItems
updateAppConfigResponse.Error = fmt.Sprintf("The following fields are required: %s", strings.Join(requiredItemsTitles, ", "))
JSON(w, http.StatusBadRequest, updateAppConfigResponse)
return
}
helmApp.TempConfigValues = updateAppConfigValues(helmApp.TempConfigValues, updateAppConfigRequest.ConfigGroups)
JSON(w, http.StatusOK, UpdateAppConfigResponse{Success: true})
return
}
foundApp, err := store.GetStore().GetAppFromSlug(mux.Vars(r)["appSlug"])
if err != nil {
logger.Error(err)
updateAppConfigResponse.Error = "failed to get app from app slug"
JSON(w, http.StatusInternalServerError, updateAppConfigResponse)
return
}
isEditbale, err := isVersionConfigEditable(foundApp, updateAppConfigRequest.Sequence)
if err != nil {
updateAppConfigResponse.Error = "failed to check if version is editable"
logger.Error(errors.Wrap(err, updateAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, updateAppConfigResponse)
return
}
if !isEditbale {
updateAppConfigResponse.Error = "this version cannot be edited"
logger.Error(errors.Wrap(err, updateAppConfigResponse.Error))
JSON(w, http.StatusForbidden, updateAppConfigResponse)
return
}
validationErrors, err := configvalidation.ValidateConfigSpec(kotsv1beta1.ConfigSpec{Groups: updateAppConfigRequest.ConfigGroups})
if err != nil {
updateAppConfigResponse.Error = "failed to validate config spec."
logger.Error(errors.Wrap(err, updateAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, updateAppConfigResponse)
return
}
if len(validationErrors) > 0 {
updateAppConfigResponse.Error = "invalid config values"
updateAppConfigResponse.ValidationErrors = validationErrors
logger.Errorf("%v, validation errors: %+v", updateAppConfigResponse.Error, validationErrors)
JSON(w, http.StatusBadRequest, updateAppConfigResponse)
return
}
archiveDir, err := ioutil.TempDir("", "kotsadm")
if err != nil {
updateAppConfigResponse.Error = "failed to create temp dir"
logger.Error(errors.Wrap(err, updateAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, updateAppConfigResponse)
return
}
defer os.RemoveAll(archiveDir)
err = store.GetStore().GetAppVersionArchive(foundApp.ID, updateAppConfigRequest.Sequence, archiveDir)
if err != nil {
updateAppConfigResponse.Error = "failed to get app version archive"
logger.Error(errors.Wrap(err, updateAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, updateAppConfigResponse)
return
}
createNewVersion, err := shouldCreateNewAppVersion(archiveDir, foundApp.ID, updateAppConfigRequest.Sequence)
if err != nil {
updateAppConfigResponse.Error = "failed to check if version should be created"
logger.Error(errors.Wrap(err, updateAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, updateAppConfigResponse)
return
}
isPrimaryVersion := true
skipPrefligths := false
deploy := false
resp, err := updateAppConfig(foundApp, updateAppConfigRequest.Sequence, updateAppConfigRequest.ConfigGroups, createNewVersion, isPrimaryVersion, skipPrefligths, deploy)
if err != nil {
logger.Error(err)
JSON(w, http.StatusInternalServerError, resp)
return
}
if len(resp.RequiredItems) > 0 {
JSON(w, http.StatusBadRequest, resp)
return
}
JSON(w, http.StatusOK, UpdateAppConfigResponse{Success: true})
}
func (h *Handler) LiveAppConfig(w http.ResponseWriter, r *http.Request) {
liveAppConfigResponse := LiveAppConfigResponse{
Success: false,
}
appSlug := mux.Vars(r)["appSlug"]
liveAppConfigRequest := LiveAppConfigRequest{}
if err := json.NewDecoder(r.Body).Decode(&liveAppConfigRequest); err != nil {
logger.Error(err)
liveAppConfigResponse.Error = "failed to decode request body"
JSON(w, http.StatusBadRequest, liveAppConfigResponse)
return
}
var kotsKinds *kotsutil.KotsKinds
var nonRenderedConfig *kotsv1beta1.Config
var appLicense *kotsv1beta1.License
var app apptypes.AppType
var localRegistry registrytypes.RegistrySettings
createNewVersion := false
configValues := configValuesFromConfigGroups(liveAppConfigRequest.ConfigGroups)
if util.IsHelmManaged() {
helmApp := helm.GetHelmApp(appSlug)
if helmApp == nil {
w.WriteHeader(http.StatusNotFound)
return
}
app = helmApp
isPending, _ := strconv.ParseBool(r.URL.Query().Get("isPending"))
if !isPending {
k, err := helm.GetKotsKindsForRevision(helmApp.Release.Name, liveAppConfigRequest.Sequence, helmApp.Namespace)
if err != nil {
logger.Error(errors.Wrap(err, "failed to get kots kinds for helm"))
w.WriteHeader(http.StatusInternalServerError)
return
}
kotsKinds = &k
nonRenderedConfig = kotsKinds.Config
appLicense = kotsKinds.License
createNewVersion = true
} else {
licenseID := helm.GetKotsLicenseID(&helmApp.Release)
if licenseID == "" {
logger.Error(errors.Errorf("no license and no license ID found for release %s", helmApp.Release.Name))
w.WriteHeader(http.StatusInternalServerError)
return
}
k, err := helm.GetKotsKindsFromUpstreamChartVersion(helmApp, licenseID, r.URL.Query().Get("semver"))
if err != nil {
logger.Error(errors.Wrap(err, "failed to get kotskinds from upstream chart"))
w.WriteHeader(http.StatusInternalServerError)
return
}
licenseData, err := replicatedapp.GetLatestLicenseForHelm(licenseID)
if err != nil {
logger.Error(errors.Wrap(err, "failed to download license for chart archive"))
w.WriteHeader(http.StatusInternalServerError)
return
}
k.License = licenseData.License
kotsKinds = &k
nonRenderedConfig = kotsKinds.Config
appLicense = kotsKinds.License
}
} else {
foundApp, err := store.GetStore().GetAppFromSlug(appSlug)
if err != nil {
liveAppConfigResponse.Error = "failed to get app from app slug"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
app = foundApp
appLicense, err = store.GetStore().GetLatestLicenseForApp(foundApp.ID)
if err != nil {
liveAppConfigResponse.Error = "failed to get license for app"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
archiveDir, err := os.MkdirTemp("", "kotsadm")
if err != nil {
liveAppConfigResponse.Error = "failed to create temp dir"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
defer os.RemoveAll(archiveDir)
err = store.GetStore().GetAppVersionArchive(foundApp.ID, liveAppConfigRequest.Sequence, archiveDir)
if err != nil {
liveAppConfigResponse.Error = "failed to get app version archive"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
kotsKinds, err = kotsutil.LoadKotsKinds(archiveDir)
if err != nil {
liveAppConfigResponse.Error = "failed to load kots kinds from path"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
// get the non-rendered config from the upstream directory because we have to re-render it with the new values
nonRenderedConfig, err = kotsutil.FindConfigInPath(filepath.Join(archiveDir, "upstream"))
if err != nil {
liveAppConfigResponse.Error = "failed to find non-rendered config"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
registryInfo, err := store.GetStore().GetRegistryDetailsForApp(foundApp.ID)
if err != nil {
liveAppConfigResponse.Error = "failed to get app registry info"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
localRegistry = registryInfo
createNewVersion, err = shouldCreateNewAppVersion(archiveDir, foundApp.GetID(), liveAppConfigRequest.Sequence)
if err != nil {
liveAppConfigResponse.Error = "failed to check new version"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
}
sequence := liveAppConfigRequest.Sequence
if createNewVersion {
sequence += 1
}
versionInfo := template.VersionInfoFromInstallationSpec(sequence, app.GetIsAirgap(), kotsKinds.Installation.Spec) // sequence +1 because the sequence will be incremented on save (and we want the preview to be accurate)
appInfo := template.ApplicationInfo{Slug: app.GetSlug()}
renderedConfig, err := kotsconfig.TemplateConfigObjects(nonRenderedConfig, configValues, appLicense, &kotsKinds.KotsApplication, localRegistry, &versionInfo, &appInfo, kotsKinds.IdentityConfig, app.GetNamespace(), false)
if err != nil {
liveAppConfigResponse.Error = "failed to render templates"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
liveAppConfigResponse.ConfigGroups = []kotsv1beta1.ConfigGroup{}
if renderedConfig != nil {
validationErrors, err := configvalidation.ValidateConfigSpec(renderedConfig.Spec)
if err != nil {
liveAppConfigResponse.Error = "failed to validate config spec"
logger.Error(errors.Wrap(err, liveAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, liveAppConfigResponse)
return
}
liveAppConfigResponse.ConfigGroups = renderedConfig.Spec.Groups
if len(validationErrors) > 0 {
liveAppConfigResponse.ValidationErrors = validationErrors
logger.Warnf("Validation errors found for config spec: %v", validationErrors)
}
}
liveAppConfigResponse.Success = true
JSON(w, http.StatusOK, liveAppConfigResponse)
}
func configValuesFromConfigGroups(configGroups []kotsv1beta1.ConfigGroup) map[string]template.ItemValue {
configValues := map[string]template.ItemValue{}
for _, group := range configGroups {
for _, item := range group.Items {
// collect all repeatable items
// Future Note: This could be refactored to use CountByGroup as the control. Front end provides the exact CountByGroup it wants, back end takes care of ValuesByGroup entries.
// this way the front end doesn't have to add anything to ValuesByGroup, it just sets values there.
if item.Repeatable {
for valuesByGroupName, groupValues := range item.ValuesByGroup {
config.CreateVariadicValues(&item, valuesByGroupName)
for fieldName, subItem := range groupValues {
itemValue := template.ItemValue{
Value: subItem,
RepeatableItem: item.Name,
}
if item.Filename != "" {
itemValue.Filename = fieldName
}
configValues[fieldName] = itemValue
}
}
continue
}
generatedValue := template.ItemValue{}
if item.Value.Type == multitype.String {
generatedValue.Value = item.Value.StrVal
} else {
generatedValue.Value = item.Value.BoolVal
}
if item.Default.Type == multitype.String {
generatedValue.Default = item.Default.StrVal
} else {
generatedValue.Default = item.Default.BoolVal
}
if item.Type == "file" {
generatedValue.Filename = item.Filename
}
configValues[item.Name] = generatedValue
}
}
return configValues
}
func (h *Handler) CurrentAppConfig(w http.ResponseWriter, r *http.Request) {
currentAppConfigResponse := CurrentAppConfigResponse{
Success: false,
}
appSlug := mux.Vars(r)["appSlug"]
sequence, err := strconv.ParseInt(mux.Vars(r)["sequence"], 10, 64)
if err != nil {
logger.Error(err)
currentAppConfigResponse.Error = "failed to parse app sequence"
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
var kotsKinds *kotsutil.KotsKinds
var nonRenderedConfig *kotsv1beta1.Config
var license *kotsv1beta1.License
var localRegistry registrytypes.RegistrySettings
var app apptypes.AppType
var downstreamVersion *downstreamtypes.DownstreamVersion
createNewVersion := false
if util.IsHelmManaged() {
helmApp := helm.GetHelmApp(appSlug)
if helmApp == nil {
w.WriteHeader(http.StatusNotFound)
return
}
app = helmApp
isPending, _ := strconv.ParseBool(r.URL.Query().Get("isPending"))
if !isPending {
installedRelease, err := helm.GetChartVersion(helmApp.Release.Name, sequence, helmApp.Namespace)
if err != nil {
logger.Error(errors.Wrap(err, "failed to get helm release"))
w.WriteHeader(http.StatusInternalServerError)
return
}
if installedRelease == nil {
w.WriteHeader(http.StatusNotFound)
return
}
downstreamVersion = helmReleaseToDownsreamVersion(installedRelease)
k, err := helm.GetKotsKindsForRevision(helmApp.Release.Name, sequence, helmApp.Namespace)
if err != nil {
logger.Error(errors.Wrap(err, "failed to get kots kinds for helm"))
w.WriteHeader(http.StatusInternalServerError)
return
}
kotsKinds = &k
nonRenderedConfig = kotsKinds.Config
license = kotsKinds.License
createNewVersion = true
} else {
appKotsKinds, err := helm.GetKotsKindsFromHelmApp(helmApp)
if err != nil {
logger.Error(errors.Wrap(err, "failed to get app kotskinds"))
w.WriteHeader(http.StatusInternalServerError)
return
}
licenseID := helm.GetKotsLicenseID(&helmApp.Release)
if licenseID == "" {
logger.Error(errors.Errorf("no license and no license ID found for release %s", helmApp.Release.Name))
w.WriteHeader(http.StatusInternalServerError)
return
}
k, err := helm.GetKotsKindsFromUpstreamChartVersion(helmApp, licenseID, r.URL.Query().Get("semver"))
if err != nil {
logger.Error(errors.Wrap(err, "failed to get kotskinds from upstream chart"))
w.WriteHeader(http.StatusInternalServerError)
return
}
k.ConfigValues = appKotsKinds.ConfigValues.DeepCopy()
licenseData, err := replicatedapp.GetLatestLicenseForHelm(licenseID)
if err != nil {
logger.Error(errors.Wrap(err, "failed to download license for chart archive"))
w.WriteHeader(http.StatusInternalServerError)
return
}
k.License = licenseData.License
kotsKinds = &k
nonRenderedConfig = kotsKinds.Config
license = kotsKinds.License
}
} else {
foundApp, err := store.GetStore().GetAppFromSlug(appSlug)
if err != nil {
currentAppConfigResponse.Error = "failed to get app from app slug"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
app = foundApp
status, err := store.GetStore().GetDownstreamVersionStatus(foundApp.ID, sequence)
if err != nil {
currentAppConfigResponse.Error = "failed to get downstream version status"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
if status == storetypes.VersionPendingDownload {
err := errors.Errorf("not returning config for version %d because it's %s", sequence, status)
logger.Error(err)
currentAppConfigResponse.Error = err.Error()
JSON(w, http.StatusBadRequest, currentAppConfigResponse)
return
}
license, err = store.GetStore().GetLatestLicenseForApp(foundApp.ID)
if err != nil {
currentAppConfigResponse.Error = "failed to get license for app"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
archiveDir, err := os.MkdirTemp("", "kotsadm")
if err != nil {
currentAppConfigResponse.Error = "failed to create temp dir"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
defer os.RemoveAll(archiveDir)
err = store.GetStore().GetAppVersionArchive(foundApp.ID, sequence, archiveDir)
if err != nil {
currentAppConfigResponse.Error = "failed to get app version archive"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
kotsKinds, err = kotsutil.LoadKotsKinds(archiveDir)
if err != nil {
currentAppConfigResponse.Error = "failed to load kots kinds from path"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
// get the non-rendered config from the upstream directory because we have to re-render it with the new values
nonRenderedConfig, err = kotsutil.FindConfigInPath(filepath.Join(archiveDir, "upstream"))
if err != nil {
currentAppConfigResponse.Error = "failed to find non-rendered config"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
registryInfo, err := store.GetStore().GetRegistryDetailsForApp(foundApp.ID)
if err != nil {
currentAppConfigResponse.Error = "failed to get app registry info"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
localRegistry = registryInfo
createNewVersion, err = shouldCreateNewAppVersion(archiveDir, foundApp.GetID(), sequence)
if err != nil {
currentAppConfigResponse.Error = "failed to check new version"
logger.Error(errors.Wrap(err, currentAppConfigResponse.Error))
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
// TODO: set downstreamVersion
}
// get values from saved app version
configValues := map[string]template.ItemValue{}
if kotsKinds.ConfigValues != nil {
for key, value := range kotsKinds.ConfigValues.Spec.Values {
generatedValue := template.ItemValue{
Default: value.Default,
Value: value.Value,
Filename: value.Filename,
RepeatableItem: value.RepeatableItem,
}
configValues[key] = generatedValue
}
}
if createNewVersion {
sequence += 1
}
versionInfo := template.VersionInfoFromInstallationSpec(sequence, app.GetIsAirgap(), kotsKinds.Installation.Spec) // sequence +1 because the sequence will be incremented on save (and we want the preview to be accurate)
appInfo := template.ApplicationInfo{Slug: app.GetSlug()}
renderedConfig, err := kotsconfig.TemplateConfigObjects(nonRenderedConfig, configValues, license, &kotsKinds.KotsApplication, localRegistry, &versionInfo, &appInfo, kotsKinds.IdentityConfig, app.GetNamespace(), false)
if err != nil {
logger.Error(err)
currentAppConfigResponse.Error = "failed to render templates"
JSON(w, http.StatusInternalServerError, currentAppConfigResponse)
return
}
currentAppConfigResponse.ConfigGroups = []kotsv1beta1.ConfigGroup{}
if renderedConfig != nil {
currentAppConfigResponse.ConfigGroups = renderedConfig.Spec.Groups
}
currentAppConfigResponse.Success = true
currentAppConfigResponse.DownstreamVersion = downstreamVersion
JSON(w, http.StatusOK, currentAppConfigResponse)
}
func isVersionConfigEditable(app *apptypes.App, sequence int64) (bool, error) {
// Only latest and currently deployed versions can be edited
downstreams, err := store.GetStore().ListDownstreamsForApp(app.ID)
if err != nil {
return false, errors.Wrap(err, "failed to get downstreams")
}
for _, d := range downstreams {
versions, err := store.GetStore().GetDownstreamVersions(app.ID, d.ClusterID, true)
if err != nil {
return false, errors.Wrap(err, "failed to get downstream versions")
}
if versions.CurrentVersion != nil && versions.CurrentVersion.ParentSequence == sequence {
return true, nil
}
if len(versions.PendingVersions) > 0 && versions.PendingVersions[0].ParentSequence == sequence {
return true, nil
}
for _, v := range versions.PendingVersions {
if v.ParentSequence != sequence {
continue
}
if v.Semver != nil {
return true, nil
}
return false, nil
}
}
return false, nil
}
func shouldCreateNewAppVersion(archiveDir string, appID string, sequence int64) (bool, error) {
// Updates are allowed for any version that does not have base rendered.
if _, err := os.Stat(filepath.Join(archiveDir, "base")); err != nil {
if os.IsNotExist(err) {
return false, nil
} else {
return false, errors.Wrap(err, "failed to stat base dir")
}
}
// If base is rendered, updates are allowed only for sequence 0 and only when it's pending config.
if sequence > 0 {
return true, nil
}
downstreams, err := store.GetStore().ListDownstreamsForApp(appID)
if err != nil {
return false, errors.Wrap(err, "failed to get downstreams")
}
for _, d := range downstreams {
status, err := store.GetStore().GetStatusForVersion(appID, d.ClusterID, sequence)
if err != nil {
return false, errors.Wrap(err, "failed to get version status")
}
if status == storetypes.VersionPendingConfig {
return false, nil
}
}
return true, nil
}
func getAppConfigValueForFile(downloadApp *apptypes.App, sequence int64, filename string, archiveDir string) (string, error) {
err := store.GetStore().GetAppVersionArchive(downloadApp.ID, sequence, archiveDir)
if err != nil {
return "", errors.Wrap(err, "failed to get app version archive")
}
kotsKinds, err := kotsutil.LoadKotsKinds(archiveDir)
if err != nil {
return "", errors.Wrap(err, "failed to load kots kinds from archive")
}
for _, v := range kotsKinds.ConfigValues.Spec.Values {
if v.Filename == filename {
return v.Value, nil
}
}
return "", errors.New("could not find requested file")
}
// if isPrimaryVersion is false, missing a required config field will not cause a failure, and instead will create
// the app version with status needs_config
func updateAppConfig(updateApp *apptypes.App, sequence int64, configGroups []kotsv1beta1.ConfigGroup, createNewVersion bool, isPrimaryVersion bool, skipPreflights bool, deploy bool) (UpdateAppConfigResponse, error) {
updateAppConfigResponse := UpdateAppConfigResponse{
Success: false,
}
archiveDir, err := os.MkdirTemp("", "kotsadm")
if err != nil {
updateAppConfigResponse.Error = "failed to create temp dir"
return updateAppConfigResponse, err
}
defer os.RemoveAll(archiveDir)
err = store.GetStore().GetAppVersionArchive(updateApp.ID, sequence, archiveDir)
if err != nil {
updateAppConfigResponse.Error = "failed to get app version archive"
return updateAppConfigResponse, err
}
kotsKinds, err := kotsutil.LoadKotsKinds(archiveDir)
if err != nil {
updateAppConfigResponse.Error = "failed to load kots kinds from path"
return updateAppConfigResponse, err
}
requiredItems, requiredItemsTitles := getMissingRequiredConfig(configGroups)
// not having all the required items is only a failure for the version that the user intended to edit
if len(requiredItems) > 0 && isPrimaryVersion {
updateAppConfigResponse.RequiredItems = requiredItems
updateAppConfigResponse.Error = fmt.Sprintf("The following fields are required: %s", strings.Join(requiredItemsTitles, ", "))
return updateAppConfigResponse, nil
}
// we don't merge, this is a wholesale replacement of the config values
// so we don't need the complex logic in kots, we can just write
if kotsKinds.ConfigValues != nil {
values := kotsKinds.ConfigValues.Spec.Values
kotsKinds.ConfigValues.Spec.Values = updateAppConfigValues(values, configGroups)
configValuesSpec, err := kotsKinds.Marshal("kots.io", "v1beta1", "ConfigValues")
if err != nil {
updateAppConfigResponse.Error = "failed to marshal config values spec"
return updateAppConfigResponse, err
}
if err := os.WriteFile(filepath.Join(archiveDir, "upstream", "userdata", "config.yaml"), []byte(configValuesSpec), 0644); err != nil {
updateAppConfigResponse.Error = "failed to write config.yaml to upstream/userdata"
return updateAppConfigResponse, err
}
}
registrySettings, err := store.GetStore().GetRegistryDetailsForApp(updateApp.ID)
if err != nil {
updateAppConfigResponse.Error = "failed to get registry settings"
return updateAppConfigResponse, err
}
app, err := store.GetStore().GetApp(updateApp.ID)
if err != nil {
updateAppConfigResponse.Error = "failed to get app"
return updateAppConfigResponse, err
}
latestSequence, err := store.GetStore().GetLatestAppSequence(app.ID, true)
if err != nil {
updateAppConfigResponse.Error = "failed to get latest app sequence"
return updateAppConfigResponse, err
}
if latestSequence != sequence {
// We are modifying an old version, registry settings may not match what the user has set
// for the app. Midstream in version archive is the only place we can get them from.
versionRegistrySettings, err := midstream.LoadPrivateRegistryInfo(archiveDir)
if err != nil {
updateAppConfigResponse.Error = "failed to get version registry settings"
return updateAppConfigResponse, err
}
if versionRegistrySettings == nil {
registrySettings = registrytypes.RegistrySettings{}
} else {
// TODO: missing namespace
registrySettings.Hostname = versionRegistrySettings.Hostname
registrySettings.Username = versionRegistrySettings.Username
registrySettings.Password = versionRegistrySettings.Password
}
}
downstreams, err := store.GetStore().ListDownstreamsForApp(updateApp.ID)
if err != nil {
updateAppConfigResponse.Error = "failed to list downstreams for app"
return updateAppConfigResponse, err
}
renderSequence := sequence
if createNewVersion {
nextAppSequence, err := store.GetStore().GetNextAppSequence(updateApp.ID)
if err != nil {
updateAppConfigResponse.Error = "failed to get next app sequence"
return updateAppConfigResponse, err
}
renderSequence = nextAppSequence
}
err = render.RenderDir(archiveDir, app, downstreams, registrySettings, renderSequence)
if err != nil {
cause := errors.Cause(err)
if _, ok := cause.(util.ActionableError); ok {
updateAppConfigResponse.Error = cause.Error()
} else {
updateAppConfigResponse.Error = "failed to render archive directory"
}
return updateAppConfigResponse, err
}
if createNewVersion {
newSequence, err := store.GetStore().CreateAppVersion(updateApp.ID, &sequence, archiveDir, "Config Change", skipPreflights, &version.DownstreamGitOps{}, render.Renderer{})
if err != nil {
updateAppConfigResponse.Error = "failed to create an app version"
return updateAppConfigResponse, err
}
sequence = newSequence
} else {
source, err := store.GetStore().GetDownstreamVersionSource(updateApp.ID, sequence)
if err != nil {
updateAppConfigResponse.Error = "failed to get existing downstream version source"
return updateAppConfigResponse, err
}
if err := store.GetStore().UpdateAppVersion(updateApp.ID, sequence, nil, archiveDir, source, skipPreflights, &version.DownstreamGitOps{}, render.Renderer{}); err != nil {
updateAppConfigResponse.Error = "failed to update app version"
return updateAppConfigResponse, err
}
}
if err := store.GetStore().SetDownstreamVersionStatus(updateApp.ID, int64(sequence), storetypes.VersionPendingPreflight, ""); err != nil {
updateAppConfigResponse.Error = "failed to set downstream status to 'pending preflight'"
return updateAppConfigResponse, err
}
hasStrictPreflights, err := store.GetStore().HasStrictPreflights(updateApp.ID, sequence)
if err != nil {
updateAppConfigResponse.Error = "failed to check if version has strict preflights"
return updateAppConfigResponse, err
}
if hasStrictPreflights && skipPreflights {
logger.Warnf("preflights will not be skipped, strict preflights are set to %t", hasStrictPreflights)
}
if !skipPreflights || hasStrictPreflights {
if err := preflight.Run(updateApp.ID, updateApp.Slug, int64(sequence), updateApp.IsAirgap, archiveDir); err != nil {
updateAppConfigResponse.Error = errors.Cause(err).Error()
return updateAppConfigResponse, err
}
}
if deploy {
err := version.DeployVersion(updateApp.ID, sequence)
if err != nil {
updateAppConfigResponse.Error = "failed to deploy"
return updateAppConfigResponse, err
}
}
updateAppConfigResponse.Success = true
return updateAppConfigResponse, nil
}
func getMissingRequiredConfig(configGroups []kotsv1beta1.ConfigGroup) ([]string, []string) {
requiredItems := make([]string, 0, 0)
requiredItemsTitles := make([]string, 0, 0)
for _, group := range configGroups {
if group.When == "false" {
continue
}
for _, item := range group.Items {
if kotsadmconfig.IsRequiredItem(item) && kotsadmconfig.IsUnsetItem(item) {
requiredItems = append(requiredItems, item.Name)
if item.Title != "" {
requiredItemsTitles = append(requiredItemsTitles, item.Title)
} else {
requiredItemsTitles = append(requiredItemsTitles, item.Name)
}
}
}
}
return requiredItems, requiredItemsTitles
}
func updateAppConfigValues(values map[string]kotsv1beta1.ConfigValue, configGroups []kotsv1beta1.ConfigGroup) map[string]kotsv1beta1.ConfigValue {
for _, group := range configGroups {
for _, item := range group.Items {
if item.Type == "file" {
v := values[item.Name]
v.Filename = item.Filename
values[item.Name] = v
}
if item.Value.Type == multitype.Bool {
updatedValue := item.Value.BoolVal
v := values[item.Name]
v.Value = strconv.FormatBool(updatedValue)
values[item.Name] = v
} else if item.Value.Type == multitype.String {
updatedValue := item.Value.String()
if item.Type == "password" && !util.IsHelmManaged() { // no encryption in helm mode
// encrypt using the key
// if the decryption succeeds, don't encrypt again
_, err := util.DecryptConfigValue(updatedValue)