/
AbstractSoftwareDeliveryMachine.ts
318 lines (282 loc) · 12.4 KB
/
AbstractSoftwareDeliveryMachine.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
/*
* Copyright © 2018 Atomist, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
logger,
Maker,
NoParameters,
} from "@atomist/automation-client";
import { HandleCommand } from "@atomist/automation-client/lib/HandleCommand";
import { HandleEvent } from "@atomist/automation-client/lib/HandleEvent";
import { CronJob } from "cron";
import * as _ from "lodash";
import { AdminCommunicationContext } from "../../api/context/AdminCommunicationContext";
import {
enrichGoalSetters,
GoalContribution,
goalContributors,
} from "../../api/dsl/goalContribution";
import { Goal } from "../../api/goal/Goal";
import {
ExecuteGoal,
GoalProjectListenerRegistration,
} from "../../api/goal/GoalInvocation";
import { Goals } from "../../api/goal/Goals";
import {
NoProgressReport,
ReportProgress,
} from "../../api/goal/progress/ReportProgress";
import { TriggeredListenerInvocation } from "../../api/listener/TriggeredListener";
import { validateConfigurationValues } from "../../api/machine/ConfigurationValues";
import { ExtensionPack } from "../../api/machine/ExtensionPack";
import { registrableManager } from "../../api/machine/Registerable";
import { SoftwareDeliveryMachine } from "../../api/machine/SoftwareDeliveryMachine";
import { SoftwareDeliveryMachineConfiguration } from "../../api/machine/SoftwareDeliveryMachineOptions";
import { GoalSetter } from "../../api/mapping/GoalSetter";
import { PushMapping } from "../../api/mapping/PushMapping";
import { PushTest } from "../../api/mapping/PushTest";
import { AnyPush } from "../../api/mapping/support/commonPushTests";
import { PushRules } from "../../api/mapping/support/PushRules";
import { CodeInspectionRegistration } from "../../api/registration/CodeInspectionRegistration";
import { CodeTransformRegistration } from "../../api/registration/CodeTransformRegistration";
import { CommandHandlerRegistration } from "../../api/registration/CommandHandlerRegistration";
import { EventHandlerRegistration } from "../../api/registration/EventHandlerRegistration";
import { GeneratorRegistration } from "../../api/registration/GeneratorRegistration";
import {
GoalApprovalRequestVoteDecisionManager,
GoalApprovalRequestVoter,
UnanimousGoalApprovalRequestVoteDecisionManager,
} from "../../api/registration/goalApprovalRequestVote";
import { IngesterRegistration } from "../../api/registration/IngesterRegistration";
import { InterpretLog } from "../../spi/log/InterpretedLog";
import { DefaultGoalImplementationMapper } from "../goal/DefaultGoalImplementationMapper";
import { GoalSetGoalCompletionListener } from "../listener/goalSetListener";
import { lastLinesLogInterpreter } from "../log/logInterpreters";
import { HandlerRegistrationManagerSupport } from "./HandlerRegistrationManagerSupport";
import { ListenerRegistrationManagerSupport } from "./ListenerRegistrationManagerSupport";
/**
* Abstract support class for implementing a SoftwareDeliveryMachine.
*/
export abstract class AbstractSoftwareDeliveryMachine<O extends SoftwareDeliveryMachineConfiguration = SoftwareDeliveryMachineConfiguration>
extends ListenerRegistrationManagerSupport
implements SoftwareDeliveryMachine<O> {
public abstract readonly commandHandlers: Array<Maker<HandleCommand>>;
public abstract readonly eventHandlers: Array<Maker<HandleEvent<any>>>;
public abstract readonly ingesters: string[];
public readonly extensionPacks: ExtensionPack[] = [];
protected readonly registrationManager = new HandlerRegistrationManagerSupport(this);
protected readonly disposalGoalSetters: GoalSetter[] = [];
protected readonly goalApprovalRequestVoters: GoalApprovalRequestVoter[] = [];
protected goalApprovalRequestVoteDecisionManager: GoalApprovalRequestVoteDecisionManager =
UnanimousGoalApprovalRequestVoteDecisionManager;
private pushMap: GoalSetter;
private fulfillmentMapper;
public get goalFulfillmentMapper() {
if (!this.fulfillmentMapper) {
this.fulfillmentMapper = new DefaultGoalImplementationMapper();
}
return this.fulfillmentMapper;
}
/**
* Return the PushMapping that will be used on pushes.
* Useful in testing goal setting.
* @return {PushMapping<Goals>}
*/
get pushMapping(): PushMapping<Goals> {
return this.pushMap;
}
/**
* Provide the implementation for a goal.
* The SDM will run it as soon as the goal is ready (all preconditions are met).
* If you provide a PushTest, then the SDM can assign different implementations
* to the same goal based on the code in the project.
* @param {string} implementationName
* @param {Goal} goal
* @param {ExecuteGoal} goalExecutor
* @param options PushTest to narrow matching & InterpretLog that can handle
* the log from the goalExecutor function
* @return {this}
*/
public addGoalImplementation(implementationName: string,
goal: Goal,
goalExecutor: ExecuteGoal,
options?: Partial<{
pushTest: PushTest,
logInterpreter: InterpretLog,
progressReporter: ReportProgress,
projectListeners: GoalProjectListenerRegistration | GoalProjectListenerRegistration[],
}>): this {
const implementation = {
implementationName, goal, goalExecutor,
pushTest: _.get(options, "pushTest") || AnyPush,
logInterpreter: _.get(options, "logInterpreter") || lastLinesLogInterpreter(implementationName, 10),
progressReporter: _.get(options, "progressReporter") || NoProgressReport,
projectListeners: _.get(options, "projectListeners") || [],
};
this.goalFulfillmentMapper.addImplementation(implementation);
return this;
}
public addGoalApprovalRequestVoter(vote: GoalApprovalRequestVoter): this {
this.goalApprovalRequestVoters.push(vote);
return this;
}
public setGoalApprovalRequestVoteDecisionManager(manager: GoalApprovalRequestVoteDecisionManager): this {
this.goalApprovalRequestVoteDecisionManager = manager;
return this;
}
public addCommand<P>(cmd: CommandHandlerRegistration<P>): this {
this.registrationManager.addCommand(cmd);
return this;
}
public addGeneratorCommand<P = NoParameters>(gen: GeneratorRegistration<P>): this {
this.registrationManager.addGeneratorCommand(gen);
return this;
}
public addCodeTransformCommand<P>(ed: CodeTransformRegistration<P>): this {
this.registrationManager.addCodeTransformCommand<P>(ed);
return this;
}
public addCodeInspectionCommand<R, P>(cir: CodeInspectionRegistration<R, P>): this {
this.registrationManager.addCodeInspectionCommand<R, P>(cir);
return this;
}
public addEvent<T, P>(e: EventHandlerRegistration<T, P>): this {
this.registrationManager.addEvent<T, P>(e);
return this;
}
public addIngester(i: string | IngesterRegistration): this {
if (typeof i === "string") {
this.registrationManager.addIngester({
ingester: i,
});
} else {
this.registrationManager.addIngester(i);
}
return this;
}
/**
* Declare that a goal will become successful based on something outside.
* For instance, ArtifactGoal succeeds because of an ImageLink event.
* This tells the SDM that it does not need to run anything when this
* goal becomes ready.
* @param {Goal} goal
* @param {string} sideEffectName
* @param {PushTest} pushTest
*/
public addGoalSideEffect(goal: Goal,
sideEffectName: string,
pushTest: PushTest = AnyPush): this {
this.goalFulfillmentMapper.addSideEffect({
goal,
sideEffectName, pushTest,
});
return this;
}
public addGoalContributions(goalContributions: GoalSetter): this {
if (!this.pushMap) {
this.pushMap = goalContributions;
} else {
this.pushMap = enrichGoalSetters(this.pushMap, goalContributions);
}
return this;
}
public withPushRules(contributor: GoalContribution<any>,
...contributors: Array<GoalContribution<any>>): this {
return this.addGoalContributions(goalContributors(contributor, ...contributors));
}
public addExtensionPacks(...packs: ExtensionPack[]): this {
for (const pack of packs) {
const found = this.extensionPacks.find(existing => existing.name === pack.name && existing.vendor === pack.vendor);
if (!!found) {
logger.warn("Cannot add extension pack '%s' version %s from %s: We already have version %s of it",
pack.name, pack.version, pack.vendor, found.version);
} else {
this.addExtensionPack(pack);
if (!!pack.goalContributions) {
this.addGoalContributions(pack.goalContributions);
}
}
}
return this;
}
private addExtensionPack(pack: ExtensionPack): this {
logger.info("Adding extension pack '%s' version %s from %s",
pack.name, pack.version, pack.vendor);
validateConfigurationValues(this.configuration, pack);
pack.configure(this);
this.extensionPacks.push(pack);
return this;
}
/**
* Invoke StartupListeners.
*/
public async notifyStartupListeners(): Promise<void> {
const i: AdminCommunicationContext = {
addressAdmin: this.configuration.sdm.adminAddressChannels || (async msg => {
logger.warn("startup: %j", msg);
}),
sdm: this,
};
return Promise.all(this.startupListeners.map(l => l(i)))
.then(() => {
// Empty to return void
});
}
/**
* Schedule the triggered listeners
*/
public scheduleTriggeredListeners(): void {
const i: TriggeredListenerInvocation = {
addressAdmin: this.configuration.sdm.adminAddressChannels || (async msg => {
logger.info("trigger: %j", msg);
}),
sdm: this,
};
this.triggeredListeners.forEach(t => {
if (t.trigger && t.trigger.cron) {
const cron = new CronJob({
cronTime: t.trigger.cron,
onTick: () => t.listener(i),
unrefTimeout: true,
} as any);
cron.start();
}
if (t.trigger && t.trigger.interval) {
setInterval(() => t.listener(i), t.trigger.interval).unref();
}
});
}
/**
* Construct a new software delivery machine, with zero or
* more goal setters.
* @param {string} name
* @param configuration automation client configuration we're running in
* @param {GoalSetter} goalSetters tell me what to do on a push. Hint: start with "whenPushSatisfies(...)"
*/
protected constructor(public readonly name: string,
public readonly configuration: O,
goalSetters: Array<GoalSetter | GoalSetter[]>) {
super();
registrableManager().register(this);
// If we didn't get any goal setters don't register a mapping
if (goalSetters.length > 0) {
this.pushMap = new PushRules("Goal setters", _.flatten(goalSetters));
}
// Register the triggered listener scheduler on SDM start
this.addStartupListener(() => Promise.resolve(this.scheduleTriggeredListeners()));
// Register the goal completion listenr to update goal set state
this.addGoalCompletionListener(GoalSetGoalCompletionListener);
}
}