-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathdockerode.ts
242 lines (210 loc) · 6.35 KB
/
dockerode.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
import fs from "fs";
import { Logger } from "@waku/utils";
import Docker from "dockerode";
import { Args, Ports } from "../types.js";
const log = new Logger("test:docker");
const NETWORK_NAME = "waku";
const SUBNET = "172.18.0.0/16";
const IP_RANGE = "172.18.0.0/24";
const GATEWAY = "172.18.0.1";
export default class Dockerode {
public docker: Docker;
private readonly IMAGE_NAME: string;
public containerId?: string;
private static network: Docker.Network;
public readonly containerIp: string;
private constructor(imageName: string, containerIp: string) {
this.docker = new Docker();
this.IMAGE_NAME = imageName;
this.containerIp = containerIp;
}
public static async createInstance(imageName: string): Promise<Dockerode> {
if (!Dockerode.network) {
Dockerode.network = await Dockerode.createNetwork(NETWORK_NAME);
}
const instance = new Dockerode(imageName, Dockerode.getNextIp());
return instance;
}
private static async createNetwork(
networkName: string = NETWORK_NAME
): Promise<Docker.Network> {
const docker = new Docker();
const networks = await docker.listNetworks();
const existingNetwork = networks.find(
(network) => network.Name === networkName
);
let network: Docker.Network;
if (existingNetwork) {
network = docker.getNetwork(existingNetwork.Id);
} else {
network = await docker.createNetwork({
Name: networkName,
Driver: "bridge",
IPAM: {
Driver: "default",
Config: [
{
Subnet: SUBNET,
IPRange: IP_RANGE,
Gateway: GATEWAY
}
]
}
});
}
return network;
}
private static getNextIp(): string {
const baseIpFragments = "172.18".split(".");
// Generate a random number between 0 and 255 for the last two fragments.
const secondLastFragment = Math.floor(Math.random() * 256); // For the .0 fragment
const lastFragment = Math.floor(Math.random() * 256); // For the last fragment
const newIp = [...baseIpFragments, secondLastFragment, lastFragment].join(
"."
);
return newIp;
}
public get container(): Docker.Container | undefined {
if (!this.containerId) {
return undefined;
}
return this.docker.getContainer(this.containerId);
}
public async startContainer(
ports: Ports,
args: Args,
logPath: string,
wakuServiceNodeParams?: string
): Promise<Docker.Container> {
const { restPort, tcpPort, websocketPort, discv5UdpPort } = ports;
await this.confirmImageExistsOrPull();
const argsArray = argsToArray(args);
if (wakuServiceNodeParams) {
argsArray.push(wakuServiceNodeParams);
}
const argsArrayWithIP = [...argsArray, `--nat=extip:${this.containerIp}`];
log.info(`Running node with args: ${argsArray.join(" ")}`);
const container = await this.docker.createContainer({
Image: this.IMAGE_NAME,
HostConfig: {
NetworkMode: NETWORK_NAME,
AutoRemove: true,
PortBindings: {
[`${restPort}/tcp`]: [{ HostPort: restPort.toString() }],
[`${tcpPort}/tcp`]: [{ HostPort: tcpPort.toString() }],
[`${websocketPort}/tcp`]: [{ HostPort: websocketPort.toString() }],
...(args?.peerExchange && {
[`${discv5UdpPort}/udp`]: [{ HostPort: discv5UdpPort.toString() }]
})
},
Dns: ["8.8.8.8"],
Links: [],
Mounts: args.rlnRelayEthClientAddress
? [
{
Type: "bind",
ReadOnly: false,
Source: "/tmp/rln_tree.db",
Target: "/rln_tree.db"
}
]
: []
},
ExposedPorts: {
[`${restPort}/tcp`]: {},
[`${tcpPort}/tcp`]: {},
[`${websocketPort}/tcp`]: {},
...(args?.peerExchange && {
[`${discv5UdpPort}/udp`]: {}
})
},
Cmd: argsArrayWithIP,
NetworkingConfig: {
EndpointsConfig: {
[NETWORK_NAME]: {
IPAMConfig: {
IPv4Address: this.containerIp
}
}
}
}
});
await container.start();
const logStream = fs.createWriteStream(logPath);
container.logs(
{ follow: true, stdout: true, stderr: true },
(err, stream) => {
if (err) {
throw err;
}
if (stream) {
stream.pipe(logStream);
}
}
);
this.containerId = container.id;
log.info(
`${this.containerId} started at ${new Date().toLocaleTimeString()}`
);
return container;
}
public async stop(): Promise<void> {
if (!this.container) {
log.error("ContainerId not set");
} else {
log.info(
`Shutting down container ID ${
this.containerId
} at ${new Date().toLocaleTimeString()}`
);
await this.container.stop();
delete this.containerId;
}
}
private async confirmImageExistsOrPull(): Promise<void> {
log.info(`Confirming that image ${this.IMAGE_NAME} exists`);
const doesImageExist = this.docker.getImage(this.IMAGE_NAME);
if (!doesImageExist) {
await new Promise<void>((resolve, reject) => {
this.docker.pull(this.IMAGE_NAME, {}, (err, stream) => {
if (err) {
reject(err);
}
if (stream === undefined) {
reject(new Error("Stream is undefined"));
return;
}
this.docker.modem.followProgress(stream, (err, result) => {
if (err) {
reject(err);
}
if (result) {
resolve();
}
});
});
});
}
log.info(`Image ${this.IMAGE_NAME} successfully found`);
}
}
export function argsToArray(args: Args): Array<string> {
const array = [];
for (const [key, value] of Object.entries(args)) {
// Change the key from camelCase to kebab-case
const kebabKey = key.replace(/([A-Z])/g, (_, capital) => {
return "-" + capital.toLowerCase();
});
if (Array.isArray(value)) {
// If the value is an array, create separate arguments for each element
value.forEach((val) => {
array.push(`--${kebabKey}=${val}`);
});
} else {
// Handle non-array values as before
const arg = `--${kebabKey}=${value}`;
array.push(arg);
}
}
return array;
}