-
Notifications
You must be signed in to change notification settings - Fork 3
/
ManagedDeployments.ts
194 lines (173 loc) · 5.79 KB
/
ManagedDeployments.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
/*
* 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.
*/
// tslint:disable:deprecation
import {
configurationValue,
DefaultHttpClientFactory,
HttpClientFactory,
HttpMethod,
logger,
RemoteRepoRef,
RepoRef,
} from "@atomist/automation-client";
import {
killAndWait,
Targeter,
} from "@atomist/sdm";
import {
Deployment,
TargetInfo,
} from "@atomist/sdm/lib/spi/deploy/Deployment";
import { ChildProcess } from "child_process";
import * as https from "https";
/**
* @ModuleExport
* @deprecated
*/
export interface ManagedDeploymentTargetInfo extends TargetInfo {
managedDeploymentKey: RemoteRepoRef;
}
/**f
* @ModuleExport
* @deprecated
*/
export const ManagedDeploymentTargeter: Targeter<ManagedDeploymentTargetInfo> = (id: RemoteRepoRef, branch: string) => {
const branchId = { ...id, branch };
return {
name: "Run alongside this automation",
description: `Locally run ${id.sha} from branch ${branch}`,
managedDeploymentKey: branchId,
};
};
/**
* Strategy for looking up a service
* @ModuleExport
* @deprecated
*/
export enum LookupStrategy {
service = "service",
branch = "branch",
sha = "sha",
}
/**
* Ports will be reused for the same app
* @ModuleExport
* @deprecated
*/
export interface DeployedApp {
id: RepoRef;
port: number;
/** Will be undefined if the app is not currently deployed */
childProcess: ChildProcess;
deployment: Deployment;
lookupStrategy: LookupStrategy;
}
/**
* Manages local deployments to the automation server node
* This is not intended for production use
* @type {Array}
* @ModuleExport
* @deprecated
*/
export class ManagedDeployments {
public readonly deployments: DeployedApp[] = [];
constructor(public initialPort: number) {
}
/**
* Find the appropriate port for this app
* @param {RemoteRepoRef} id
* @param lookupStrategy strategy for looking up the instance
* @param host it will be on. Check for ports not in use
* @return {number}
*/
public async findPort(id: RemoteRepoRef, lookupStrategy: LookupStrategy, host: string): Promise<number> {
const running = this.findDeployment(id, lookupStrategy);
return !!running ? running.port : this.nextFreePort(host);
}
public recordDeployment(da: DeployedApp): void {
logger.info("Recording app [%s:%s] on port [%d]", da.id.owner, da.id.repo, da.port);
this.deployments.push(da);
}
public findDeployment(id: RemoteRepoRef, lookupStrategy: LookupStrategy): DeployedApp {
switch (lookupStrategy) {
case LookupStrategy.sha:
if (!id.sha) {
throw new Error("Sha should have been set to use 'sha' LookupStrategy");
}
// Probability of a sha collision is tiny
return this.deployments.find(d => d.id.sha === id.sha);
case LookupStrategy.branch:
if (!id.branch) {
throw new Error("Branch should have been set to use 'branch' LookupStrategy");
}
return this.deployments
.find(d => d.id.owner === id.owner && d.id.repo === id.repo && d.id.branch === id.branch);
case LookupStrategy.service:
return this.deployments
.find(d => d.id.owner === id.owner && d.id.repo === id.repo);
default:
return undefined;
}
}
/**
* Terminate any process we're managing on behalf of this id
* @param {RemoteRepoRef} id
* @param lookupStrategy strategy for finding the instance
* @return {Promise<any>}
*/
public async terminateIfRunning(id: RemoteRepoRef, lookupStrategy: LookupStrategy): Promise<any> {
const victim = this.findDeployment(id, lookupStrategy);
if (!!victim && !!victim.childProcess) {
await killAndWait(victim.childProcess);
// Keep the port but deallocate the process
logger.info("Killed app [%j] with pid %d, but continuing to reserve port [%d]",
id, victim.childProcess.pid, victim.port);
victim.childProcess = undefined;
} else {
logger.info("Was asked to kill app [%j], but no eligible process found", id);
}
}
private async nextFreePort(host: string): Promise<number> {
let port = this.initialPort;
while (true) {
if (this.deployments.some(d => d.port === port)) {
port++;
} else if (await portIsInUse(host, port)) {
// Skip this port, too
logger.warn("Unexpected: %s is serving on port %d", host, port);
port++;
} else {
break;
}
}
return port;
}
}
export async function portIsInUse(host: string, port: number): Promise<boolean> {
const httpClient = configurationValue<HttpClientFactory>("http.client.factory", DefaultHttpClientFactory).create();
const agent = new https.Agent({
rejectUnauthorized: false,
});
try {
await httpClient.exchange(`${host}:${port}`, {
method: HttpMethod.Head,
options: { httpsAgent: agent },
});
return true;
} catch {
return false;
}
}