-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathotomi-stack.ts
More file actions
3061 lines (2648 loc) · 108 KB
/
Copy pathotomi-stack.ts
File metadata and controls
3061 lines (2648 loc) · 108 KB
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
import { CoreV1Api, User as k8sUser, KubeConfig, V1ObjectReference } from '@kubernetes/client-node'
import Debug from 'debug'
import { getRegions, ObjectStorageKeyRegions, Region, ResourcePage } from '@linode/api-v4'
import { existsSync, rmSync } from 'fs'
import { readFile } from 'fs/promises'
import { generate as generatePassword } from 'generate-password'
import { cloneDeep, filter, isEmpty, map, merge, omit, pick, set, unset } from 'lodash'
import { getAppList, getAppSchema } from 'src/app'
import { APL_SECRETS_NAMESPACE, APL_USERS_NAMESPACE, PLATFORM_SECRETS_NAME } from 'src/constants'
import {
AlreadyExists,
BadRequestError,
ForbiddenError,
HttpError,
NotExistError,
OtomiError,
PublicUrlExists,
ValidationError,
} from 'src/error'
import { getSettingsFileMaps } from 'src/fileStore/file-map'
import { FileStore } from 'src/fileStore/file-store'
import getRepo, { getWorktreeRepo, Git } from 'src/git'
import { cleanSession, getSessionStack } from 'src/middleware'
import {
AplAgentRequest,
AplAgentResponse,
AplAIModelResponse,
AplBuildRequest,
AplBuildResponse,
AplCatalogChartResponse,
AplCatalogRequest,
AplCatalogResponse,
AplCodeRepoRequest,
AplCodeRepoResponse,
AplKind,
AplKnowledgeBaseRequest,
AplKnowledgeBaseResponse,
AplNetpolRequest,
AplNetpolResponse,
AplObject,
AplPlatformObject,
AplPolicyRequest,
AplPolicyResponse,
AplRecord,
AplServiceRequest,
AplServiceResponse,
AplTeamObject,
AplTeamSettingsRequest,
AplTeamSettingsResponse,
AplWorkloadRequest,
AplWorkloadResponse,
App,
Build,
buildPlatformObject,
buildTeamObject,
Cloudtty,
CodeRepo,
Core,
DeepPartial,
K8sService,
Netpol,
ObjWizard,
Policies,
Policy,
SealedSecret,
SealedSecretManifestRequest,
SealedSecretManifestResponse,
Service,
ServiceSpec,
Session,
SessionUser,
Settings,
SettingsInfo,
Team,
TeamSelfService,
TestRepoConnect,
toPlatformObject,
toTeamObject,
User,
Workload,
WorkloadName,
WorkloadValues,
} from 'src/otomi-models'
import {
arrayToObject,
getSanitizedErrorMessage,
getServiceUrl,
getValuesSchema,
removeBlankAttributes,
} from 'src/utils'
import { deepQuote } from 'src/utils/yamlUtils'
import {
API_NAMESPACE,
CATALOG_CACHE_PATH,
cleanEnv,
CUSTOM_ROOT_CA,
DEFAULT_PLATFORM_ADMIN_EMAIL,
EDITOR_INACTIVITY_TIMEOUT,
GIT_BRANCH,
GIT_EMAIL,
GIT_INIT_MAX_RETRIES,
GIT_INIT_RETRY_INTERVAL_MS,
GIT_LOCAL_PATH,
GIT_PASSWORD,
GIT_REPO_URL,
GIT_USER,
HELM_CHART_CATALOG,
HIDDEN_APPS,
KNOWLEDGE_BASE_KIND,
OBJ_STORAGE_APPS,
OBJECT_STORAGE_UI_EXCLUSIONS,
PREINSTALLED_EXCLUDED_APPS,
VERSIONS,
} from 'src/validators'
import { v4 as uuidv4 } from 'uuid'
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
import { getAIModels } from './ai/aiModelHandler'
import { DatabaseCR } from './ai/DatabaseCR'
import { getResourceFilePath } from './fileStore/file-map'
import {
checkPodExists,
getCloudttyActiveTime,
getKubernetesVersion,
getSecretValues,
getTeamSecretsFromK8s,
isK8sReachable,
mergeCanaryServices,
setApiStatusInConfigMap,
toK8sService,
watchPodUntilRunning,
} from './k8s-operations'
import CloudTty from './tty'
import {
getGiteaRepoUrls,
getPrivateRepoBranches,
getPublicRepoBranches,
normalizeRepoUrl,
testPrivateRepoConnect,
testPublicRepoConnect,
} from './utils/codeRepoUtils'
import { isKnativeSupported } from './utils/k8sUtils'
import { getAplObjectFromV1, getV1MergeObject, getV1ObjectFromApl } from './utils/manifests'
import {
createPlatformSealedSecretManifest,
createUserSealedSecret,
encryptAndMergeSecrets,
ensureEncryptedData,
ensureSealedSecretMetadata,
extractSecretPaths,
extractSettingsSecrets,
filterChangedSecrets,
getSealedSecretsPEM,
removeSettingsSecrets,
sealedSecretManifest,
} from './utils/sealedSecretUtils'
import {
getKeycloakUsers,
getUserSecretData,
isValidUsername,
listUserSecretData,
userSecretDataToUser,
} from './utils/userUtils'
import { defineClusterId, ObjectStorageClient } from './utils/wizardUtils'
import { fetchWorkloadCatalog, isInteralGiteaURL, validateGitUrl } from './utils/workloadUtils'
interface ExcludedApp extends App {
managed: boolean
}
const debug = Debug('otomi:otomi-stack')
const env = cleanEnv({
API_NAMESPACE,
CATALOG_CACHE_PATH,
CUSTOM_ROOT_CA,
DEFAULT_PLATFORM_ADMIN_EMAIL,
EDITOR_INACTIVITY_TIMEOUT,
GIT_BRANCH,
GIT_EMAIL,
GIT_INIT_MAX_RETRIES,
GIT_INIT_RETRY_INTERVAL_MS,
GIT_LOCAL_PATH,
GIT_PASSWORD,
GIT_REPO_URL,
GIT_USER,
HELM_CHART_CATALOG,
VERSIONS,
PREINSTALLED_EXCLUDED_APPS,
HIDDEN_APPS,
OBJ_STORAGE_APPS,
KNOWLEDGE_BASE_KIND,
OBJECT_STORAGE_UI_EXCLUSIONS,
})
export const rootPath = '/tmp/otomi/values'
const clusterSettingsFilePath = 'env/settings/cluster.yaml'
function getTeamSealedSecretsValuesFilePath(teamId: string, sealedSecretsName: string): string {
return `env/teams/${teamId}/sealedsecrets/${sealedSecretsName}.yaml`
}
function getNamespaceSealedSecretsValuesFilePath(namespace: string, sealedSecretsName: string): string {
return `env/manifests/namespaces/${namespace}/sealedsecrets/${sealedSecretsName}.yaml`
}
function getTeamWorkloadValuesManagedFilePath(teamId: string, workloadName: string): string {
return `env/teams/${teamId}/workloadValues/${workloadName}.managed.yaml`
}
function getTeamWorkloadValuesFilePath(teamId: string, workloadName: string): string {
return `env/teams/${teamId}/workloadValues/${workloadName}.yaml`
}
function getTeamKnowledgeBaseValuesFilePath(teamId: string, knowledgeBaseName: string): string {
return `env/teams/${teamId}/knowledgebases/${knowledgeBaseName}`
}
function getTeamDatabaseValuesFilePath(teamId: string, databaseName: string): string {
return `env/teams/${teamId}/databases/${databaseName}`
}
function buildUpdatedOtomiSettings(
otomi: Settings['otomi'],
params: { repoUrl: string; username?: string; password: string; email: string; branch: string },
): Record<string, any> {
const { repoUrl, username, password, email, branch } = params
return {
...otomi,
git: {
...(otomi?.git ?? {}),
repoUrl,
email,
branch,
...(username !== undefined && { username }),
password,
},
}
}
export default class OtomiStack {
private coreValues: Core
editor?: string
sessionId?: string
isLoaded = false
public locked = false
git: Git
fileStore: FileStore
private cloudTty: CloudTty
constructor(editor?: string, sessionId?: string) {
this.editor = editor
this.sessionId = sessionId ?? 'main'
}
getApiStatus(): { locked: boolean } {
return { locked: this.locked }
}
setLocked(value: boolean): void {
this.locked = value
}
getCloudTty() {
if (!this.cloudTty) {
this.cloudTty = new CloudTty()
}
return this.cloudTty
}
async getAppList() {
return getAppList()
}
getRepoPath() {
if (env.isTest || this.sessionId === undefined) return env.GIT_LOCAL_PATH
return `${rootPath}/${this.sessionId}`
}
async init(): Promise<void> {
if (env.isProd) {
const corePath = '/etc/otomi/core.yaml'
this.coreValues = parseYaml(await readFile(corePath, 'utf8')) as Core
} else {
this.coreValues = {
...parseYaml(await readFile('./test/core.yaml', 'utf8')),
...parseYaml(await readFile('./test/apps.yaml', 'utf8')),
}
}
}
async initRepo(existingStore?: FileStore): Promise<void> {
if (existingStore) {
this.fileStore = existingStore
return
}
// Load all files into the in-memory store
this.fileStore = await FileStore.load(this.getRepoPath())
}
async initGit(inflateValues = true): Promise<void> {
await this.init()
// every editor gets their own folder to detect conflicts upon deploy
const path = this.getRepoPath()
const branch = env.GIT_BRANCH
const url = env.GIT_REPO_URL
const maxRetries = env.GIT_INIT_MAX_RETRIES
const timeoutMs = env.GIT_INIT_RETRY_INTERVAL_MS
let attempt = 0
for (;;) {
try {
this.git = await getRepo(path, url, env.GIT_USER, env.GIT_EMAIL, env.GIT_PASSWORD, branch)
await this.git.pull()
//TODO fetch this url from the repo
if (await this.git.fileExists(clusterSettingsFilePath)) break
debug(`Values are not present at ${url}:${branch}`)
} catch (e) {
// Remove password from error message
const errorMessage = getSanitizedErrorMessage(e)
debug(`Error while initializing git repository: ${errorMessage}`)
debug(`Git repository is not ready: ${url}:${branch}`)
}
attempt++
if (attempt >= maxRetries) {
console.error(`Git repository could not be initialized after ${maxRetries} attempts, exiting`)
process.exit(1)
}
debug(`Trying again in ${timeoutMs} ms (attempt ${attempt}/${maxRetries})`)
await new Promise((resolve) => setTimeout(resolve, timeoutMs))
}
if (inflateValues) {
await this.loadValues()
await this.unlockApi()
}
debug(`Values are loaded for ${this.editor} in ${this.sessionId}`)
}
async initGitWorktree(mainRepo: Git): Promise<void> {
await this.init()
debug(`Creating worktree for session ${this.sessionId}`)
try {
await mainRepo.git.revparse(`--verify refs/heads/${env.GIT_BRANCH}`)
} catch (error) {
const errorMessage = getSanitizedErrorMessage(error)
throw new Error(
`Main repository does not have branch '${env.GIT_BRANCH}'. Cannot create worktree. ${errorMessage}`,
)
}
// Pull latest changes so the worktree starts from up-to-date state
try {
debug(`Pulled latest changes before creating worktree for session ${this.sessionId}`)
await mainRepo.pull(true, true)
} catch (e) {
debug(`Warning: could not pull latest before creating worktree: ${getSanitizedErrorMessage(e)}`)
}
const worktreePath = this.getRepoPath()
this.git = await getWorktreeRepo(mainRepo, worktreePath, env.GIT_BRANCH)
this.fileStore = new FileStore()
debug(`Worktree created for ${this.editor} in ${this.sessionId}`)
}
async getSettingsInfo(): Promise<SettingsInfo> {
const settings = await this.getSettings(['cluster', 'dns', 'otomi', 'smtp', 'ingress'])
const otomiInfo = pick(settings.otomi, [
'hasExternalDNS',
'hasExternalIDP',
'isPreInstalled',
'aiEnabled',
'git.repoUrl',
'git.branch',
])
if (otomiInfo.git?.repoUrl?.includes('gitea-http.gitea.svc.cluster.local')) {
otomiInfo.git.repoUrl = `https://gitea.${settings.cluster?.domainSuffix}/otomi/values`
}
return {
cluster: pick(settings.cluster, ['name', 'domainSuffix', 'apiServer', 'provider', 'linode']),
dns: pick(settings.dns, ['zones']),
otomi: otomiInfo,
ingressClassNames: map(settings.ingress?.classes, 'className') ?? [],
} as SettingsInfo
}
async createObjWizard(data: ObjWizard): Promise<ObjWizard> {
const { obj } = await this.getSettings(['obj'])
const settingsdata = { obj: { ...obj, showWizard: data.showWizard } }
const createdBuckets = [] as Array<string>
if (data?.apiToken && data?.regionId) {
const { cluster } = await this.getSettings(['cluster'])
let lkeClusterId: undefined | string = defineClusterId(cluster?.name)
if (lkeClusterId === undefined) {
return { status: 'error', errorMessage: 'Cluster name is not found.' }
}
const bucketNames = {
cnpg: `lke${lkeClusterId}-cnpg`,
harbor: `lke${lkeClusterId}-harbor`,
loki: `lke${lkeClusterId}-loki`,
gitea: `lke${lkeClusterId}-gitea`,
'kubeflow-pipelines': `lke${lkeClusterId}-kubeflow-pipelines`,
}
const objectStorageClient = new ObjectStorageClient(data.apiToken)
// Create object storage buckets
for (const bucket in bucketNames) {
const bucketLabel = await objectStorageClient.createObjectStorageBucket(
bucketNames[bucket] as string,
data.regionId,
)
if (bucketLabel instanceof OtomiError) {
return {
objBuckets: createdBuckets,
status: 'error',
errorMessage: bucketLabel.publicMessage,
}
} else {
createdBuckets.push(bucketLabel)
debug(`${bucketLabel} bucket is created.`)
}
}
// Create object storage keys
const objStorageKey = await objectStorageClient.createObjectStorageKey(
lkeClusterId,
data.regionId,
Object.values(bucketNames),
)
if (objStorageKey instanceof OtomiError) return { status: 'error', errorMessage: objStorageKey.publicMessage }
const { access_key, secret_key, regions } = objStorageKey
// The data.regionId (for example 'eu-central') does not include the zone.
// However, we need to add the region with the zone suffix (for example 'eu-central-1') in the object storage values.
// Therefore, we need to extract the region with the zone suffix from the s3_endpoint.
const { s3_endpoint } = regions.find((region) => region.id === data.regionId) as ObjectStorageKeyRegions
const [objStorageRegion] = s3_endpoint.split('.')
debug(`Object Storage keys are created.`)
// Modify object storage settings
settingsdata.obj = {
showWizard: false,
provider: {
type: 'linode',
linode: {
accessKeyId: access_key,
buckets: bucketNames,
region: objStorageRegion,
secretAccessKey: secret_key,
},
},
}
}
await this.editSettings(settingsdata as Settings, 'obj')
debug('Object storage settings have been configured.')
return {
status: 'success',
regionId: data.regionId,
objBuckets: createdBuckets,
} as ObjWizard
}
async getSettings(keys?: string[]): Promise<Settings> {
const settings: Settings = {}
const settingsFileMaps = getSettingsFileMaps(this.getRepoPath())
// Early return: if specific keys requested, only fetch those
if (keys && keys.length > 0) {
keys.forEach((key) => {
const fileMap = settingsFileMaps.get(key)
if (!fileMap) return // Skip unknown keys
const files = this.fileStore.getPlatformResourcesByKind(fileMap.kind)
for (const [, content] of files) {
settings[key] = content?.spec || content
}
})
// Apply otomi nodeSelector transformation if needed
if (keys.includes('otomi')) {
this.transformOtomiNodeSelector(settings)
}
} else {
// No keys specified: fetch all settings
for (const [name, fileMap] of settingsFileMaps.entries()) {
const files = this.fileStore.getPlatformResourcesByKind(fileMap.kind)
for (const [, content] of files) {
settings[name] = content?.spec || content
}
}
// Apply otomi nodeSelector transformation
this.transformOtomiNodeSelector(settings)
}
await this.mergeEncryptedSecretsIntoSettings(settings, keys, settingsFileMaps)
return settings
}
private async mergeEncryptedSecretsIntoSettings(
settings: Settings,
keys: string[] | undefined,
settingsFileMaps: Map<string, any>,
): Promise<void> {
const valuesSchema = await getValuesSchema()
const settingKeys = keys && keys.length > 0 ? keys : Array.from(settingsFileMaps.keys())
for (const settingId of settingKeys) {
if (!settings[settingId]) continue
const subSchema = valuesSchema.properties?.[settingId]
if (!subSchema) continue
const secretPaths = extractSecretPaths(subSchema)
if (secretPaths.length === 0) continue
const sealedSecretName = `${settingId}-secrets`
const manifest = this.fileStore.getNamespaceResource(
'AplNamespaceSealedSecret',
sealedSecretName,
APL_SECRETS_NAMESPACE,
)
if (!manifest) continue
const encryptedData = (manifest as SealedSecretManifestResponse).spec?.encryptedData || {}
for (const dotPath of secretPaths) {
const underscoreKey = dotPath.replace(/\./g, '_')
if (underscoreKey in encryptedData) {
set(settings[settingId] as Record<string, any>, dotPath, encryptedData[underscoreKey])
}
}
}
}
/**
* Extracts secrets from settings data, encrypts changed values,
* merges with existing sealed secret, and saves the result.
*/
private async extractAndStoreSettingsSecrets(
settingId: string,
updatedSettingsData: Record<string, any>,
): Promise<AplRecord | undefined> {
const valuesSchema = await getValuesSchema()
const subSchema = valuesSchema.properties?.[settingId]
if (!subSchema) return undefined
const secretPaths = extractSecretPaths(subSchema)
const newSecrets = extractSettingsSecrets(secretPaths, updatedSettingsData[settingId])
if (Object.keys(newSecrets).length === 0) return undefined
const sealedSecretName = `${settingId}-secrets`
const sealedSecretPath = getNamespaceSealedSecretsValuesFilePath(APL_SECRETS_NAMESPACE, sealedSecretName)
const existingManifest = await this.git.readFile(sealedSecretPath)
const existingEncryptedData: Record<string, string> =
(existingManifest?.spec?.encryptedData as Record<string, string>) || {}
const changedSecrets = filterChangedSecrets(newSecrets, existingEncryptedData)
const mergedEncryptedData = await encryptAndMergeSecrets(
sealedSecretName,
APL_SECRETS_NAMESPACE,
changedSecrets,
existingEncryptedData,
)
return this.saveNamespaceSealedSecret(APL_SECRETS_NAMESPACE, {
kind: 'SealedSecret',
metadata: { name: sealedSecretName },
spec: {
encryptedData: mergedEncryptedData,
template: {
type: 'kubernetes.io/opaque',
immutable: false,
metadata: { name: sealedSecretName, namespace: APL_SECRETS_NAMESPACE },
},
},
})
}
private transformOtomiNodeSelector(settings: Settings): void {
const nodeSelector = settings.otomi?.nodeSelector
if (!Array.isArray(nodeSelector)) {
const nodeSelectorArray = Object.entries(nodeSelector || {}).map(([name, value]) => ({
name,
value,
}))
set(settings, 'otomi.nodeSelector', nodeSelectorArray)
}
}
async editSettings(data: Settings, settingId: string): Promise<Settings> {
const settings = await this.getSettings()
const updatedSettingsData: any = { ...data }
if (settingId === 'otomi') {
// convert otomi.nodeSelector to object
if (Array.isArray(updatedSettingsData.otomi?.nodeSelector)) {
const nodeSelectorArray = updatedSettingsData.otomi.nodeSelector
const nodeSelectorObject = nodeSelectorArray.reduce((acc, { name, value }) => {
return { ...acc, [name]: value }
}, {})
updatedSettingsData.otomi.nodeSelector = nodeSelectorObject
}
}
const sealedSecretRecord = await this.extractAndStoreSettingsSecrets(settingId, updatedSettingsData)
// Strip secrets from settings before disk storage
const valuesSchema = await getValuesSchema()
const subSchema = valuesSchema.properties?.[settingId]
if (subSchema) {
const secretPaths = extractSecretPaths(subSchema)
const diskData = cloneDeep(updatedSettingsData[settingId])
removeSettingsSecrets(secretPaths, diskData)
settings[settingId] = removeBlankAttributes(diskData as Record<string, any>)
} else {
settings[settingId] = removeBlankAttributes(updatedSettingsData[settingId] as Record<string, any>)
}
const settingKindMap = getSettingsFileMaps(this.getRepoPath())
const kind = settingKindMap.get(settingId)
if (!kind) {
throw new Error(`Unknown settingId ${settingId}`)
}
const filePath = getResourceFilePath(kind.kind, settingId)
const spec = settings[settingId]
const aplObject = toPlatformObject(kind.kind, settingId, spec)
this.fileStore.set(filePath, aplObject)
await this.saveSettings()
const aplRecords: AplRecord[] = [{ filePath, content: aplObject }]
if (sealedSecretRecord) aplRecords.push(sealedSecretRecord)
await this.doDeployments(aplRecords)
// Return settings with secret values from the incoming data
settings[settingId] = removeBlankAttributes(updatedSettingsData[settingId] as Record<string, any>)
return settings
}
async migrateGitSettings(params: {
repoUrl: string
username?: string
password: string
email: string
branch: string
remoteHasContent: boolean
}): Promise<void> {
const { otomi } = await this.getSettings()
const updatedOtomi = buildUpdatedOtomiSettings(otomi, params)
// Encrypt the password into the otomi-secrets SealedSecret and strip it from the settings YAML
const sealedSecretRecord = await this.extractAndStoreSettingsSecrets('otomi', { otomi: updatedOtomi })
const valuesSchema = await getValuesSchema()
const subSchema = valuesSchema.properties?.otomi
if (subSchema) {
removeSettingsSecrets(extractSecretPaths(subSchema), updatedOtomi)
}
const { filePath, aplObject } = await this.persistOtomiSettings(updatedOtomi)
await this.commitAndPushMigration({ ...params, filePath, aplObject, sealedSecretRecord })
}
private async persistOtomiSettings(
updatedOtomi: Record<string, any>,
): Promise<{ filePath: string; aplObject: AplObject }> {
const filePath = getResourceFilePath('AplCapabilitySet', 'otomi')
const aplObject = toPlatformObject('AplCapabilitySet', 'otomi', updatedOtomi)
this.fileStore.set(filePath, aplObject)
await this.saveSettings()
return { filePath, aplObject }
}
private async commitAndPushMigration(params: {
repoUrl: string
branch: string
password: string
username?: string
remoteHasContent: boolean
filePath: string
aplObject: AplObject
sealedSecretRecord?: AplRecord
}): Promise<void> {
const { repoUrl, branch, password, username, remoteHasContent, filePath, aplObject, sealedSecretRecord } = params
const rootStack = await getSessionStack()
try {
await this.git.commit(this.editor!)
if (!remoteHasContent) {
// Remote is empty: push so the new remote has the config pointing to itself
await this.git.pushToNewRemote(repoUrl, branch, password, username)
}
// Push to current remote so the operator picks up the git config change
await this.git.pushWithRetry()
await rootStack.git.git.pull()
rootStack.fileStore.set(filePath, aplObject)
if (sealedSecretRecord) {
rootStack.fileStore.set(sealedSecretRecord.filePath, sealedSecretRecord.content)
}
debug(`Updated root stack values with ${this.sessionId} migration changes`)
} catch (e) {
e.message = getSanitizedErrorMessage(e)
throw e
} finally {
await cleanSession(this.sessionId!)
}
}
async filterExcludedApp(apps: App | App[], k8sVersion?: string) {
const preInstalledExcludedApps = env.PREINSTALLED_EXCLUDED_APPS.apps
const hiddenApps = env.HIDDEN_APPS.apps
const excludedApps = preInstalledExcludedApps.concat(hiddenApps)
const settingsInfo = await this.getSettingsInfo()
if (!Array.isArray(apps)) {
if (k8sVersion && !isKnativeSupported(k8sVersion) && apps.id === 'knative') {
// eslint-disable-next-line no-param-reassign
;(apps as ExcludedApp).managed = true
return apps as ExcludedApp
}
if (settingsInfo.otomi && settingsInfo.otomi.isPreInstalled && excludedApps.includes(apps.id)) {
// eslint-disable-next-line no-param-reassign
;(apps as ExcludedApp).managed = true
return apps as ExcludedApp
}
} else if (Array.isArray(apps)) {
let filtered = k8sVersion && !isKnativeSupported(k8sVersion) ? apps.filter((app) => app.id !== 'knative') : apps
if (settingsInfo.otomi && settingsInfo.otomi.isPreInstalled) {
return filtered.filter((app) => !excludedApps.includes(app.id))
} else {
return filtered
}
}
return apps
}
async getTeamApp(teamId: string, id: string): Promise<App | ExcludedApp> {
const k8sVersion = (await getKubernetesVersion()) as string | undefined
const app = this.getApp(id)
this.filterExcludedApp(app, k8sVersion)
if (teamId === 'admin') return app
return { id: app.id, enabled: app.enabled }
}
getApp(name: string): App {
const filePath = getResourceFilePath('AplApp', name)
const content = this.fileStore.get(filePath)
if (!content) {
throw new Error(`App ${name} not found`)
}
return { values: content.spec, id: content.metadata.name } as App
}
async getApps(): Promise<Array<App>> {
const appList = await this.getAppList()
const k8sVersion = (await getKubernetesVersion()) as string | undefined
const allApps = appList.map((id) => {
return this.getApp(id)
})
const providerSpecificApps = (await this.filterExcludedApp(allApps, k8sVersion)) as App[]
return providerSpecificApps.map((app) => {
return {
id: app.id,
enabled: Boolean(app.values?.enabled ?? true),
}
})
}
async getTeamApps(teamId: string): Promise<Array<App>> {
const allApps = await this.getApps()
if (teamId === 'admin') return allApps
const core = this.getCore()
const teamApps = allApps
.map((app: App) => {
const isShared = !!core.adminApps.find((a) => a.name === app.id)?.isShared
const inTeamApps = !!core.teamApps.find((a) => a.name === app.id)
if (isShared || inTeamApps) return app
})
.filter((app): app is App => app !== undefined)
return teamApps.map((app) => {
return {
id: app.id,
enabled: app.enabled ?? true,
}
})
}
async editApp(teamId: string, id: string, data: App): Promise<App> {
let app: App = this.getApp(id)
// Only merge editable data sections
const updatedValues = {
enabled: !!data.values?.enabled,
values: omit(data.values, ['enabled', '_rawValues']),
rawValues: (data.values?._rawValues as Record<string, any>) || undefined,
}
app = { ...app, ...updatedValues }
const filePath = getResourceFilePath('AplApp', id)
const aplApp = toPlatformObject('AplApp', id, { enabled: app.enabled, _rawValues: app.rawValues, ...app.values })
this.fileStore.set(filePath, aplApp)
await this.saveAdminApp(app)
await this.doDeployment({ filePath, content: aplApp })
return this.getApp(id)
}
canToggleApp(id: string): boolean {
const app = getAppSchema(id)
return app.properties!.enabled !== undefined
}
async toggleApps(teamId: string, ids: string[], enabled: boolean): Promise<void> {
const aplRecords = (
await Promise.all(
ids.map(async (id) => {
const orig = this.getApp(id)
if (orig && this.canToggleApp(id)) {
const filePath = getResourceFilePath('AplApp', id)
const aplApp = this.fileStore.get(filePath)
if (!aplApp) {
throw new NotExistError(`App ${id} not found`)
}
set(aplApp, 'spec.enabled', enabled)
await this.saveAppToggle(aplApp)
return { filePath, content: aplApp } as AplRecord
}
return undefined
}),
)
).filter((record): record is AplRecord => record !== undefined)
if (aplRecords.length === 0) {
throw new Error(`Failed toggling apps ${ids.toString()}`)
}
await this.doDeployments(aplRecords)
}
getTeams(): Array<Team> {
const teams: Team[] = []
const teamIds = this.fileStore.getTeamIds()
for (const teamId of teamIds) {
const settingsFiles = this.fileStore.getTeamResourcesByKindAndTeamId('AplTeamSettingSet', teamId)
for (const [, content] of settingsFiles) {
// v1 format: return spec directly
const team = getV1ObjectFromApl(content as AplTeamSettingsResponse) as Team
if (team) {
team.name = team.name || teamId
teams.push(team as Team)
}
}
}
return teams
}
getTeamIds(): string[] {
return this.fileStore.getTeamIds()
}
getAplTeams(): AplTeamSettingsResponse[] {
const teams: AplTeamSettingsResponse[] = []
const teamIds = this.fileStore.getTeamIds()
for (const teamId of teamIds) {
if (teamId === 'admin') continue
const settingsFiles = this.fileStore.getTeamResourcesByKindAndTeamId('AplTeamSettingSet', teamId)
for (const [, content] of settingsFiles) {
if (content) {
// Return full v2 object with password removed
const team = { ...content }
if (team.spec) {
team.spec = { ...team.spec, password: undefined }
}
teams.push(team as AplTeamSettingsResponse)
}
}
}
return teams
}
getTeamSelfServiceFlags(id: string): TeamSelfService {
const data = this.getTeam(id)
return data.selfService
}
getCore(): Core {
return this.coreValues
}
getTeam(name: string): Team {
const settingsResponse = this.fileStore.getTeamResource('AplTeamSettingSet', name, 'settings')
if (!settingsResponse) {
throw new Error(`Team ${name} not found`)
}
const team = getV1ObjectFromApl(settingsResponse as AplTeamSettingsResponse) as Team
team.name = team.name || name
unset(team, 'password') // Remove password from the response
return team
}
getAplTeam(name: string): AplTeamSettingsResponse {
const settingsResponse = this.fileStore.getTeamResource(
'AplTeamSettingSet',
name,
'settings',
) as AplTeamSettingsResponse
if (!settingsResponse) {
throw new Error(`Team ${name} not found`)
}
unset(settingsResponse, 'spec.password') // Remove password from the response
return settingsResponse
}
async createTeam(data: Team): Promise<Team> {
const newTeam = await this.createAplTeam(getAplObjectFromV1('AplTeamSettingSet', data) as AplTeamSettingsRequest)
return getV1ObjectFromApl(newTeam) as Team
}
async createAplTeam(data: AplTeamSettingsRequest): Promise<AplTeamSettingsResponse> {
const teamName = data.metadata.name
if (teamName.length < 3) throw new ValidationError('Team name must be at least 3 characters long')
if (teamName.length > 9) throw new ValidationError('Team name must not exceed 9 characters')
let password = data.spec.password as string
if (isEmpty(password)) {
debug(`creating password for team '${teamName}'`)
password = generatePassword({
length: 16,
numbers: true,
symbols: false,
lowercase: true,
uppercase: true,
strict: true,
})
}
// Encrypt password into a SealedSecret manifest
const sealedSecretName = `team-${teamName}-settings-secrets`
const sealedSecretYaml = await createPlatformSealedSecretManifest(sealedSecretName, APL_SECRETS_NAMESPACE, {
password,
})
const sealedSecretPath = getNamespaceSealedSecretsValuesFilePath(APL_SECRETS_NAMESPACE, sealedSecretName)
await this.git.writeTextFile(sealedSecretPath, sealedSecretYaml)
// Remove password from team spec before saving settings.yaml
// eslint-disable-next-line no-param-reassign
delete data.spec.password
const teamObject = toTeamObject(teamName, data)
const team = await this.saveTeam(teamObject)
await this.doDeployment(team)
return team.content as AplTeamSettingsResponse
}
async editTeam(name: string, data: Team): Promise<Team> {
const mergeObj = getV1MergeObject(data) as DeepPartial<AplTeamSettingsRequest>
const mergedTeam = await this.editAplTeam(name, mergeObj)
return getV1ObjectFromApl(mergedTeam) as Team
}
async editAplTeam(
name: string,
data: AplTeamSettingsRequest | DeepPartial<AplTeamSettingsRequest>,
patch = false,
): Promise<AplTeamSettingsResponse> {
const currentTeam = this.getAplTeam(name)
const updatedSpec = patch ? merge(cloneDeep(currentTeam.spec), data.spec) : { ...currentTeam.spec, ...data.spec }
const teamObject = buildTeamObject(currentTeam, updatedSpec)
const team = await this.saveTeam(teamObject)
await this.doDeployment(team)
return team.content as AplTeamSettingsResponse
}
async deleteTeam(id: string): Promise<void> {
const filePaths = await this.deleteTeamObjects(id)
await this.doDeleteDeployment(filePaths)
}
async saveTeamConfigItem(aplTeamObject: AplTeamObject): Promise<AplRecord> {
debug(
`Saving ${aplTeamObject.kind} ${aplTeamObject.metadata.name} for team ${aplTeamObject.metadata.labels['apl.io/teamId']}`,
)
const filePath = this.fileStore.setTeamResource(aplTeamObject)
await this.git.writeFile(filePath, aplTeamObject)
return { filePath, content: aplTeamObject }
}