-
Notifications
You must be signed in to change notification settings - Fork 1
/
docker-compose-testkit.ts
213 lines (193 loc) · 6.36 KB
/
docker-compose-testkit.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
import {execa, ExecaReturnValue} from 'execa'
import {cleanupContainersByEnvironmentName, cleanupOrphanEnvironments} from './cleanup.js'
import {getProjectName} from './project-name.js'
import {pullImagesFromComposeFile} from './pull-images.js'
import {
AddressOptions,
getAddressForService,
getInternalIpForService,
} from './service-compose-network.js'
import {listContainers, containerExists, Container} from './list-containers.js'
import {getLogsForService, tailLogsForServices} from './container-logs.js'
import {
startService,
stopService,
pauseService,
unpauseService,
runService,
waitForServiceToExit,
ExitOptions,
} from './container-lifecycle.js'
import debug from './debug.js'
type EnvFunc = () => string | number
type EnvAsyncFunc = () => Promise<string | number>
type Env = Record<string, string | Promise<string> | EnvFunc | EnvAsyncFunc>
export interface ComposeOptions {
servicesToStart?: string[]
tailServices?: string
projectName?: string
env?: Env
orphanCleanup?: boolean
cleanup?: boolean
pullImages?: boolean
forceKill?: boolean
containerRetentionInMinutes?: number
}
export interface Compose {
projectName: string
pathToCompose: string
pullImages: () => Promise<string[]>
setup: () => Promise<void>
teardown: () => Promise<void>
getAddressForService: (
serviceName: string,
exposedPort: number,
options?: AddressOptions,
) => Promise<string>
getInternalIpForService: (serviceName: string) => Promise<string>
listContainers: () => Promise<Container[]>
containerExists: (serviceName: string) => Promise<boolean>
getLogsForService: (serviceName: string) => Promise<string>
waitForServiceToExit: (serviceName: string, options?: ExitOptions) => Promise<void>
runService: (serviceName: string, commandWithArgs: string[]) => Promise<ExecaReturnValue<string>>
startService: (serviceName: string) => Promise<void>
stopService: (serviceName: string) => Promise<void>
pauseService: (serviceName: string) => Promise<void>
unpauseService: (serviceName: string) => Promise<void>
}
export function compose(pathToCompose: string, options?: ComposeOptions): Compose {
const {
servicesToStart,
tailServices,
projectName,
env,
orphanCleanup,
cleanup,
pullImages: pullImagesConfig,
forceKill,
containerRetentionInMinutes,
} = {
servicesToStart: [],
env: {},
orphanCleanup: true,
cleanup: true,
pullImages: false,
forceKill: true,
containerRetentionInMinutes: 5,
...options,
}
const {project, displayName} = getProjectName(projectName)
const log = debug(`docker-compose-testkit:info:${displayName}`)
let killTailProcess: any = undefined
const finalEnv: Record<string, string> = {path: process.env.PATH as string}
let finalEnvAssembled = false
async function assembleFinalEnv() {
if (!finalEnvAssembled) {
// Keep the pointer to finalEnv to not break the bind for runService
Object.entries(await replaceFunctionsWithTheirValues(env)).forEach(([k, v]) => {
finalEnv[k] = v
})
}
finalEnvAssembled = true
}
async function pullImages() {
await assembleFinalEnv()
return pullImagesFromComposeFile({
pathToCompose,
servicesToStart,
env: finalEnv,
})
}
async function setup() {
if (orphanCleanup) {
await cleanupOrphanEnvironments(containerRetentionInMinutes)
}
const onlyTheseServicesMessage = servicesToStart.length
? `, using only these services: ${servicesToStart.join(',')}`
: ''
const consoleMessage = `starting up runtime environment for this run (codenamed: ${displayName})${onlyTheseServicesMessage}... `
log(consoleMessage)
await assembleFinalEnv()
if (pullImagesConfig) {
await pullImagesFromComposeFile({
pathToCompose,
servicesToStart,
env: finalEnv,
})
}
try {
await execa(
'docker',
['compose', '-p', project, '-f', pathToCompose, 'up', '-d', ...servicesToStart],
{env: finalEnv},
)
} catch (err) {
const error = err as any
if (
!error.stderr.includes('no service selected') &&
!error.stderr.includes('empty compose file')
) {
throw error
}
log(error.stderr)
}
//if (tailServices === true || (Array.isArray(tailServices) && tailServices.length)) {
if (tailServices) {
killTailProcess = tailLogsForServices(project, pathToCompose, [tailServices], process.stdout)
}
}
async function teardown() {
if (killTailProcess) {
await killTailProcess()
}
if (cleanup) {
await cleanupContainersByEnvironmentName(project, pathToCompose, {
displayName,
forceKill,
log,
env: finalEnv,
})
}
}
return {
projectName: project,
pathToCompose,
pullImages,
setup,
teardown,
getAddressForService: getAddressForService.bind(undefined, project, pathToCompose),
getInternalIpForService: getInternalIpForService.bind(undefined, project, pathToCompose),
listContainers: listContainers.bind(undefined, project, pathToCompose),
containerExists: containerExists.bind(undefined, project, pathToCompose),
getLogsForService: getLogsForService.bind(undefined, project, pathToCompose),
waitForServiceToExit: waitForServiceToExit.bind(undefined, project, pathToCompose),
runService: runService.bind(undefined, project, pathToCompose, finalEnv),
startService: startService.bind(undefined, project, pathToCompose),
stopService: stopService.bind(undefined, project, pathToCompose),
pauseService: pauseService.bind(undefined, project, pathToCompose),
unpauseService: unpauseService.bind(undefined, project, pathToCompose),
}
}
export default compose
export type {Container, Publisher, State} from './list-containers.js'
async function replaceFunctionsWithTheirValues(env: Env): Promise<Record<string, string>> {
return (
await Promise.all(
Object.entries(env).map(([k, v]) => {
if (typeof v === 'function') {
return Promise.resolve(v()).then((f) => [k, f.toString()])
} else if (typeof (v as any)?.then === 'function') {
return (v as any).then((f: any) => [k, f.toString()])
} else {
return [k, v]
}
}),
)
).reduce(
(finalEnv, [key, value]) => {
finalEnv[key] = value
return finalEnv
},
{} as Record<string, string>,
)
}