This repository has been archived by the owner on Jul 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mavenDeployer.ts
249 lines (224 loc) · 8.09 KB
/
mavenDeployer.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
/*
* Copyright © 2019 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 {
LocalProject,
logger,
ProjectOperationCredentials,
RemoteRepoRef,
} from "@atomist/automation-client";
import {
DelimitedWriteProgressLogDecorator,
DeployableArtifact,
Deployer,
InterpretedLog,
InterpretLog,
ProgressLog,
ProjectLoader,
} from "@atomist/sdm";
import {
DefaultLocalDeployerOptions,
LocalDeployerOptions,
LookupStrategy,
ManagedDeployments,
ManagedDeploymentTargetInfo,
SpawnedDeployment,
} from "@atomist/sdm-core";
import { Deployment } from "@atomist/sdm/lib/spi/deploy/Deployment";
import * as spawn from "cross-spawn";
import { MavenOptions } from "../build/helpers";
import { determineMavenCommand } from "../mavenCommand";
/**
* Managed deployments
*/
export let managedMavenDeployments: ManagedDeployments;
/**
* Use Maven to deploy
* @param projectLoader use to load projects
* @param opts options
*/
export function mavenDeployer(
projectLoader: ProjectLoader,
opts: LocalDeployerOptions,
): Deployer<ManagedDeploymentTargetInfo> {
if (!managedMavenDeployments) {
logger.debug("Created new deployments record");
managedMavenDeployments = new ManagedDeployments(opts.lowerPort);
}
return new MavenSourceDeployer(projectLoader, {
...DefaultLocalDeployerOptions,
...opts,
});
}
/**
* Source deployer that uses Maven target
*/
class MavenSourceDeployer implements Deployer<ManagedDeploymentTargetInfo> {
constructor(public readonly projectLoader: ProjectLoader, public readonly opts: LocalDeployerOptions) {
}
public async findDeployments(
id: RemoteRepoRef,
ti: ManagedDeploymentTargetInfo,
creds: ProjectOperationCredentials,
): Promise<Deployment[]> {
const deployedApp = managedMavenDeployments.findDeployment(
ti.managedDeploymentKey,
this.opts.lookupStrategy || LookupStrategy.branch);
if (!deployedApp) {
return [];
}
return [deployedApp.deployment];
}
public async deploy(da: DeployableArtifact,
ti: ManagedDeploymentTargetInfo,
log: ProgressLog,
credentials: ProjectOperationCredentials,
team: string): Promise<SpawnedDeployment[]> {
const id = da.id;
if (!id.branch) {
throw new Error(`Cannot locally deploy ${JSON.stringify(id)}: Branch must be set`);
}
const port = await managedMavenDeployments.findPort(ti.managedDeploymentKey, LookupStrategy.branch,
this.opts.baseUrl);
logger.info("MavenSourceDeployer: Deploying app [%j],branch=%s on port [%d] for team %s", id,
ti.managedDeploymentKey.branch, port, team);
await managedMavenDeployments.terminateIfRunning(ti.managedDeploymentKey, LookupStrategy.branch);
return [await this.projectLoader.doWithProject({ credentials, id, readOnly: true },
project => this.deployProject(ti, log, project, port, team))];
}
public async undeploy(
ti: ManagedDeploymentTargetInfo,
deployment: Deployment,
log: ProgressLog,
): Promise<void> {
await managedMavenDeployments.terminateIfRunning(ti.managedDeploymentKey, LookupStrategy.branch);
return;
}
public logInterpreter(log: string): InterpretedLog | undefined {
return springBootRunLogInterpreter(log) || shortLogInterpreter(log);
}
private async deployProject(ti: ManagedDeploymentTargetInfo,
log: ProgressLog,
project: LocalProject,
port: number,
atomistTeam: string): Promise<SpawnedDeployment> {
const branchId = ti.managedDeploymentKey;
const startupInfo = {
port,
atomistTeam,
contextRoot: `/${branchId.owner}/${branchId.repo}/${branchId.branch}`,
};
const mvn = await determineMavenCommand(project);
const childProcess = spawn(mvn,
[
"spring-boot:run",
...MavenOptions,
].concat(this.opts.commandLineArgumentsFor(startupInfo)),
{
cwd: project.baseDir,
});
if (!childProcess.pid) {
throw new Error("Fatal error deploying using Maven--is `mvn` on your automation node path?\n" +
`Attempted to execute '${mvn} spring-boot:run' in ${project.baseDir}`);
}
const deployment = {
childProcess,
endpoint: `${this.opts.baseUrl}:${port}/${startupInfo.contextRoot}`,
};
managedMavenDeployments.recordDeployment({
id: branchId,
port,
childProcess,
deployment,
lookupStrategy: LookupStrategy.branch,
});
const newLineDelimitedLog = new DelimitedWriteProgressLogDecorator(log, "\n");
childProcess.stdout.on("data", what => newLineDelimitedLog.write(what.toString()));
childProcess.stderr.on("data", what => newLineDelimitedLog.write(what.toString()));
return new Promise<SpawnedDeployment>((resolve, reject) => {
childProcess.stdout.addListener("data", what => {
if (!!what && this.opts.successPatterns.some(successPattern => successPattern.test(what.toString()))) {
resolve(deployment);
}
});
childProcess.addListener("exit", () => {
reject(new Error("We should have found success message pattern by now!!"));
});
childProcess.addListener("error", reject);
});
}
}
const shortLogInterpreter: InterpretLog = (log: string) => {
if (log.length < 200) {
return {
relevantPart: log,
message: "This is the whole log.",
includeFullLog: false,
};
}
return undefined;
};
const springBootRunLogInterpreter: InterpretLog = (log: string) => {
logger.debug("Interpreting log");
if (!log) {
logger.warn("log was empty");
return undefined;
}
const maybeFailedToStart = appFailedToStart(log);
if (maybeFailedToStart) {
return {
relevantPart: maybeFailedToStart,
message: "Application failed to start",
includeFullLog: false,
};
}
// default to maven errors
const maybeMavenErrors = mavenErrors(log);
if (maybeMavenErrors) {
logger.info("recognized maven error");
return {
relevantPart: maybeMavenErrors,
message: "Maven errors",
};
}
// or it could be this problem here
if (log.match(/Error checking out artifact/)) {
logger.info("Recognized artifact error");
return {
relevantPart: log,
message: "I lost the local cache. Please rebuild",
includeFullLog: false,
};
}
logger.info("Did not find anything to recognize in the log");
return undefined;
};
function appFailedToStart(log: string) {
const lines = log.split("\n");
const failedToStartLine = lines.indexOf("APPLICATION FAILED TO START");
if (failedToStartLine < 1) {
return undefined;
}
const likelyLines = lines.slice(failedToStartLine + 3, failedToStartLine + 10);
return likelyLines.join("\n");
}
function mavenErrors(log: string): string {
if (log.match(/^\[ERROR]/m)) {
return log.split("\n")
.filter(l => l.startsWith("[ERROR]"))
.join("\n");
}
return undefined;
}