forked from cardano-foundation/cardano-rosetta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker.ts
94 lines (80 loc) · 2.57 KB
/
docker.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
import Docker from 'dockerode';
import { containerExec, imageExists, pullImageAsync } from 'dockerode-utils';
import path from 'path';
const CONTAINER_IMAGE = 'postgres:11.5-alpine';
const CONTAINER_TEMP_DIR = '/tmp';
const CONTAINER_NAME = 'cardano-test';
export const removePostgresContainer = async (): Promise<void> => {
const docker = new Docker();
const container = await docker.getContainer(CONTAINER_NAME);
await container.stop();
await container.remove({ v: true });
};
interface DatabaseConfig {
database: string;
snapshot: boolean;
fixture: boolean;
}
const setupDBData = async (databaseConfig: DatabaseConfig, user: string, container: Docker.Container) => {
const database = databaseConfig.database;
await containerExec(container, ['bash', '-c', `psql -U ${user} -c "CREATE DATABASE ${database}"`]);
if (databaseConfig.snapshot) {
await container.putArchive(path.join(__dirname, `${database}-db-snapshot.tar`), {
path: CONTAINER_TEMP_DIR,
User: 'root'
});
// Execute backup restore
await containerExec(container, [
'bash',
'-c',
`cat ${CONTAINER_TEMP_DIR}/${database}.bak | psql -U ${user} ${database}`
]);
}
if (databaseConfig.fixture) {
await container.putArchive(path.join(__dirname, `${database}-fixture-data.tar`), {
path: CONTAINER_TEMP_DIR,
User: 'root'
});
await containerExec(container, [
'bash',
'-c',
`cat ${CONTAINER_TEMP_DIR}/${database}-fixture-data.sql | psql -U ${user} ${database}`
]);
}
};
export const setupPostgresContainer = async (user: string, password: string, port: string): Promise<void> => {
const docker = new Docker();
const needsToPull = !(await imageExists(docker, CONTAINER_IMAGE));
if (needsToPull) await pullImageAsync(docker, CONTAINER_IMAGE);
const container = await docker.createContainer({
Image: CONTAINER_IMAGE,
Env: [`POSTGRES_PASSWORD=${password}`, `POSTGRES_USER=${user}`],
HostConfig: {
PortBindings: {
'5432/tcp': [
{
HostPort: port
}
]
}
},
name: CONTAINER_NAME
});
await container.start();
// Wait for the db service to be running (container started event is not enough)
await containerExec(container, [
'bash',
'-c',
`until psql -U ${user} -c "select 1" > /dev/null 2>&1 ; do sleep 1; done`
]);
const databaseConfigs = [
{
snapshot: true,
fixture: true,
database: 'mainnet'
}
];
for (const databaseConfig of databaseConfigs) {
await setupDBData(databaseConfig, user, container);
}
};