|
| 1 | +import type { EventEmitter } from "events"; |
| 2 | +import { Optional } from "typescript-optional"; |
| 3 | +import { RuntimeError } from "run-time-error"; |
| 4 | +import type { Container, ContainerInfo } from "dockerode"; |
| 5 | +import Docker from "dockerode"; |
| 6 | +import { Logger, Checks, Bools } from "@hyperledger/cactus-common"; |
| 7 | +import type { LogLevelDesc } from "@hyperledger/cactus-common"; |
| 8 | +import { LoggerProvider } from "@hyperledger/cactus-common"; |
| 9 | +import { Containers } from "../common/containers"; |
| 10 | + |
| 11 | +export interface ISubstrateTestLedgerOptions { |
| 12 | + readonly publishAllPorts: boolean; |
| 13 | + readonly logLevel?: LogLevelDesc; |
| 14 | + readonly imageName?: string; |
| 15 | + readonly imageTag?: string; |
| 16 | + readonly emitContainerLogs?: boolean; |
| 17 | + readonly envVars?: Map<string, string>; |
| 18 | +} |
| 19 | + |
| 20 | +export class SubstrateTestLedger { |
| 21 | + public static readonly CLASS_NAME = "SubstrateTestLedger"; |
| 22 | + |
| 23 | + public readonly logLevel: LogLevelDesc; |
| 24 | + public readonly imageName: string; |
| 25 | + public readonly imageTag: string; |
| 26 | + public readonly imageFqn: string; |
| 27 | + public readonly log: Logger; |
| 28 | + public readonly emitContainerLogs: boolean; |
| 29 | + public readonly publishAllPorts: boolean; |
| 30 | + public readonly envVars: Map<string, string>; |
| 31 | + |
| 32 | + private _containerId: Optional<string>; |
| 33 | + |
| 34 | + public get containerId(): Optional<string> { |
| 35 | + return this._containerId; |
| 36 | + } |
| 37 | + |
| 38 | + public get container(): Optional<Container> { |
| 39 | + const docker = new Docker(); |
| 40 | + return this.containerId.isPresent() |
| 41 | + ? Optional.ofNonNull(docker.getContainer(this.containerId.get())) |
| 42 | + : Optional.empty(); |
| 43 | + } |
| 44 | + |
| 45 | + public get className(): string { |
| 46 | + return SubstrateTestLedger.CLASS_NAME; |
| 47 | + } |
| 48 | + |
| 49 | + constructor(public readonly opts: ISubstrateTestLedgerOptions) { |
| 50 | + const fnTag = `${this.className}#constructor()`; |
| 51 | + Checks.truthy(opts, `${fnTag} arg options`); |
| 52 | + |
| 53 | + this.publishAllPorts = opts.publishAllPorts; |
| 54 | + this._containerId = Optional.empty(); |
| 55 | + this.imageName = |
| 56 | + opts.imageName || "ghcr.io/hyperledger/cactus-substrate-all-in-one"; |
| 57 | + this.imageTag = opts.imageTag || "2021-09-24---feat-1274"; |
| 58 | + this.imageFqn = `${this.imageName}:${this.imageTag}`; |
| 59 | + this.envVars = opts.envVars || new Map(); |
| 60 | + this.emitContainerLogs = Bools.isBooleanStrict(opts.emitContainerLogs) |
| 61 | + ? (opts.emitContainerLogs as boolean) |
| 62 | + : true; |
| 63 | + |
| 64 | + this.logLevel = opts.logLevel || "INFO"; |
| 65 | + |
| 66 | + const level = this.logLevel; |
| 67 | + const label = this.className; |
| 68 | + this.log = LoggerProvider.getOrCreate({ level, label }); |
| 69 | + |
| 70 | + this.log.debug(`Created instance of ${this.className} OK`); |
| 71 | + } |
| 72 | + public getContainerImageName(): string { |
| 73 | + return `${this.imageName}:${this.imageTag}`; |
| 74 | + } |
| 75 | + public async start(omitPull = false): Promise<Container> { |
| 76 | + const docker = new Docker(); |
| 77 | + if (this.containerId.isPresent()) { |
| 78 | + this.log.debug(`Container ID provided. Will not start new one.`); |
| 79 | + const container = docker.getContainer(this.containerId.get()); |
| 80 | + return container; |
| 81 | + } |
| 82 | + if (!omitPull) { |
| 83 | + this.log.debug(`Pulling image ${this.imageFqn}...`); |
| 84 | + await Containers.pullImage(this.imageFqn); |
| 85 | + this.log.debug(`Pulled image ${this.imageFqn} OK`); |
| 86 | + } |
| 87 | + |
| 88 | + const dockerEnvVars: string[] = new Array(...this.envVars).map( |
| 89 | + (pairs) => `${pairs[0]}=${pairs[1]}`, |
| 90 | + ); |
| 91 | + |
| 92 | + // TODO: dynamically expose ports for custom port mapping |
| 93 | + const createOptions = { |
| 94 | + Env: dockerEnvVars, |
| 95 | + Healthcheck: { |
| 96 | + Test: [ |
| 97 | + "CMD-SHELL", |
| 98 | + `rustup --version && rustc --version && cargo --version`, |
| 99 | + ], |
| 100 | + Interval: 1000000000, // 1 second |
| 101 | + Timeout: 3000000000, // 3 seconds |
| 102 | + Retries: 10, |
| 103 | + StartPeriod: 1000000000, // 1 second |
| 104 | + }, |
| 105 | + ExposedPorts: { |
| 106 | + "9944/tcp": {}, // OpenSSH Server - TCP |
| 107 | + }, |
| 108 | + HostConfig: { |
| 109 | + AutoRemove: true, |
| 110 | + PublishAllPorts: this.publishAllPorts, |
| 111 | + Privileged: false, |
| 112 | + PortBindings: { |
| 113 | + "9944/tcp": [{ HostPort: "9944" }], |
| 114 | + }, |
| 115 | + }, |
| 116 | + }; |
| 117 | + |
| 118 | + this.log.debug(`Starting ${this.imageFqn} with options: `, createOptions); |
| 119 | + |
| 120 | + return new Promise<Container>((resolve, reject) => { |
| 121 | + const eventEmitter: EventEmitter = docker.run( |
| 122 | + this.imageFqn, |
| 123 | + [], |
| 124 | + [], |
| 125 | + createOptions, |
| 126 | + {}, |
| 127 | + (err: Error) => { |
| 128 | + if (err) { |
| 129 | + const errorMessage = `Failed to start container ${this.imageFqn}`; |
| 130 | + const exception = new RuntimeError(errorMessage, err); |
| 131 | + this.log.error(exception); |
| 132 | + reject(exception); |
| 133 | + } |
| 134 | + }, |
| 135 | + ); |
| 136 | + |
| 137 | + eventEmitter.once("start", async (container: Container) => { |
| 138 | + const { id } = container; |
| 139 | + this.log.debug(`Started ${this.imageFqn} successfully. ID=${id}`); |
| 140 | + this._containerId = Optional.ofNonNull(id); |
| 141 | + |
| 142 | + if (this.emitContainerLogs) { |
| 143 | + const logOptions = { follow: true, stderr: true, stdout: true }; |
| 144 | + const logStream = await container.logs(logOptions); |
| 145 | + logStream.on("data", (data: Buffer) => { |
| 146 | + const fnTag = `[${this.imageFqn}]`; |
| 147 | + this.log.debug(`${fnTag} %o`, data.toString("utf-8")); |
| 148 | + }); |
| 149 | + } |
| 150 | + this.log.debug(`Registered container log stream callbacks OK`); |
| 151 | + |
| 152 | + try { |
| 153 | + this.log.debug(`Starting to wait for healthcheck... `); |
| 154 | + await Containers.waitForHealthCheck(this.containerId.get()); |
| 155 | + this.log.debug(`Healthcheck passed OK`); |
| 156 | + resolve(container); |
| 157 | + } catch (ex) { |
| 158 | + this.log.error(ex); |
| 159 | + reject(ex); |
| 160 | + } |
| 161 | + }); |
| 162 | + }); |
| 163 | + } |
| 164 | + |
| 165 | + public async stop(): Promise<unknown> { |
| 166 | + return Containers.stop(this.container.get()); |
| 167 | + } |
| 168 | + |
| 169 | + public async destroy(): Promise<unknown> { |
| 170 | + return this.container.get().remove(); |
| 171 | + } |
| 172 | + |
| 173 | + public async getContainerIpAddress(): Promise<string> { |
| 174 | + const containerInfo = await this.getContainerInfo(); |
| 175 | + return Containers.getContainerInternalIp(containerInfo); |
| 176 | + } |
| 177 | + |
| 178 | + protected async getContainerInfo(): Promise<ContainerInfo> { |
| 179 | + const fnTag = "FabricTestLedgerV1#getContainerInfo()"; |
| 180 | + const docker = new Docker(); |
| 181 | + const image = this.getContainerImageName(); |
| 182 | + const containerInfos = await docker.listContainers({}); |
| 183 | + |
| 184 | + let aContainerInfo; |
| 185 | + if (this.containerId !== undefined) { |
| 186 | + aContainerInfo = containerInfos.find( |
| 187 | + (ci) => ci.Id == this.containerId.toString(), |
| 188 | + ); |
| 189 | + } |
| 190 | + |
| 191 | + if (aContainerInfo) { |
| 192 | + return aContainerInfo; |
| 193 | + } else { |
| 194 | + throw new Error(`${fnTag} no image "${image}"`); |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + // ./scripts/docker_run.sh ./target/release/node-template purge-chain --dev |
| 199 | + protected async purgeDevChain(): Promise<void> { |
| 200 | + throw new Error("TODO"); |
| 201 | + } |
| 202 | +} |
0 commit comments