-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathapl-operator.ts
More file actions
210 lines (177 loc) · 6.35 KB
/
apl-operator.ts
File metadata and controls
210 lines (177 loc) · 6.35 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
import { decrypt } from 'src/common/crypt'
import { commit } from '../cmd/commit'
import { terminal } from '../common/debug'
import { env } from '../common/envalid'
import { GitRepoConfig } from '../common/git-config'
import { waitTillGitRepoAvailable } from '../common/gitea'
import { hfValues } from '../common/hf'
import { ensureTeamGitOpsDirectories } from '../common/utils'
import { writeValues } from '../common/values'
import { HelmArguments } from '../common/yargs'
import { AplOperations } from './apl-operations'
import { GitRepository } from './git-repository'
import { updateApplyState } from './k8s'
import { getErrorMessage } from './utils'
export interface AplOperatorConfig {
gitRepo: GitRepository
gitConfig: GitRepoConfig
aplOps: AplOperations
pollIntervalMs: number
reconcileIntervalMs: number
}
export enum ApplyTrigger {
Poll = 'poll',
Reconcile = 'reconcile',
}
function maskRepoUrl(url: string): string {
return url.replace(/(https?:\/\/)([^@]+)(@.+)/g, '$1***$3')
}
export class AplOperator {
private d = terminal('operator:apl-operator')
private isRunning = false
private isApplying = false
private gitRepo: GitRepository
private aplOps: AplOperations
readonly authenticatedUrl: string
readonly pollInterval: number
readonly reconcileInterval: number
readonly startupGitConfig: GitRepoConfig
constructor(config: AplOperatorConfig) {
const { gitRepo, gitConfig, aplOps, pollIntervalMs, reconcileIntervalMs } = config
this.pollInterval = pollIntervalMs
this.reconcileInterval = reconcileIntervalMs
this.gitRepo = gitRepo
this.aplOps = aplOps
this.authenticatedUrl = gitRepo.authenticatedUrl
this.startupGitConfig = gitConfig
this.d.info(`Initializing APL Operator with repo URL: ${maskRepoUrl(gitRepo.authenticatedUrl)}`)
this.d.debug(`Initializing APL Operator with repo URL: ${gitRepo.authenticatedUrl}`)
}
// public for testing
public async runApplyIfNotBusy(trigger: ApplyTrigger, applyTeamsOnly = false): Promise<void> {
if (this.isApplying) {
this.d.info(`[${trigger}] Apply already in progress, skipping`)
return
}
this.isApplying = true
this.d.info(`[${trigger}] Starting apply process`)
const commitHash = this.gitRepo.lastRevision
await updateApplyState({
commitHash,
status: 'in-progress',
timestamp: new Date().toISOString(),
trigger,
})
try {
const defaultValues = (await hfValues({ defaultValues: true })) as Record<string, any>
this.d.info('Write default values to env repo')
await writeValues(defaultValues)
await this.aplOps.migrate()
if (trigger === ApplyTrigger.Poll) {
this.d.info(`[${trigger}] Starting validation process`)
await this.aplOps.validateValues()
this.d.info(`[${trigger}] Validation process completed`)
}
if (trigger === ApplyTrigger.Reconcile) {
await decrypt()
}
const values = await hfValues({}, env.ENV_DIR)
await ensureTeamGitOpsDirectories(env.ENV_DIR, values ?? {})
await commit(false, {} as HelmArguments, this.startupGitConfig) // Pass startup config to use frozen git credentials
if (applyTeamsOnly) {
await this.aplOps.applyTeams()
await this.aplOps.applyAsAppsTeams()
} else {
await this.aplOps.apply()
}
this.d.info(`[${trigger}] Apply process completed`)
await updateApplyState({
commitHash,
status: 'succeeded',
timestamp: new Date().toISOString(),
trigger,
})
} catch (error) {
const errorMessage = getErrorMessage(error)
this.d.error(`[${trigger}] Apply process failed`, errorMessage)
await updateApplyState({
commitHash,
status: 'failed',
timestamp: new Date().toISOString(),
trigger,
errorMessage,
})
} finally {
this.isApplying = false
}
}
// Only used in tests: run N iterations and exit
public async reconcile(maxIterations = Infinity): Promise<void> {
this.d.info('Starting reconciliation loop')
for (let i = 0; this.isRunning && i < maxIterations; i++) {
try {
this.d.info('Reconciliation triggered')
await this.runApplyIfNotBusy(ApplyTrigger.Reconcile)
this.d.info('Reconciliation completed')
} catch (error) {
this.d.error('Error during reconciliation:', getErrorMessage(error))
}
await this.scheduleNextAttempt(this.reconcileInterval)
}
this.d.info('Reconciliation loop stopped')
}
// Only used in tests: run N iterations and exit
public async pollAndApplyGitChanges(maxIterations = Infinity): Promise<void> {
this.d.info('Starting git polling loop')
for (let i = 0; this.isRunning && i < maxIterations; i++) {
if (this.isApplying) {
this.d.debug('Skipping polling cycle, apply process is in progress')
await this.scheduleNextAttempt(this.pollInterval)
continue
}
try {
const { hasChangesToApply, applyTeamsOnly } = await this.gitRepo.syncAndAnalyzeChanges()
if (hasChangesToApply) {
await this.runApplyIfNotBusy(ApplyTrigger.Poll, applyTeamsOnly)
}
} catch (error) {
this.d.error('Error during git polling cycle:', getErrorMessage(error))
}
await this.scheduleNextAttempt(this.pollInterval)
}
this.d.info('Git polling loop stopped')
}
private async scheduleNextAttempt(interval: number) {
await new Promise((resolve) => setTimeout(resolve, interval))
}
public async start(): Promise<void> {
if (this.isRunning) {
this.d.warn('Operator is already running')
return
}
this.isRunning = true
this.d.info('Starting APL operator')
try {
await waitTillGitRepoAvailable(this.authenticatedUrl)
await this.gitRepo.clone()
this.d.info('APL operator started successfully')
} catch (error) {
this.isRunning = false
this.d.error('Failed to start APL operator:', getErrorMessage(error))
throw error
}
try {
await Promise.all([this.pollAndApplyGitChanges(), this.reconcile()])
} catch (error) {
this.d.error('Error in polling or reconcile task:', getErrorMessage(error))
}
}
public stop(): void {
if (!this.isRunning) {
this.d.warn('Operator is not running')
return
}
this.d.info('Stopping APL operator')
this.isRunning = false
}
}