-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathotomi-stack.ts
More file actions
2636 lines (2269 loc) · 92.6 KB
/
Copy pathotomi-stack.ts
File metadata and controls
2636 lines (2269 loc) · 92.6 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 } from '@linode/api-v4'
import { existsSync, rmSync } from 'fs'
import { pathExists, unlink } from 'fs-extra'
import { readdir, readFile, writeFile } from 'fs/promises'
import { generate as generatePassword } from 'generate-password'
import { cloneDeep, filter, get, isEmpty, map, merge, omit, pick, set, unset } from 'lodash'
import { getAppList, getAppSchema, getSecretPaths } from 'src/app'
import {
AlreadyExists,
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,
AplCodeRepoRequest,
AplCodeRepoResponse,
AplKind,
AplKnowledgeBaseRequest,
AplKnowledgeBaseResponse,
AplNetpolRequest,
AplNetpolResponse,
AplObject,
AplPlatformObject,
AplPolicyRequest,
AplPolicyResponse,
AplRecord,
AplSecretRequest,
AplSecretResponse,
AplServiceRequest,
AplServiceResponse,
AplTeamObject,
AplTeamSettingsRequest,
AplTeamSettingsResponse,
AplWorkloadRequest,
AplWorkloadResponse,
App,
Build,
buildPlatformObject,
buildTeamObject,
Cloudtty,
CodeRepo,
Core,
DeepPartial,
K8sService,
Netpol,
ObjWizard,
Policies,
Policy,
SealedSecret,
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 {
cleanEnv,
CUSTOM_ROOT_CA,
DEFAULT_PLATFORM_ADMIN_EMAIL,
EDITOR_INACTIVITY_TIMEOUT,
GIT_BRANCH,
GIT_EMAIL,
GIT_LOCAL_PATH,
GIT_PASSWORD,
GIT_REPO_URL,
GIT_USER,
HELM_CHART_CATALOG,
HIDDEN_APPS,
KNOWLEDGE_BASE_KIND,
OBJ_STORAGE_APPS,
PREINSTALLED_EXCLUDED_APPS,
TOOLS_HOST,
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, getSecretFilePath } from './fileStore/file-map'
import {
apply,
checkPodExists,
getCloudttyActiveTime,
getKubernetesVersion,
getSecretValues,
getTeamSecretsFromK8s,
k8sdelete,
watchPodUntilRunning,
} from './k8s_operations'
import {
getGiteaRepoUrls,
getPrivateRepoBranches,
getPublicRepoBranches,
normalizeRepoUrl,
testPrivateRepoConnect,
testPublicRepoConnect,
} from './utils/codeRepoUtils'
import { getAplObjectFromV1, getV1MergeObject, getV1ObjectFromApl } from './utils/manifests'
import { getSealedSecretsPEM, sealedSecretManifest } from './utils/sealedSecretUtils'
import { getKeycloakUsers, isValidUsername } from './utils/userUtils'
import { defineClusterId, ObjectStorageClient } from './utils/wizardUtils'
import {
fetchChartYaml,
fetchWorkloadCatalog,
isInteralGiteaURL,
NewHelmChartValues,
sparseCloneChart,
} from './utils/workloadUtils'
interface ExcludedApp extends App {
managed: boolean
}
const debug = Debug('otomi:otomi-stack')
const env = cleanEnv({
CUSTOM_ROOT_CA,
DEFAULT_PLATFORM_ADMIN_EMAIL,
EDITOR_INACTIVITY_TIMEOUT,
GIT_BRANCH,
GIT_EMAIL,
GIT_LOCAL_PATH,
GIT_PASSWORD,
GIT_REPO_URL,
GIT_USER,
HELM_CHART_CATALOG,
TOOLS_HOST,
VERSIONS,
PREINSTALLED_EXCLUDED_APPS,
HIDDEN_APPS,
OBJ_STORAGE_APPS,
KNOWLEDGE_BASE_KIND,
})
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 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}`
}
export default class OtomiStack {
private coreValues: Core
editor?: string
sessionId?: string
isLoaded = false
git: Git
fileStore: FileStore
constructor(editor?: string, sessionId?: string) {
this.editor = editor
this.sessionId = sessionId ?? 'main'
}
getAppList() {
let apps = getAppList()
apps = apps.filter((item) => item !== 'ingress-nginx')
const { ingress } = this.getSettings()
const allClasses = ['platform'].concat(ingress?.classes?.map((obj) => obj.className as string) || [])
const ingressApps = allClasses.map((name) => `ingress-nginx-${name}`)
return apps.concat(ingressApps)
}
async getValues(query): Promise<Record<string, any>> {
return (await this.git.requestValues(query)).data
}
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
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}`)
}
const timeoutMs = 10000
debug(`Trying again in ${timeoutMs} ms`)
await new Promise((resolve) => setTimeout(resolve, timeoutMs))
}
if (inflateValues) {
await this.loadValues()
}
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}`,
)
}
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}`)
}
getSettingsInfo(): SettingsInfo {
const settings = this.getSettings(['cluster', 'dns', 'otomi', 'smtp', 'ingress'])
return {
cluster: pick(settings.cluster, ['name', 'domainSuffix', 'apiServer', 'provider', 'linode']),
dns: pick(settings.dns, ['zones']),
otomi: pick(settings.otomi, ['hasExternalDNS', 'hasExternalIDP', 'isPreInstalled', 'aiEnabled']),
smtp: pick(settings.smtp, ['smarthost']),
ingressClassNames: map(settings.ingress?.classes, 'className') ?? [],
} as SettingsInfo
}
async createObjWizard(data: ObjWizard): Promise<ObjWizard> {
const { obj } = this.getSettings(['obj'])
const settingsdata = { obj: { ...obj, showWizard: data.showWizard } }
const createdBuckets = [] as Array<string>
if (data?.apiToken && data?.regionId) {
const { cluster } = 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`,
tempo: `lke${lkeClusterId}-tempo`,
gitea: `lke${lkeClusterId}-gitea`,
thanos: `lke${lkeClusterId}-thanos`,
'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
}
getSettings(keys?: string[]): 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)
}
return settings
}
// 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)
return settings
}
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 loadIngressApps(id: string): Promise<void> {
try {
debug(`Loading ingress apps for ${id}`)
const content = await this.git.loadConfig('env/apps/ingress-nginx.yaml', 'env/apps/secrets.ingress-nginx.yaml')
const values = content?.apps?.['ingress-nginx'] ?? {}
const filePath = getResourceFilePath('AplApp', id)
const aplApp = toPlatformObject('AplApp', id, { enabled: true, rawValues: {}, ...values })
this.fileStore.set(filePath, aplApp)
debug(`Ingress app loaded for ${id}`)
} catch (error) {
debug(`Failed to load ingress apps for ${id}:`)
}
}
async removeIngressApps(id: string): Promise<void> {
try {
debug(`Removing ingress apps for ${id}`)
const filePath = `env/apps/${id}.yaml`
const secretsPath = `env/apps/secrets.${id}.yaml`
this.fileStore.delete(filePath)
await this.git.removeFile(filePath)
await this.git.removeFile(secretsPath)
debug(`Ingress app removed for ${id}`)
} catch (error) {
debug(`Failed to remove ingress app for ${id}:`)
}
}
async editIngressApps(settings: Settings, data: Settings, settingId: string): Promise<void> {
if (settingId !== 'ingress') return
const initClasses = settings[settingId]?.classes || []
const initClassNames = initClasses.map((obj) => obj.className)
const dataClasses = data[settingId]?.classes || []
const dataClassNames = dataClasses.map((obj) => obj.className)
// Ingress app addition
for (const ingressClass of dataClasses) {
if (!initClassNames.includes(ingressClass.className)) {
const id = `ingress-nginx-${ingressClass.className}`
await this.loadIngressApps(id)
}
}
// Ingress app deletion
for (const ingressClass of initClasses) {
if (!dataClassNames.includes(ingressClass.className)) {
const id = `ingress-nginx-${ingressClass.className}`
await this.removeIngressApps(id)
}
}
}
async editSettings(data: Settings, settingId: string): Promise<Settings> {
const settings = this.getSettings()
await this.editIngressApps(settings, data, settingId)
const updatedSettingsData: any = { ...data }
// Preserve the otomi.adminPassword when editing otomi settings
if (settingId === 'otomi') {
updatedSettingsData.otomi = {
...updatedSettingsData.otomi,
adminPassword: settings.otomi?.adminPassword,
}
// 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
}
}
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()
await this.doDeployment({ filePath, content: aplObject }, true, [
`${this.getRepoPath()}/env/settings/secrets.${settingId}.yaml`,
])
return settings
}
filterExcludedApp(apps: App | App[]) {
const preInstalledExcludedApps = env.PREINSTALLED_EXCLUDED_APPS.apps
const hiddenApps = env.HIDDEN_APPS.apps
const excludedApps = preInstalledExcludedApps.concat(hiddenApps)
const settingsInfo = this.getSettingsInfo()
if (!Array.isArray(apps)) {
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)) {
if (settingsInfo.otomi && settingsInfo.otomi.isPreInstalled) {
return apps.filter((app) => !excludedApps.includes(app.id))
} else {
return apps
}
}
return apps
}
getTeamApp(teamId: string, id: string): App | ExcludedApp {
const app = this.getApp(id)
this.filterExcludedApp(app)
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
}
getApps(teamId: string): Array<App> {
const appList = this.getAppList()
const allApps = appList.map((id) => {
return this.getApp(id)
})
const providerSpecificApps = this.filterExcludedApp(allApps) as App[]
if (teamId === 'admin')
return providerSpecificApps.map((app) => {
return {
id: app.id,
enabled: Boolean(app.values?.enabled ?? true),
}
})
const core = this.getCore()
const teamApps = providerSpecificApps
.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: Boolean(app.values?.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 }, true, [`${this.getRepoPath()}/env/apps/secrets.${id}.yaml`])
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,
true,
ids.map((id) => `${this.getRepoPath()}/env/apps/secrets.${id}.yaml`),
)
}
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')
if (isEmpty(data.spec.password)) {
debug(`creating password for team '${teamName}'`)
// eslint-disable-next-line no-param-reassign
data.spec.password = generatePassword({
length: 16,
numbers: true,
symbols: false,
lowercase: true,
uppercase: true,
strict: true,
})
}
const teamObject = toTeamObject(teamName, data)
const team = await this.saveTeam(teamObject)
await this.doDeployment(team, true, [`${this.getRepoPath()}/env/teams/${teamName}/secrets.settings.yaml`])
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, true, [`${this.getRepoPath()}/env/teams/${name}/secrets.settings.yaml`])
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 }
}
async saveTeamWorkload(aplTeamObject: AplTeamObject): Promise<AplRecord> {
const teamId = aplTeamObject.metadata.labels['apl.io/teamId']
debug(`Saving AplTeamWorkload ${aplTeamObject.metadata.name} for team ${teamId}`)
// Create workload object without values for file storage
const workload = {
...aplTeamObject,
spec: omit(aplTeamObject.spec, 'values'),
} as AplTeamObject
const filePath = this.fileStore.setTeamResource(workload)
await this.git.writeFile(filePath, workload)
return { filePath, content: workload }
}
async saveTeamWorkloadValues(
teamId: string,
name: string,
values: string,
createManagedFile = false,
): Promise<AplRecord> {
debug(`Saving AplTeamWorkloadValues ${name} for team ${teamId}`)
//AplTeamWorkloadValues does not adhere the AplObject structure so we set it as any
const aplRecord = this.fileStore.set(getTeamWorkloadValuesFilePath(teamId, name), values as any)
await this.git.writeTextFile(aplRecord.filePath, values)
if (createManagedFile) {
const filePathValuesManaged = getTeamWorkloadValuesManagedFilePath(teamId, name)
await this.git.writeTextFile(filePathValuesManaged, '')
}
return aplRecord
}
async saveTeamSealedSecret(teamId: string, data: AplSecretRequest): Promise<AplRecord> {
debug(`Saving sealed secrets of team: ${teamId}`)
const { metadata } = data
const aplObject = toTeamObject(teamId, data) as AplSecretResponse
const sealedSecretChartValues = sealedSecretManifest(aplObject)
const aplRecord = this.fileStore.set(
getTeamSealedSecretsValuesFilePath(teamId, metadata.name),
sealedSecretChartValues,
)
await this.git.writeFile(aplRecord.filePath, sealedSecretChartValues as any)
return aplRecord
}
async deleteTeamConfigItem(kind: AplKind, teamId: string, name: string): Promise<string> {
debug(`Removing ${kind} ${name} for team ${teamId}`)
const filePath = this.fileStore.deleteTeamResource(kind, teamId, name)
await this.git.removeFile(filePath)
return filePath
}
async deleteTeamWorkload(kind: AplKind, teamId: string, name: string): Promise<string> {
debug(`Removing AplWorkload ${name} for team ${teamId}`)
// Delete workload file
const workloadFilePath = this.fileStore.deleteTeamResource(kind, teamId, name)
await this.git.removeFile(workloadFilePath)
// Delete workload values file
const valuesFilePath = getTeamWorkloadValuesFilePath(teamId, name)
await this.git.removeFile(valuesFilePath)
// Delete managed values file
const managedFilePath = getTeamWorkloadValuesManagedFilePath(teamId, name)
await this.git.removeFile(managedFilePath)
return workloadFilePath
}
getTeamNetpols(teamId: string): Netpol[] {
return this.getTeamAplNetpols(teamId).map((netpol) => getV1ObjectFromApl(netpol) as Netpol)
}
getTeamAplNetpols(teamId: string): AplNetpolResponse[] {
const files = this.fileStore.getTeamResourcesByKindAndTeamId('AplTeamNetworkControl', teamId)
return Array.from(files.values()) as AplNetpolResponse[]
}
getAllNetpols(): Netpol[] {
return this.getAllAplNetpols().map((netpol) => getV1ObjectFromApl(netpol) as Netpol)
}
getAllAplNetpols(): AplNetpolResponse[] {
const files = this.fileStore.getAllTeamResourcesByKind('AplTeamNetworkControl')
return Array.from(files.values()) as AplNetpolResponse[]
}
async createNetpol(teamId: string, data: Netpol): Promise<Netpol> {
const newNetpol = await this.createAplNetpol(
teamId,
getAplObjectFromV1('AplTeamNetworkControl', data) as AplNetpolRequest,
)
return getV1ObjectFromApl(newNetpol) as Netpol
}
async createAplNetpol(teamId: string, data: AplNetpolRequest): Promise<AplNetpolResponse> {
if (data.metadata.name.length < 2)
throw new ValidationError('Network policy name must be at least 2 characters long')
if (this.fileStore.getTeamResource('AplTeamNetworkControl', teamId, data.metadata.name)) {
throw new AlreadyExists('Network policy name already exists')
}
const teamObject = toTeamObject(teamId, data)
const aplRecord = await this.saveTeamConfigItem(teamObject)
await this.doDeployment(aplRecord, false)
return aplRecord.content as AplNetpolResponse
}
getNetpol(teamId: string, name: string): Netpol {
const netpol = this.getAplNetpol(teamId, name)
return getV1ObjectFromApl(netpol) as Netpol
}
getAplNetpol(teamId: string, name: string): AplNetpolResponse {
const netpol = this.fileStore.getTeamResource('AplTeamNetworkControl', teamId, name)
if (!netpol) {
throw new NotExistError(`Network policy ${name} not found in team ${teamId}`)
}
return netpol as AplNetpolResponse
}
async editNetpol(teamId: string, name: string, data: Netpol): Promise<Netpol> {
const mergeObj = getV1MergeObject(data) as DeepPartial<AplNetpolRequest>
const mergedNetpol = await this.editAplNetpol(teamId, name, mergeObj)
return getV1ObjectFromApl(mergedNetpol) as Netpol
}
async editAplNetpol(
teamId: string,
name: string,
data: AplNetpolRequest | DeepPartial<AplNetpolRequest>,
patch = false,
): Promise<AplNetpolResponse> {
const existing = this.getAplNetpol(teamId, name)
const updatedSpec = patch
? merge(cloneDeep(existing.spec), data.spec)
: ({ ...existing.spec, ...data.spec } as Netpol)
const teamObject = buildTeamObject(existing, updatedSpec)
const aplRecord = await this.saveTeamConfigItem(teamObject)
await this.doDeployment(aplRecord, false)
return aplRecord.content as AplNetpolResponse
}
async deleteNetpol(teamId: string, name: string): Promise<void> {
const filePath = await this.deleteTeamConfigItem('AplTeamNetworkControl', teamId, name)
await this.doDeleteDeployment([filePath])
}
getAllUsers(sessionUser: SessionUser): Array<User> {
const files = this.fileStore.getPlatformResourcesByKind('AplUser')
const aplObjects = Array.from(files.values()) as AplObject[]
const users = aplObjects.map((aplObject) => {
return { ...aplObject.spec, id: aplObject.metadata.name } as User
})
if (sessionUser.isPlatformAdmin) {
return users
} else if (sessionUser.isTeamAdmin) {
const usersWithBasicInfo = users.map((user) => {
const { id, email, isPlatformAdmin, isTeamAdmin, teams } = user
return { id, email, isPlatformAdmin, isTeamAdmin, teams }
})
return usersWithBasicInfo as Array<User>
}
throw new ForbiddenError()
}
async createUser(data: User): Promise<User> {
const { valid, error } = isValidUsername(data.email.split('@')[0])
if (!valid) {
throw new HttpError(400, error as string)
}
const initialPassword = generatePassword({
length: 16,
numbers: true,
symbols: '!@#$%&*',
lowercase: true,
uppercase: true,
strict: true,
})
const userId = uuidv4()
const user: User = { ...data, id: userId, initialPassword }
// Get existing users' emails
const files = this.fileStore.getPlatformResourcesByKind('AplUser')
let existingUsersEmail = Array.from(files.values()).map((aplObject: AplObject) => aplObject.spec.email)
if (!env.isDev) {
const { otomi, cluster } = this.getSettings(['otomi', 'cluster'])
const keycloak = this.getApp('keycloak')
const keycloakBaseUrl = `https://keycloak.${cluster?.domainSuffix}`
const realm = 'otomi'
const username = keycloak?.values?.adminUsername as string
const password = otomi?.adminPassword as string
existingUsersEmail = await getKeycloakUsers(keycloakBaseUrl, realm, username, password)
}
if (existingUsersEmail.some((existingUser) => existingUser === user.email)) {
throw new AlreadyExists('User email already exists')
}
const aplRecord = await this.saveUser(user)