Path: blob/main/components/gitpod-db/src/wait-for-db.ts
2498 views
/**1* Copyright (c) 2020 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56/**7* Script that waits for a database to become available8*/9import "reflect-metadata";10import { Config } from "./config";11import * as mysql from "mysql";1213const retryPeriod = 5000; // [ms]14const totalAttempts = 30;15const connCfg: mysql.ConnectionConfig = {16...new Config().mysqlConfig,17timeout: retryPeriod,18};1920function connectOrReschedule(attempt: number) {21const con = mysql.createConnection(connCfg);22try {23con.connect((err) => {24if (err) {25rescheduleConnectionAttempt(attempt, err);26} else {27console.log("DB is available");28con.destroy();29process.exit(0);30}31});32} catch (err) {33rescheduleConnectionAttempt(attempt, err);34}35}3637function rescheduleConnectionAttempt(attempt: number, err: unknown) {38if (attempt == totalAttempts) {39console.log(`Could not connect within ${totalAttempts} attempts. Stopping.`, err);40process.exit(1);41}42console.log(`Connection attempt ${attempt}/${totalAttempts} failed. Retrying in ${retryPeriod / 1000} seconds.`);43setTimeout(() => connectOrReschedule(attempt + 1), retryPeriod);44}4546connectOrReschedule(0);474849