1
0
Fork 0
mirror of synced 2024-09-16 01:07:19 +12:00
budibase/packages/backend-core/tests/core/utilities/testContainerUtils.ts

99 lines
2.3 KiB
TypeScript
Raw Normal View History

import { execSync } from "child_process"
let dockerPsResult: string | undefined
function formatDockerPsResult(serverName: string, port: number) {
const lines = dockerPsResult?.split("\n")
let first = true
if (!lines) {
return null
}
for (let line of lines) {
if (first) {
first = false
continue
}
let toLookFor = serverName.split("-service")[0]
if (!line.includes(toLookFor)) {
continue
}
const regex = new RegExp(`0.0.0.0:([0-9]*)->${port}`, "g")
const found = line.match(regex)
if (found) {
return found[0].split(":")[1].split("->")[0]
}
}
return null
}
function getTestContainerSettings(
serverName: string,
key: string
): string | null {
2023-02-02 04:02:31 +13:00
const entry = Object.entries(global).find(
2023-02-01 00:23:26 +13:00
([k]) =>
k.includes(`_${serverName.toUpperCase()}`) &&
k.includes(`_${key.toUpperCase()}__`)
2023-02-02 04:02:31 +13:00
)
if (!entry) {
return null
}
return entry[1]
2023-02-01 00:23:26 +13:00
}
2023-02-07 02:07:21 +13:00
function getContainerInfo(containerName: string, port: number) {
let assignedPort = getTestContainerSettings(
2023-02-07 02:07:21 +13:00
containerName.toUpperCase(),
`PORT_${port}`
)
if (!dockerPsResult) {
try {
const outputBuffer = execSync("docker ps")
dockerPsResult = outputBuffer.toString("utf8")
} catch (err) {
//no-op
}
}
const possiblePort = formatDockerPsResult(containerName, port)
if (possiblePort) {
assignedPort = possiblePort
}
2023-02-07 02:07:21 +13:00
const host = getTestContainerSettings(containerName.toUpperCase(), "IP")
2023-02-01 00:23:26 +13:00
return {
2023-02-07 02:07:21 +13:00
port: assignedPort,
host,
url: host && assignedPort && `http://${host}:${assignedPort}`,
2023-02-01 00:23:26 +13:00
}
}
2023-02-07 02:07:21 +13:00
function getCouchConfig() {
return getContainerInfo("couchdb-service", 5984)
}
2023-02-01 00:23:26 +13:00
function getMinioConfig() {
2023-02-07 02:07:21 +13:00
return getContainerInfo("minio-service", 9000)
}
function getRedisConfig() {
return getContainerInfo("redis-service", 6379)
}
2023-02-01 00:23:26 +13:00
export function setupEnv(...envs: any[]) {
const couch = getCouchConfig(),
minio = getMinioConfig(),
redis = getRedisConfig()
2023-02-01 00:23:26 +13:00
const configs = [
{ key: "COUCH_DB_PORT", value: couch.port },
{ key: "COUCH_DB_URL", value: couch.url },
{ key: "MINIO_PORT", value: minio.port },
{ key: "MINIO_URL", value: minio.url },
{ key: "REDIS_URL", value: redis.url },
2023-02-01 00:23:26 +13:00
]
for (const config of configs.filter(x => !!x.value)) {
2023-02-01 00:23:26 +13:00
for (const env of envs) {
env._set(config.key, config.value)
}
}
}