-
Notifications
You must be signed in to change notification settings - Fork 267
/
resolve-module.ts
468 lines (402 loc) · 16.1 KB
/
resolve-module.ts
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
/*
* Copyright (C) 2018-2020 Garden Technologies, Inc. <info@garden.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { cloneDeep, keyBy } from "lodash"
import { validateWithPath } from "./config/validation"
import { resolveTemplateStrings, getModuleTemplateReferences, resolveTemplateString } from "./template-string"
import { ContextResolveOpts, ModuleConfigContext, GenericContext } from "./config/config-context"
import { relative, resolve, posix } from "path"
import { Garden } from "./garden"
import { ConfigurationError, FilesystemError, PluginError } from "./exceptions"
import { deline, dedent } from "./util/string"
import { getModuleKey, ModuleConfigMap, GardenModule, ModuleMap, moduleFromConfig } from "./types/module"
import { getModuleTypeBases } from "./plugins"
import { ModuleConfig, moduleConfigSchema } from "./config/module"
import { Profile } from "./util/profiling"
import { getLinkedSources } from "./util/ext-source-util"
import { ProviderMap } from "./config/provider"
import { RuntimeContext } from "./runtime-context"
import chalk from "chalk"
import { DependencyValidationGraph } from "./util/validate-dependencies"
import Bluebird from "bluebird"
import { readFile, mkdirp, writeFile } from "fs-extra"
import { LogEntry } from "./logger/log-entry"
// This limit is fairly arbitrary, but we need to have some cap on concurrent processing.
export const moduleResolutionConcurrencyLimit = 40
/**
* Resolves a set of module configurations in dependency order.
*
* This operates differently than the TaskGraph in that it can add dependency links as it proceeds through the modules,
* which is important because dependencies can be discovered mid-stream, and the TaskGraph currently needs to
* statically resolve all dependencies before processing tasks.
*/
@Profile()
export class ModuleResolver {
private garden: Garden
private log: LogEntry
private rawConfigs: ModuleConfig[]
private rawConfigsByName: ModuleConfigMap
private resolvedProviders: ProviderMap
private runtimeContext?: RuntimeContext
constructor({
garden,
log,
rawConfigs,
resolvedProviders,
runtimeContext,
}: {
garden: Garden
log: LogEntry
rawConfigs: ModuleConfig[]
resolvedProviders: ProviderMap
runtimeContext?: RuntimeContext
}) {
this.garden = garden
this.log = log
this.rawConfigs = rawConfigs
this.rawConfigsByName = keyBy(rawConfigs, "name")
this.resolvedProviders = resolvedProviders
this.runtimeContext = runtimeContext
}
async resolveAll() {
// Collect template references for every raw config and work out module references in templates and explicit
// dependency references. We use two graphs, one will be fully populated as we progress, the other we gradually
// remove nodes from as we complete the processing.
const fullGraph = new DependencyValidationGraph()
const processingGraph = new DependencyValidationGraph()
for (const rawConfig of this.rawConfigs) {
for (const graph of [fullGraph, processingGraph]) {
graph.addNode(rawConfig.name)
}
}
for (const rawConfig of this.rawConfigs) {
const deps = this.getModuleDependenciesFromTemplateStrings(rawConfig)
for (const graph of [fullGraph, processingGraph]) {
for (const dep of deps) {
graph.addNode(dep.name)
graph.addDependency(rawConfig.name, dep.name)
}
}
}
const resolvedConfigs: ModuleConfigMap = {}
const resolvedModules: ModuleMap = {}
const errors: { [moduleName: string]: Error } = {}
// Iterate through dependency graph, a batch of leaves at a time. While there are items remaining:
while (processingGraph.size() > 0) {
// Get batch of leaf nodes (ones with no unresolved dependencies). Implicitly checks for circular dependencies.
let batch: string[]
try {
batch = processingGraph.overallOrder(true)
} catch (err) {
throw new ConfigurationError(
dedent`
Detected circular dependencies between module configurations:
${err.detail?.["circular-dependencies"] || err.message}
`,
{ cycles: err.detail?.cycles }
)
}
// Process each of the leaf node module configs.
await Bluebird.map(
batch,
async (moduleName) => {
// Resolve configuration, unless previously resolved.
let resolvedConfig = resolvedConfigs[moduleName]
let foundNewDependency = false
const dependencyNames = fullGraph.dependenciesOf(moduleName)
const resolvedDependencies = dependencyNames.map((n) => resolvedModules[n])
try {
if (!resolvedConfig) {
const rawConfig = this.rawConfigsByName[moduleName]
resolvedConfig = resolvedConfigs[moduleName] = await this.resolveModuleConfig(
rawConfig,
resolvedDependencies
)
// Check if any new build dependencies were added by the configure handler
for (const dep of resolvedConfig.build.dependencies) {
if (!dependencyNames.includes(dep.name)) {
foundNewDependency = true
// We throw if the build dependency can't be found at all
if (!fullGraph.hasNode(dep.name)) {
this.missingBuildDependency(moduleName, dep.name)
}
fullGraph.addDependency(moduleName, dep.name)
// The dependency may already have been processed, we don't want to add it to the graph in that case
if (processingGraph.hasNode(dep.name)) {
processingGraph.addDependency(moduleName, dep.name)
}
}
}
}
// If no build dependency was added, fully resolve the module and remove from graph, otherwise keep it
// in the graph and move on to make sure we fully resolve the dependencies and don't run into circular
// dependencies.
if (!foundNewDependency) {
resolvedModules[moduleName] = await this.resolveModule(resolvedConfig, resolvedDependencies)
processingGraph.removeNode(moduleName)
}
} catch (err) {
errors[moduleName] = err
}
},
{ concurrency: moduleResolutionConcurrencyLimit }
)
if (Object.keys(errors).length > 0) {
const errorStr = Object.entries(errors)
.map(([name, err]) => `${chalk.white.bold(name)}: ${err.message}`)
.join("\n")
throw new ConfigurationError(chalk.red(`Failed resolving one or more modules:\n\n${errorStr}`), {
errors,
})
}
}
return Object.values(resolvedModules)
}
/**
* Returns module configs for each module that is referenced in a ${modules.*} template string in the raw config.
*/
private getModuleDependenciesFromTemplateStrings(rawConfig: ModuleConfig) {
const configContext = new ModuleConfigContext({
garden: this.garden,
resolvedProviders: this.resolvedProviders,
moduleName: rawConfig.name,
dependencies: [],
runtimeContext: this.runtimeContext,
parentName: rawConfig.parentName,
templateName: rawConfig.templateName,
inputs: rawConfig.inputs,
partialRuntimeResolution: true,
})
const templateRefs = getModuleTemplateReferences(rawConfig, configContext)
const deps = templateRefs.filter((d) => d[1] !== rawConfig.name)
return deps.map((d) => {
const name = d[1]
const moduleConfig = this.rawConfigsByName[name]
if (!moduleConfig) {
this.missingBuildDependency(rawConfig.name, name as string)
}
return moduleConfig
})
}
private missingBuildDependency(moduleName: string, dependencyName: string) {
throw new ConfigurationError(
chalk.red(
`Could not find build dependency ${chalk.white(dependencyName)}, ` +
`configured in module ${chalk.white(moduleName)}`
),
{ moduleName, dependencyName }
)
}
/**
* Resolves and validates a single module configuration.
*/
async resolveModuleConfig(config: ModuleConfig, dependencies: GardenModule[]): Promise<ModuleConfig> {
const garden = this.garden
let inputs = {}
const templateContextParams = {
garden,
resolvedProviders: this.resolvedProviders,
dependencies,
runtimeContext: this.runtimeContext,
parentName: config.parentName,
templateName: config.templateName,
inputs,
partialRuntimeResolution: true,
}
// First resolve and validate the inputs field, because template module inputs may not be fully resolved at this
// time.
// TODO: This whole complicated procedure could be much improved and simplified by implementing lazy resolution on
// values... I'll be looking into that. - JE
const templateName = config.templateName
if (templateName) {
const template = this.garden.moduleTemplates[templateName]
inputs = resolveTemplateStrings(
inputs,
new ModuleConfigContext(templateContextParams),
// Not all inputs may need to be resolvable
{ allowPartial: true }
)
inputs = validateWithPath({
config: cloneDeep(config.inputs || {}),
configType: `inputs for module ${config.name}`,
path: config.configPath || config.path,
schema: template.inputsSchema,
projectRoot: garden.projectRoot,
})
}
// Now resolve just references to inputs on the config
config = resolveTemplateStrings(cloneDeep(config), new GenericContext({ inputs }), {
allowPartial: true,
})
// And finally fully resolve the config
const configContext = new ModuleConfigContext({
...templateContextParams,
inputs,
moduleName: config.name,
})
config = resolveTemplateStrings({ ...config, inputs: {} }, configContext, {
allowPartial: false,
})
config.inputs = inputs
const moduleTypeDefinitions = await garden.getModuleTypes()
const description = moduleTypeDefinitions[config.type]
if (!description) {
const configPath = relative(garden.projectRoot, config.configPath || config.path)
throw new ConfigurationError(
deline`
Unrecognized module type '${config.type}' (defined at ${configPath}).
Are you missing a provider configuration?
`,
{ config, configuredModuleTypes: Object.keys(moduleTypeDefinitions) }
)
}
// Validate the module-type specific spec
if (description.schema) {
config.spec = validateWithPath({
config: config.spec,
configType: "Module",
schema: description.schema,
name: config.name,
path: config.path,
projectRoot: garden.projectRoot,
})
}
/*
We allow specifying modules by name only as a shorthand:
dependencies:
- foo-module
- name: foo-module // same as the above
*/
if (config.build && config.build.dependencies) {
config.build.dependencies = config.build.dependencies.map((dep) =>
typeof dep === "string" ? { name: dep, copy: [] } : dep
)
}
// Validate the base config schema
config = validateWithPath({
config,
schema: moduleConfigSchema(),
configType: "module",
name: config.name,
path: config.path,
projectRoot: garden.projectRoot,
})
if (config.repositoryUrl) {
const linkedSources = await getLinkedSources(garden, "module")
config.path = await garden.loadExtSourcePath({
name: config.name,
linkedSources,
repositoryUrl: config.repositoryUrl,
sourceType: "module",
})
}
const actions = await garden.getActionRouter()
const configureResult = await actions.configureModule({
moduleConfig: config,
log: garden.log,
})
config = configureResult.moduleConfig
// Validate the configure handler output against the module type's bases
const bases = getModuleTypeBases(moduleTypeDefinitions[config.type], moduleTypeDefinitions)
for (const base of bases) {
if (base.schema) {
garden.log.silly(`Validating '${config.name}' config against '${base.name}' schema`)
config.spec = <ModuleConfig>validateWithPath({
config: config.spec,
schema: base.schema.unknown(true),
path: garden.projectRoot,
projectRoot: garden.projectRoot,
configType: `configuration for module '${config.name}' (base schema from '${base.name}' plugin)`,
ErrorClass: ConfigurationError,
})
}
}
// FIXME: We should be able to avoid this
config.name = getModuleKey(config.name, config.plugin)
if (config.plugin) {
for (const serviceConfig of config.serviceConfigs) {
serviceConfig.name = getModuleKey(serviceConfig.name, config.plugin)
}
for (const taskConfig of config.taskConfigs) {
taskConfig.name = getModuleKey(taskConfig.name, config.plugin)
}
for (const testConfig of config.testConfigs) {
testConfig.name = getModuleKey(testConfig.name, config.plugin)
}
}
return config
}
private async resolveModule(resolvedConfig: ModuleConfig, dependencies: GardenModule[]) {
// Write module files
const configContext = new ModuleConfigContext({
garden: this.garden,
resolvedProviders: this.resolvedProviders,
moduleName: resolvedConfig.name,
dependencies,
runtimeContext: this.runtimeContext,
parentName: resolvedConfig.parentName,
templateName: resolvedConfig.templateName,
inputs: resolvedConfig.inputs,
partialRuntimeResolution: true,
})
await Bluebird.map(resolvedConfig.generateFiles || [], async (fileSpec) => {
let contents = fileSpec.value || ""
if (fileSpec.sourcePath) {
contents = (await readFile(fileSpec.sourcePath)).toString()
}
const resolvedContents = resolveTemplateString(contents, configContext, { unescape: true })
const targetDir = resolve(resolvedConfig.path, ...posix.dirname(fileSpec.targetPath).split(posix.sep))
const targetPath = resolve(resolvedConfig.path, ...fileSpec.targetPath.split(posix.sep))
try {
await mkdirp(targetDir)
await writeFile(targetPath, resolvedContents)
} catch (error) {
throw new FilesystemError(
`Unable to write templated file ${fileSpec.targetPath} from ${resolvedConfig.name}: ${error.message}`,
{
fileSpec,
error,
}
)
}
})
const module = await moduleFromConfig(this.garden, this.log, resolvedConfig, dependencies)
const moduleTypeDefinitions = await this.garden.getModuleTypes()
const description = moduleTypeDefinitions[module.type]!
// Validate the module outputs against the outputs schema
if (description.moduleOutputsSchema) {
module.outputs = validateWithPath({
config: module.outputs,
schema: description.moduleOutputsSchema,
configType: `outputs for module`,
name: module.name,
path: module.configPath || module.path,
projectRoot: this.garden.projectRoot,
ErrorClass: PluginError,
})
}
// Validate the module outputs against the module type's bases
const bases = getModuleTypeBases(moduleTypeDefinitions[module.type], moduleTypeDefinitions)
for (const base of bases) {
if (base.moduleOutputsSchema) {
this.log.silly(`Validating '${module.name}' module outputs against '${base.name}' schema`)
module.outputs = validateWithPath({
config: module.outputs,
schema: base.moduleOutputsSchema.unknown(true),
path: module.configPath || module.path,
projectRoot: this.garden.projectRoot,
configType: `outputs for module '${module.name}' (base schema from '${base.name}' plugin)`,
ErrorClass: PluginError,
})
}
}
return module
}
}
export interface ModuleConfigResolveOpts extends ContextResolveOpts {
configContext: ModuleConfigContext
}