|
1 | | -import { AbstractStartedContainer, ExecResult, GenericContainer, StartedTestContainer, Wait } from "testcontainers"; |
| 1 | +import { satisfies } from "compare-versions"; |
| 2 | +import { AbstractStartedContainer, GenericContainer, StartedTestContainer, Wait } from "testcontainers"; |
2 | 3 |
|
3 | 4 | const MONGODB_PORT = 27017; |
4 | 5 |
|
5 | 6 | export class MongoDBContainer extends GenericContainer { |
| 7 | + private username: string | undefined; |
| 8 | + private password: string | undefined; |
| 9 | + |
6 | 10 | constructor(image: string) { |
7 | 11 | super(image); |
8 | | - this.withExposedPorts(MONGODB_PORT) |
9 | | - .withCommand(["--replSet", "rs0"]) |
10 | | - .withWaitStrategy(Wait.forLogMessage(/.*waiting for connections.*/i)) |
11 | | - .withStartupTimeout(120_000); |
| 12 | + this.withExposedPorts(MONGODB_PORT).withWaitStrategy(Wait.forHealthCheck()).withStartupTimeout(120_000); |
12 | 13 | } |
13 | 14 |
|
14 | | - public override async start(): Promise<StartedMongoDBContainer> { |
15 | | - return new StartedMongoDBContainer(await super.start()); |
| 15 | + public withUsername(username: string): this { |
| 16 | + if (!username) throw new Error("Username should not be empty."); |
| 17 | + this.username = username; |
| 18 | + return this; |
16 | 19 | } |
17 | 20 |
|
18 | | - protected override async containerStarted(startedTestContainer: StartedTestContainer): Promise<void> { |
19 | | - await this.initReplicaSet(startedTestContainer); |
| 21 | + public withPassword(password: string): this { |
| 22 | + if (!password) throw new Error("Password should not be empty."); |
| 23 | + this.password = password; |
| 24 | + return this; |
20 | 25 | } |
21 | 26 |
|
22 | | - private async initReplicaSet(startedTestContainer: StartedTestContainer) { |
23 | | - await this.executeMongoEvalCommand(startedTestContainer, "rs.initiate();"); |
24 | | - await this.executeMongoEvalCommand(startedTestContainer, this.buildMongoWaitCommand()); |
| 27 | + public override async start(): Promise<StartedMongoDBContainer> { |
| 28 | + const cmdArgs = ["--replSet", "rs0"]; |
| 29 | + if (!this.healthCheck) this.withWaitForRsHealthCheck(); |
| 30 | + if (this.username && this.password) { |
| 31 | + cmdArgs.push("--keyFile", "/data/db/key.txt"); |
| 32 | + this.withEnvironment({ |
| 33 | + MONGO_INITDB_ROOT_USERNAME: this.username, |
| 34 | + MONGO_INITDB_ROOT_PASSWORD: this.password, |
| 35 | + }) |
| 36 | + .withCopyContentToContainer([ |
| 37 | + { |
| 38 | + content: "1111111111", |
| 39 | + mode: 0o400, |
| 40 | + target: "/data/db/key.txt", |
| 41 | + }, |
| 42 | + ]) |
| 43 | + .withCommand(cmdArgs); |
| 44 | + } else { |
| 45 | + this.withCommand(cmdArgs); |
| 46 | + } |
| 47 | + return new StartedMongoDBContainer(await super.start(), this.username, this.password); |
25 | 48 | } |
26 | 49 |
|
27 | | - private async executeMongoEvalCommand(startedTestContainer: StartedTestContainer, command: string) { |
28 | | - const execResult = await startedTestContainer.exec(this.buildMongoEvalCommand(command)); |
29 | | - this.checkMongoNodeExitCode(execResult); |
| 50 | + private withWaitForRsHealthCheck(): this { |
| 51 | + return this.withHealthCheck({ |
| 52 | + test: [ |
| 53 | + "CMD-SHELL", |
| 54 | + this.buildMongoEvalCommand( |
| 55 | + `'try { rs.initiate(); } catch (e){} while (db.runCommand({isMaster: 1}).ismaster==false) { sleep(100); }'` |
| 56 | + ), |
| 57 | + ], |
| 58 | + interval: 250, |
| 59 | + timeout: 60000, |
| 60 | + retries: 1000, |
| 61 | + }); |
30 | 62 | } |
31 | 63 |
|
32 | 64 | private buildMongoEvalCommand(command: string) { |
33 | | - return [this.getMongoCmdBasedOnImageTag(), "--eval", command]; |
34 | | - } |
35 | | - |
36 | | - private getMongoCmdBasedOnImageTag() { |
37 | | - return parseInt(this.imageName.tag[0]) >= 5 ? "mongosh" : "mongo"; |
38 | | - } |
39 | | - |
40 | | - private checkMongoNodeExitCode(execResult: ExecResult) { |
41 | | - const { exitCode, output } = execResult; |
42 | | - if (execResult.exitCode !== 0) { |
43 | | - throw new Error(`Error running mongo command. Exit code ${exitCode}: ${output}`); |
44 | | - } |
45 | | - } |
46 | | - |
47 | | - private buildMongoWaitCommand() { |
48 | | - return ` |
49 | | - var attempt = 0; |
50 | | - while(db.runCommand({isMaster: 1}).ismaster==false) { |
51 | | - if (attempt > 60) { |
52 | | - quit(1); |
53 | | - } |
54 | | - print(attempt); sleep(100); attempt++; |
55 | | - } |
56 | | - `; |
| 65 | + const useMongosh = satisfies(this.imageName.tag, ">=5.0.0"); |
| 66 | + const args = []; |
| 67 | + if (useMongosh) args.push("mongosh"); |
| 68 | + else args.push("mongo", "admin"); |
| 69 | + if (this.username && this.password) args.push("-u", this.username, "-p", this.password); |
| 70 | + args.push("--quiet", "--eval", command); |
| 71 | + return args.join(" "); |
57 | 72 | } |
58 | 73 | } |
59 | 74 |
|
60 | 75 | export class StartedMongoDBContainer extends AbstractStartedContainer { |
61 | | - constructor(startedTestContainer: StartedTestContainer) { |
| 76 | + private readonly username: string | undefined; |
| 77 | + private readonly password: string | undefined; |
| 78 | + |
| 79 | + constructor(startedTestContainer: StartedTestContainer, username: string | undefined, password: string | undefined) { |
62 | 80 | super(startedTestContainer); |
| 81 | + this.username = username; |
| 82 | + this.password = password; |
63 | 83 | } |
64 | 84 |
|
65 | 85 | public getConnectionString(): string { |
| 86 | + if (this.username && this.password) |
| 87 | + return `mongodb://${this.username}:${this.password}@${this.getHost()}:${this.getMappedPort(MONGODB_PORT)}?authSource=admin`; |
66 | 88 | return `mongodb://${this.getHost()}:${this.getMappedPort(MONGODB_PORT)}`; |
67 | 89 | } |
68 | 90 | } |
0 commit comments