-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.ts
More file actions
282 lines (228 loc) · 9 KB
/
plugin.ts
File metadata and controls
282 lines (228 loc) · 9 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
import { JSONSchemaType } from 'ajv';
import {
ApplyRequestData,
GetResourceInfoRequestData,
GetResourceInfoResponseData,
ImportRequestData,
ImportResponseData,
InitializeRequestData,
InitializeResponseData,
MatchRequestData,
MatchResponseData,
PlanRequestData,
PlanResponseData,
ResourceConfig,
ResourceJson,
ValidateRequestData,
ValidateResponseData
} from 'codify-schemas';
import { ApplyValidationError } from '../common/errors.js';
import { Plan } from '../plan/plan.js';
import { BackgroundPty } from '../pty/background-pty.js';
import { getPty } from '../pty/index.js';
import { Resource } from '../resource/resource.js';
import { ResourceController } from '../resource/resource-controller.js';
import { ptyLocalStorage } from '../utils/pty-local-storage.js';
import { VerbosityLevel } from '../utils/utils.js';
export class Plugin {
planStorage: Map<string, Plan<any>>;
planPty = new BackgroundPty();
constructor(
public name: string,
public resourceControllers: Map<string, ResourceController<ResourceConfig>>
) {
this.planStorage = new Map();
}
static create(name: string, resources: Resource<any>[]) {
const controllers = resources
.map((resource) => new ResourceController(resource))
const controllersMap = new Map<string, ResourceController<any>>(
controllers.map((r) => [r.typeId, r] as const)
);
return new Plugin(name, controllersMap);
}
async initialize(data: InitializeRequestData): Promise<InitializeResponseData> {
if (data.verbosityLevel) {
VerbosityLevel.set(data.verbosityLevel);
}
for (const controller of this.resourceControllers.values()) {
await controller.initialize();
}
return {
resourceDefinitions: [...this.resourceControllers.values()]
.map((r) => {
const sensitiveParameters = Object.entries(r.settings.parameterSettings ?? {})
.filter(([, v]) => v?.isSensitive)
.map(([k]) => k);
// Here we add '*' if the resource is sensitive but no sensitive parameters are found. This works because the import
// sensitivity check only checks for the existance of a sensitive parameter whereas the parameter blocking one blocks
// on a specific sensitive parameter.
if (r.settings.isSensitive && sensitiveParameters.length === 0) {
sensitiveParameters.push('*');
}
return {
dependencies: r.dependencies,
type: r.typeId,
sensitiveParameters,
}
})
}
}
getResourceInfo(data: GetResourceInfoRequestData): GetResourceInfoResponseData {
if (!this.resourceControllers.has(data.type)) {
throw new Error(`Cannot get info for resource ${data.type}, resource doesn't exist`);
}
const resource = this.resourceControllers.get(data.type)!;
const schema = resource.settings.schema as JSONSchemaType<any> | undefined;
const requiredPropertyNames = (
resource.settings.importAndDestroy?.requiredParameters
?? (typeof resource.settings.allowMultiple === 'object' ? resource.settings.allowMultiple.identifyingParameters : null)
?? schema?.required
?? undefined
) as any;
const allowMultiple = resource.settings.allowMultiple !== undefined
&& resource.settings.allowMultiple !== false;
// Here we add '*' if the resource is sensitive but no sensitive parameters are found. This works because the import
// sensitivity check only checks for the existance of a sensitive parameter whereas the parameter blocking one blocks
// on a specific sensitive parameter.
const sensitiveParameters = Object.entries(resource.settings.parameterSettings ?? {})
.filter(([, v]) => v?.isSensitive)
.map(([k]) => k);
if (resource.settings.isSensitive && sensitiveParameters.length === 0) {
sensitiveParameters.push('*');
}
return {
plugin: this.name,
type: data.type,
dependencies: resource.dependencies,
schema: schema as Record<string, unknown> | undefined,
importAndDestroy: {
preventImport: resource.settings.importAndDestroy?.preventImport,
requiredParameters: requiredPropertyNames,
},
import: {
requiredParameters: requiredPropertyNames,
},
sensitiveParameters,
allowMultiple
}
}
async match(data: MatchRequestData): Promise<MatchResponseData> {
const { resource: resourceConfig, array } = data;
const resource = this.resourceControllers.get(resourceConfig.core.type);
if (!resource) {
throw new Error(`Resource of type ${resourceConfig.core.type} could not be found for match`);
}
const match = await resource.match(resourceConfig, array);
return { match }
}
async import(data: ImportRequestData): Promise<ImportResponseData> {
const { core, parameters, autoSearchAll } = data;
if (!this.resourceControllers.has(core.type)) {
throw new Error(`Cannot get info for resource ${core.type}, resource doesn't exist`);
}
const result = await ptyLocalStorage.run(this.planPty, () =>
this.resourceControllers
.get(core.type!)
?.import(core, parameters, autoSearchAll)
)
return {
request: data,
result: result ?? [],
}
}
async validate(data: ValidateRequestData): Promise<ValidateResponseData> {
const validationResults: ValidateResponseData['resourceValidations'] = [];
for (const config of data.configs) {
const { core, parameters } = config;
if (!this.resourceControllers.has(core.type)) {
throw new Error(`Resource type not found: ${core.type}`);
}
const validation = await this.resourceControllers
.get(core.type)!
.validate(core, parameters);
validationResults.push(validation);
}
// Validate that if allow multiple is false, then only 1 of each resource exists
const countMap = data.configs.reduce((map, resource) => {
if (!map.has(resource.core.type)) {
map.set(resource.core.type, 0);
}
const count = map.get(resource.core.type)!;
map.set(resource.core.type, count + 1)
return map;
}, new Map<string, number>())
const invalidMultipleConfigs = [...countMap.entries()].filter(([k, v]) => {
const controller = this.resourceControllers.get(k)!;
return !controller.parsedSettings.allowMultiple && v > 1;
});
if (invalidMultipleConfigs.length > 0) {
throw new Error(
`Multiples of the following configs were found but only 1 is allowed. [${invalidMultipleConfigs.map(([k, v]) => `${v}x ${k}`).join(', ')}] found.`)
}
await this.crossValidateResources(data.configs);
return {
resourceValidations: validationResults
};
}
async plan(data: PlanRequestData): Promise<PlanResponseData> {
const { type } = data.core
if (!this.resourceControllers.has(type)) {
throw new Error(`Resource type not found: ${type}`);
}
const plan = await ptyLocalStorage.run(this.planPty, async () => this.resourceControllers.get(type)!.plan(
data.core,
data.desired ?? null,
data.state ?? null,
data.isStateful
))
this.planStorage.set(plan.id, plan);
return plan.toResponse();
}
async apply(data: ApplyRequestData): Promise<void> {
if (!data.planId && !data.plan) {
throw new Error('For applies either plan or planId must be supplied');
}
const plan = this.resolvePlan(data);
const resource = this.resourceControllers.get(plan.getResourceType());
if (!resource) {
throw new Error('Malformed plan with resource that cannot be found');
}
await resource.apply(plan);
// Validate using desired/desired. If the apply was successful, no changes should be reported back.
// Default back desired back to current if it is not defined (for destroys only)
const validationPlan = await ptyLocalStorage.run(new BackgroundPty(), async () => {
const result = await resource.plan(
plan.coreParameters,
plan.desiredConfig,
plan.desiredConfig ?? plan.currentConfig,
plan.isStateful,
'validationPlan'
);
await getPty().kill();
return result;
})
if (validationPlan.requiresChanges()) {
throw new ApplyValidationError(plan);
}
}
async kill() {
await this.planPty.kill();
}
private resolvePlan(data: ApplyRequestData): Plan<ResourceConfig> {
const { plan: planRequest, planId } = data;
if (planId) {
if (!this.planStorage.has(planId)) {
throw new Error(`Plan with id: ${planId} was not found`);
}
return this.planStorage.get(planId)!
}
if (!planRequest?.resourceType || !this.resourceControllers.has(planRequest.resourceType)) {
throw new Error('Malformed plan. Resource type must be supplied or resource type was not found');
}
const resource = this.resourceControllers.get(planRequest.resourceType)!;
return Plan.fromResponse(planRequest, resource.parsedSettings.defaultValues);
}
protected async crossValidateResources(resources: ResourceJson[]): Promise<void> {
}
}