-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
846 lines (797 loc) · 32.3 KB
/
index.ts
File metadata and controls
846 lines (797 loc) · 32.3 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
import { createMachine, interpret } from 'xstate';
import { isEmpty, get, each, map, isFunction, has, uniqueId, filter, omit, includes, set, isNil, isUndefined, keys, size, cloneDeep, find } from 'lodash';
import { IStepOptions, IRecord, IStatus, IEngineOptions, IContext, IEngineError, STEP_STATUS, IDiff } from './types';
import { getProcessTime, getCredential, stringify, getAllowFailure, getDiffs } from './utils';
import ParseSpec, { getInputs, ISpec, IHookType, IStep as IParseStep, IActionLevel } from '@serverless-devs/parse-spec';
import path from 'path';
import chalk from 'chalk';
import Actions from './actions';
import Credential from '@serverless-devs/credential';
import loadComponent from '@serverless-devs/load-component';
import Logger, { ILoggerInstance } from '@serverless-devs/logger';
import SecretManager from '@serverless-devs/secret';
import { DevsError, ETrackerType, emoji, getAbsolutePath, getRootHome, getUserAgent, traceid, parseArgv } from '@serverless-devs/utils';
import { EXIT_CODE, INFO_EXP_PATTERN, COMPONENT_EXP_PATTERN } from './constants';
import assert from 'assert';
import Ajv from 'ajv';
export * from './types';
export { verify, preview, init } from './utils';
const debug = require('@serverless-cd/debug')('serverless-devs:engine');
/**
* Engine Class
*
* This class provides an engine to handle Serverless Devs operations and steps.
* It operates based on the xstate state machine library, ensuring that execution follows
* the predefined flow and states.
*/
class Engine {
public context = {
status: STEP_STATUS.PENDING,
completed: false,
error: [] as IEngineError[],
} as IContext;
private record = { status: STEP_STATUS.PENDING, editStatusAble: true } as IRecord;
private spec = {} as ISpec;
private baselineSpec = {} as ISpec;
private glog!: Logger;
private logger!: ILoggerInstance;
private parseSpecInstance!: ParseSpec;
private parseSpecInstanceBaseline!: ParseSpec;
private globalActionInstance!: Actions; // 全局的 action
private actionInstance!: Actions; // 项目的 action
private info: Record<string, any> = {}; // 存储全局变量
private secretManager!: SecretManager; // 敏感参数管理
private diffs: IDiff[] = []; // baseline diff
constructor(private options: IEngineOptions) {
debug('engine start');
// 初始化参数
this.options.args = get(this.options, 'args', process.argv.slice(2));
this.options.cwd = get(this.options, 'cwd', process.cwd());
this.options.template = getAbsolutePath(get(this.options, 'template'), this.options.cwd);
debug(`engine options: ${stringify(options)}`);
}
/**
* Initialization steps before starting the engine.
*/
private async beforeStart() {
// 初始化 logger
this.glog = this.getLogger() as Logger;
this.logger = this.glog.__generate('engine');
// 初始化 secretManager
this.secretManager = SecretManager.getInstance();
// 加密所有敏感值
const secrets = this.secretManager.getAllSecrets();
for (const i of keys(secrets)) {
this.glog.__setSecret([i, secrets[i]]);
this.glog.__setSecret([i, this.secretManager.getSecret(i)]);
}
// 初始化 spec
this.parseSpecInstance = new ParseSpec(get(this.options, 'template'), {
argv: this.options.args,
logger: this.logger,
});
this.spec = await this.parseSpecInstance.start();
// 20240808: Add baselineTemplate, do diff when --baseline-template is set
if (this.spec.baselineTemplate) {
this.logger.debug(`baselineTemplate: ${this.spec.baselineTemplate}`);
this.parseSpecInstanceBaseline = new ParseSpec(get(this.spec, 'baselineTemplate'), {
argv: this.options.args,
logger: this.logger,
});
this.baselineSpec = await this.parseSpecInstanceBaseline.start();
this.diffs = getDiffs(get(this.spec, 'yaml.content'), get(this.baselineSpec, 'yaml.content')) || [];
}
// 初始化行参环境变量 > .env (parse-spec require .env)
each(this.options.env, (value, key) => {
process.env[key] = value;
});
const { steps: _steps, allSteps } = this.spec;
// 参数校验
await this.validate();
this.context.steps = await this.download(_steps);
this.context.allSteps = allSteps ? await this.download(allSteps) : [];
}
/**
* Start the engine.
*
* This is the primary execution function for the engine. It is responsible for starting
* the entire engine and handling each step.
*
* @note engine应收敛所有的异常,不应该抛出异常
*/
async start() {
this.context.status = STEP_STATUS.RUNNING;
// Haoran: should set this.record.status to RUNNING?
this.record.status = STEP_STATUS.RUNNING;
try {
await this.beforeStart();
} catch (error) {
this.context.status = STEP_STATUS.FAILURE;
this.context.completed = true;
this.context.error.push(error as IEngineError);
return this.context;
}
const { steps: _steps, yaml, command, access = yaml.access } = this.spec;
this.logger.write(chalk.gray(`${emoji('⌛')} Steps for [${command}] of [${get(this.spec, 'yaml.appName')}]\n${chalk.gray('====================')}`));
// 初始化全局的 action
this.globalActionInstance = new Actions(yaml.actions, {
hookLevel: IActionLevel.GLOBAL,
appName: get(this.spec, 'yaml.appName'), // 项目名称
logger: this.logger,
skipActions: this.spec.skipActions,
});
const credential = await getCredential(access, this.logger);
this.context.credential = credential;
// 处理 global-pre
try {
this.globalActionInstance.setValue('magic', await this.getFilterContext());
this.globalActionInstance.setValue('command', command);
await this.globalActionInstance.start(IHookType.PRE, { access, credential });
} catch (error) {
this.context.error.push(error as DevsError);
this.context.status = STEP_STATUS.FAILURE;
await this.doCompleted();
return this.context;
}
// Assign the id, pending status and etc for all steps.
this.context.steps = map(this.context.steps, item => {
return { ...item, stepCount: uniqueId(), status: STEP_STATUS.PENDING, done: false };
});
this.context.allSteps = map(this.context.allSteps, item => {
return { ...item, stepCount: uniqueId(), status: STEP_STATUS.PENDING, done: false };
});
const res: IContext = await new Promise(async resolve => {
// Every states object has two fixed states, "init" and "final".
const states: any = {
init: {
on: {
// Haoran: May this.context.steps be empty?
INIT: this.context.steps.length === 0 ? 'final' : get(this.context.steps, '[0].stepCount'),
},
},
final: {
type: 'final',
invoke: {
src: async () => {
// 执行终态是 error-with-continue 的时候,改为 success
const status = this.record.status === STEP_STATUS.ERROR_WITH_CONTINUE ? STEP_STATUS.SUCCESS : this.record.status;
this.context.status = status;
await this.doCompleted();
this.context.steps = map(this.context.steps, item => omit(item, ['instance']));
this.context.output = this.getOutput();
debug(`context: ${stringify(this.context)}`);
debug('engine end');
resolve(this.context);
},
},
},
};
// Every states object has dynamic state, that based on the step.StepCount.
each(this.context.steps, (item, index) => {
const target = this.context.steps[index + 1] ? get(this.context.steps, `[${index + 1}].stepCount`) : 'final';
const flowProject = yaml.useFlow ? filter(this.context.steps, o => o.flowId === item.flowId) : [item];
states[item.stepCount as string] = {
invoke: {
id: item.stepCount,
src: async () => {
// 并行时如果已经执行,则跳过。
if (item.done) return;
this.record.startTime = Date.now();
// 记录 context
this.recordContext(item, { status: STEP_STATUS.RUNNING });
// 检查全局的执行状态,如果是failure,则不执行该步骤, 并记录状态为 skipped
if (this.record.status === STEP_STATUS.FAILURE) {
return await Promise.all(map(flowProject, o => this.doSkip(o)));
}
return await Promise.all(map(flowProject, o => this.handleSrc(o)));
},
onDone: {
target,
},
onError: target,
},
};
});
const fetchMachine = createMachine({
predictableActionArguments: true,
id: 'step',
initial: 'init',
states,
});
const stepService = interpret(fetchMachine)
.onTransition(state => state.value)
.start();
stepService.send('INIT');
});
this.glog.__clear();
return res;
}
/**
* Extracts and returns an object containing the output of each step.
* The object's key is the project name and the value is the output of that project.
*/
private getOutput() {
const output = {};
each(this.context.steps, item => {
if (!isNil(item.output)) {
set(output, item.projectName, item.output);
}
});
return output;
}
/**
* Validates the 'steps', 'command' and 'projectName' present in 'this.spec'.
* Throws an error if either 'steps' or 'command' are missing or 'projectName' is overlaps with a command.
*/
private async validate() {
const { steps, command, projectName } = this.spec;
let errorsList: any[] = [];
const ajv = new Ajv({ allErrors: true });
assert(!isEmpty(steps), 'Step is required');
for (const step of steps) {
const instance = await loadComponent(step.component, { logger: this.logger, engineLogger: this.logger });
if (projectName && keys(get(instance, 'commands')).includes(projectName)) {
throw new DevsError(`The name of the project [${projectName}] overlaps with a command, please change it's name.`, {
exitCode: EXIT_CODE.DEVS,
trackerType: ETrackerType.parseException,
prefix: `[${projectName}] failed to [${command}]:`
});
}
// schema validation
if (get(this.spec, 'yaml.use3x') && get(this.spec, 'yaml.content.validation')) {
const schema = await this.getSchemaByInstance(instance);
if (isEmpty(schema)) continue;
const validate = ajv.compile(JSON.parse(schema));
if (!validate(step.props)) {
const errors = validate.errors;
if (!errors) continue;
for (const j of errors) {
j.instancePath = step.projectName + '/props' + j.instancePath;
if (j.keyword === 'enum') {
j.message = j.message + ': ' + j.params.allowedValues.join(', ');
}
}
errorsList = errorsList.concat(errors);
}
}
}
assert(command, 'Command is required');
if (!isEmpty(errorsList)) {
throw new DevsError(`${ajv.errorsText(errorsList, { dataVar: '', separator: '\n' })}`, {
exitCode: EXIT_CODE.DEVS,
trackerType: ETrackerType.parseException,
prefix: 'Function props validation error:'
});
}
}
/**
* Get schema by existing instance, avoid loading components.
* @param instance loadComponent instance
* @param logger Logger
*/
private getSchemaByInstance(instance: any) {
if (!instance || !instance.getSchema) return null;
return instance.getSchema();
}
/**
* Asynchronously downloads and initializes the given steps.
* For each step, it loads the specified component and associates a logger with it.
* Returns an array containing the initialized steps.
*/
private async download(steps: IParseStep[]) {
const { command } = this.spec;
const newSteps = [];
for (const step of steps) {
const logger = this.glog.__generate(step.projectName);
const instance = await loadComponent(step.component, {
logger,
engineLogger: this.logger,
});
const verify = get(instance, `commands.${command}.verify`);
newSteps.push({ ...step, instance, logger, verify: isUndefined(verify) ? true : verify });
}
return newSteps;
}
private getLogger() {
const customLogger = get(this.options, 'logConfig.customLogger');
if (customLogger) {
debug('use custom logger');
if (customLogger?.CODE === Logger.CODE) {
return customLogger;
}
throw new Error('customLogger must be instance of Logger');
}
return new Logger({
traceId: traceid(),
logDir: path.join(getRootHome(), 'logs'),
...this.options.logConfig,
level: get(this.options, 'logConfig.level', this.spec.debug ? 'DEBUG' : undefined),
});
}
/**
* Updates the context for the given step based on the provided options.
*
* @param item - The current step being processed.
* @param options - An object containing details like status, error, output, etc. to update the step's context.
*/
private recordContext(item: IStepOptions, options: Record<string, any> = {}) {
const { status, error, output, process_time, props, done } = options;
this.context.stepCount = item.stepCount as string;
this.context.steps = map(this.context.steps, obj => {
if (obj.stepCount === item.stepCount) {
if (status) {
obj.status = status;
}
if (error) {
obj.error = error;
this.context.error.push(error);
}
if (props) {
obj.props = props;
}
if (output) {
obj.output = output;
}
if (done) {
obj.done = done;
}
if (has(options, 'process_time')) {
obj.process_time = process_time;
}
}
return obj;
});
}
/**
* 20240624 New feature
* ${resources.xx.info.xx} read from `info` command's output.
* This function will check current step content to determine
* whether to execute `info` command of a certain resource.
*
* @param item - The current step being processed.
* @returns
*/
private async getInfo(item: IStepOptions | undefined) {
if (!item) return;
const { props } = item;
const compString = JSON.stringify(props);
const matches = compString.matchAll(INFO_EXP_PATTERN);
const resourceNames = new Set<string>();
for (const match of matches) {
if (match[1]) {
resourceNames.add(match[1]);
}
}
// support ${components.xx.output.xx}
const comMatches = compString.matchAll(COMPONENT_EXP_PATTERN);
for (const match of comMatches) {
if (match[1]) {
resourceNames.add(match[1]);
}
}
if (isEmpty(resourceNames)) return;
const resourcesItems: IStepOptions[] = map(Array.from(resourceNames), (name) => {
return this.context.allSteps.find((obj) => obj.projectName === name) as IStepOptions;
});
await Promise.all(map(resourcesItems, async (item) => {
if (!item) return;
const projectInfo = get(this.info, item.projectName);
if (!projectInfo || isEmpty(projectInfo) || isNil(projectInfo)) {
this.logger.write(`${chalk.gray(`execute info command of [${item.projectName}]...`)}`);
let args = cloneDeep(this.options.args);
if (args) {
args[0] = 'info';
}
// 20250520: support action for ${resources.xx.info.xx}
const newParseSpecInstance = new ParseSpec(get(this.spec, 'yaml.path'), {
argv: args,
logger: this.logger,
});
newParseSpecInstance.start();
const newAction = newParseSpecInstance.parseActions(item.actions, IActionLevel.PROJECT);
const newActionInstance = new Actions(newAction, {
hookLevel: IActionLevel.PROJECT,
projectName: item.projectName, // 资源名称
appName: get(this.spec, 'yaml.appName'), // 项目名称
logger: item.logger,
skipActions: this.spec.skipActions,
});
newActionInstance.setValue('magic', await this.getFilterContext(item));
newActionInstance.setValue('step', item);
newActionInstance.setValue('command', 'info');
const newInputs = await this.getProps(item);
newActionInstance.setValue('componentProps', newInputs);
const pluginResult = await this.actionInstance?.start(IHookType.PRE, newInputs) || {};
const spec = cloneDeep(this.spec);
spec['command'] = 'info';
// 20240912 when -f, don't throw error
// 20250521: remove previous logic
let res: any = {}
try {
res = await this.doSrc(item, pluginResult, spec);
set(newInputs, 'output', res);
const pluginSuccessResult = await newActionInstance?.start(IHookType.SUCCESS, newInputs);
if (!isEmpty(pluginSuccessResult)) {
res = get(pluginSuccessResult, 'step.output');
}
} catch (e) {
this.logger.warn(get(e, 'data'));
// 将error信息添加到inputs中传递给fail hook
set(newInputs, 'errorContext', e);
res = get(await newActionInstance?.start(IHookType.FAIL, newInputs), 'step.output') || {};
}
const pluginCompleteResult = await newActionInstance?.start(IHookType.COMPLETE, newInputs);
if (!isEmpty(pluginCompleteResult)) {
res = get(pluginCompleteResult, 'step.output');
}
set(this.info, item.projectName, res);
this.logger.write(`${chalk.gray(`[${item.projectName}] info command executed.`)}`);
}
}));
}
/**
* Generates a context data for the given step containing details like cwd, vars, and other steps' outputs and props.
* @param item - The current step being processed.
* @returns - The generated context data.
*/
private async getFilterContext(item?: IStepOptions) {
await this.getInfo(item);
const data = {
cwd: path.dirname(this.spec.yaml.path),
vars: this.spec.yaml.vars,
resources: {},
components: {},
__runtime: this.options.verify ? 'engine' : 'parse',
__steps: this.context.steps,
} as Record<string, any>;
for (const obj of this.context.allSteps) {
const stepItem = find(this.context.steps, (obj2) => obj2.projectName === obj.projectName);
data.resources[obj.projectName] = {
output: obj.output || get(stepItem, 'output') || {},
props: obj.props || get(stepItem, 'props') || {},
info: this.info[obj.projectName] || {},
vars: obj.vars || get(stepItem, 'vars') || {},
};
// support ${components.xx.output.xx}
data.components[obj.projectName] = {
output: this.info[obj.projectName] || {},
}
}
if (item) {
data.credential = item.credential;
data.that = {
name: item.projectName,
access: item.access,
component: item.component,
props: data.resources[item.projectName].props,
output: data.resources[item.projectName].output,
vars: data.resources[item.projectName].vars,
};
}
return data;
}
/**
* Handles the subsequent operations after a step has been completed.
* 1. Marks the step as completed.
* 2. If the step status is FAILURE, attempts to trigger the global FAIL hook.
* 3. If the step status is SUCCESS, attempts to trigger the global SUCCESS hook.
* 4. Regardless of the step's status, tries to trigger the global COMPLETE hook to denote completion.
*/
private async doCompleted() {
this.context.completed = true;
if (this.context.status === STEP_STATUS.FAILURE) {
try {
await this.globalActionInstance.start(IHookType.FAIL, this.context);
} catch (error) {
this.context.status = STEP_STATUS.FAILURE;
this.context.error.push(error as DevsError);
}
}
if (this.context.status === STEP_STATUS.SUCCESS) {
try {
await this.globalActionInstance.start(IHookType.SUCCESS, this.context);
} catch (error) {
this.context.status = STEP_STATUS.FAILURE;
this.context.error.push(error as DevsError);
}
}
try {
await this.globalActionInstance.start(IHookType.COMPLETE, this.context);
} catch (error) {
this.context.status = STEP_STATUS.FAILURE;
this.context.error.push(error as DevsError);
}
}
/**
* Handles the execution process for a project step.
* @param item - The project step to handle.
*/
private async handleSrc(item: IStepOptions) {
const { command } = this.spec;
// Attempt to execute pre-hook and component logic for the project step.
try {
// project pre hook and project component
await this.handleAfterSrc(item);
} catch (error) {
// On error, attempt to trigger the project's fail hook and update the recorded context.
try {
// 将error信息添加到inputs中传递给fail hook
const failInputs = {
...this.record.componentProps,
errorContext: error,
};
const res = await this.actionInstance?.start(IHookType.FAIL, failInputs);
this.recordContext(item, get(res, 'pluginOutput', {}));
} catch (error) {
this.record.status = STEP_STATUS.FAILURE;
this.recordContext(item, { error });
}
}
// 若记录的全局状态为true,则进行输出成功的日志
// If the global record status is SUCCESS, attempt to trigger the project's success hook.
if (this.record.status === STEP_STATUS.SUCCESS) {
// project success hook
try {
// 项目的output, 再次获取魔法变量
this.actionInstance.setValue('magic', await this.getFilterContext(item));
const res = await this.actionInstance?.start(IHookType.SUCCESS, {
...this.record.componentProps,
output: get(item, 'output', {}),
});
this.recordContext(item, get(res, 'pluginOutput', {}));
} catch (error) {
this.record.status = STEP_STATUS.FAILURE;
this.recordContext(item, { error });
}
}
// Attempt to trigger the project's complete hook regardless of status.
try {
// complete hook需要包含error信息(如果有的话)
const completeInputs = {
...this.record.componentProps,
output: get(item, 'output', {}),
errorContext: get(item, 'error'),
};
const res = await this.actionInstance?.start(IHookType.COMPLETE, completeInputs);
this.recordContext(item, get(res, 'pluginOutput', {}));
} catch (error) {
this.record.status = STEP_STATUS.FAILURE;
this.recordContext(item, { error });
}
// 记录项目已经执行完成
const process_time = getProcessTime(this.record.startTime);
this.recordContext(item, { done: true, process_time });
// Log output based on the record status.
if (this.record.status === STEP_STATUS.SUCCESS) {
this.logger.write(`${chalk.green('✔')} ${chalk.gray(`[${item.projectName}] completed (${process_time}s)`)}`);
}
if (this.record.status === STEP_STATUS.FAILURE) {
this.logger.write(`${chalk.red('✖')} ${chalk.gray(`[${item.projectName}] failed to [${command}] (${process_time}s)`)}`);
}
// step执行完成后,释放logger
this.glog.__unset(item.projectName);
}
/**
* Handles the logic after a project step's execution.
* @param item - The project step to handle.
*/
private async handleAfterSrc(item: IStepOptions) {
try {
// Print detailed information of the project step for debugging purposes.
debug(`project item: ${stringify(item)}`);
// Extract the command from the specification.
const { command } = this.spec;
// Retrieve the credentials for the project step.
item.credential = await getCredential(item.access, this.logger);
// Set a secret for each credential.
const { AccessKeyID, AccessKeySecret } = item.credential;
this.glog.__setSecret([AccessKeyID, AccessKeySecret]);
// Parse actions for the project step and initialize a new action instance.
const newAction = this.parseSpecInstance.parseActions(item.actions, IActionLevel.PROJECT);
debug(`project actions: ${JSON.stringify(newAction)}`);
this.actionInstance = new Actions(newAction, {
hookLevel: IActionLevel.PROJECT,
projectName: item.projectName, // 资源名称
appName: get(this.spec, 'yaml.appName'), // 项目名称
logger: item.logger,
skipActions: this.spec.skipActions,
});
// Set values for the action instance.
this.actionInstance.setValue('magic', await this.getFilterContext(item));
this.actionInstance.setValue('step', item);
this.actionInstance.setValue('command', command);
// Retrieve properties for the project step.
const newInputs = await this.getProps(item);
this.actionInstance.setValue('componentProps', newInputs);
// Start the pre-hook and execute the logic for the project step.
const pluginResult = await this.actionInstance?.start(IHookType.PRE, newInputs);
const response: any = await this.doSrc(item, pluginResult);
// 记录全局的执行状态
if (this.record.editStatusAble) {
this.record.status = STEP_STATUS.SUCCESS;
}
// If the project step has an ID, update the corresponding record status and output.
if (item.id) {
this.record.steps = {
...this.record.steps,
[item.id]: {
status: STEP_STATUS.SUCCESS,
output: response,
},
};
}
// Update the project step's context to SUCCESS.
this.recordContext(item, { status: STEP_STATUS.SUCCESS, output: response });
} catch (e) {
const error = e as Error;
// Determine the status based on the project step's "continue-on-error" attribute.
const status = item['continue-on-error'] === true ? STEP_STATUS.ERROR_WITH_CONTINUE : STEP_STATUS.FAILURE;
// 记录全局的执行状态
if (this.record.editStatusAble) {
this.record.status = status as IStatus;
}
if (status === STEP_STATUS.FAILURE) {
// 全局的执行状态一旦失败,便不可修改
this.record.editStatusAble = false;
}
// If the project step has an ID, update the corresponding record status.
if (item.id) {
this.record.steps = {
...this.record.steps,
[item.id]: {
status,
},
};
}
// Handle the error based on the project step's "continue-on-error" attribute.
if (item['continue-on-error']) {
this.recordContext(item, { status });
} else {
this.recordContext(item, { status, error });
throw error;
}
}
}
/**
* Retrieve properties for a specific project step.
* @param item - The project step for which properties are to be retrieved.
* @returns An object containing properties related to the project step.
*/
private async getProps(item: IStepOptions) {
const magic = await this.getFilterContext(item);
debug(`magic context: ${JSON.stringify(magic)}`);
const newInputs = getInputs(item.props, magic);
const { projectName, command } = this.spec;
// 20240910: if resource does not exist in baseline, diffs will be empty
const diffs = get(this.baselineSpec, `yaml.content.resources.${item.projectName}`) ?
filter(this.diffs, (diff) => { return diff.path?.startsWith(`resources.${item.projectName}`) }) :
[];
const result = {
cwd: this.options.cwd,
userAgent: getUserAgent({ component: item.instance.__info }),
name: get(this.spec, 'yaml.appName'),
props: newInputs,
command,
args: filter(this.options.args, o => !includes([projectName, command], o)),
yaml: {
path: get(this.spec, 'yaml.path'),
},
resource: {
name: item.projectName,
component: item.component,
access: item.access,
},
outputs: this.getOutput(),
getCredential: async () => {
const res = await new Credential({ logger: this.logger }).get(item.access);
return get(res, 'credential', {});
},
diffs: diffs,
};
this.recordContext(item, { props: newInputs });
debug(`get props: ${JSON.stringify(result)}`);
return result;
}
/**
* Executes the appropriate action based on the provided project step.
* @param item - The project step to be executed.
* @param data - Additional data which may contain plugin output.
* @returns Result of the executed action, if applicable.
*/
private async doSrc(item: IStepOptions, data: Record<string, any> = {}, spec = this.spec) {
// Extract command and projectName from the specification.
const { command = '', projectName, yaml } = spec;
// Retrieve properties for the given project step.
const newInputs = await this.getProps(item);
// default '-y' when flow projects > 1 (workaround for inquirer bug)
const flowProject = yaml.useFlow ? filter(this.context.steps, o => o.flowId === item.flowId) : [item];
if (size(flowProject) > 1) newInputs.args.push('-y');
// Set component properties based on the provided data or the newly retrieved properties.
this.record.componentProps = isEmpty(data.pluginOutput) ? newInputs : data.pluginOutput;
debug(`component props: ${stringify(this.record.componentProps)}`);
this.actionInstance.setValue('componentProps', this.record.componentProps);
// 服务级操作
if (projectName) {
if (isFunction(item.instance[command])) {
// 方法存在,执行报错,退出码101
try {
return await item.instance[command](this.record.componentProps);
} catch (e) {
const useAllowFailure = getAllowFailure(item.allow_failure, {
exitCode: EXIT_CODE.COMPONENT,
command,
});
if (useAllowFailure) return;
const error = e as Error;
throw new DevsError(error.message, {
data: get(e, 'data'),
stack: error.stack,
exitCode: EXIT_CODE.COMPONENT,
prefix: `[${item.projectName}] failed to [${command}]:`,
trackerType: ETrackerType.runtimeException,
});
}
}
const useAllowFailure = getAllowFailure(item.allow_failure, {
exitCode: EXIT_CODE.DEVS,
command,
});
if (useAllowFailure) return;
// 方法不存在,此时系统将会认为是未找到组件方法,系统的exit code为100;
throw new DevsError(`The [${command}] command was not found.`, {
exitCode: EXIT_CODE.DEVS,
tips: `Please check the component ${item.component} has the ${command} command. Serverless Devs documents:${chalk.underline(
'https://docs.serverless-devs.com/',
)}`,
prefix: `[${item.projectName}] failed to [${command}]:`,
trackerType: ETrackerType.parseException,
});
}
// 应用级操作
if (isFunction(item.instance[command])) {
// 方法存在,执行报错,退出码101
try {
return await item.instance[command](this.record.componentProps);
} catch (e) {
const useAllowFailure = getAllowFailure(item.allow_failure, {
exitCode: EXIT_CODE.COMPONENT,
command,
});
if (useAllowFailure) return;
const error = e as Error;
throw new DevsError(error.message, {
data: get(e, 'data'),
stack: error.stack,
exitCode: EXIT_CODE.COMPONENT,
prefix: `[${item.projectName}] failed to [${command}]:`,
trackerType: ETrackerType.runtimeException,
});
}
}
// 方法不存在,进行警告,但是并不会报错,最终的exit code为0;
this.logger.tips(
`The [${command}] command was not found.`,
`Please check the component ${item.component} has the ${command} command. Serverless Devs documents:https://docs.serverless-devs.com/`,
);
}
/**
* Handles the project step that is marked to be skipped.
* @param item - The project step to be skipped.
* @returns A resolved Promise.
*/
private async doSkip(item: IStepOptions) {
// If the step has an 'id', set its status to 'SKIP' in the record.
if (item.id) {
this.record.steps = {
...this.record.steps,
[item.id]: {
status: STEP_STATUS.SKIP,
},
};
}
// Mark the step's status as 'SKIP' and set its processing time to 0.
this.recordContext(item, { status: STEP_STATUS.SKIP, process_time: 0 });
return Promise.resolve();
}
}
export default Engine;