blob: 8343b8e6f6cbe491264d96ff5a8f34f5dbe2e854 [file] [log] [blame]
Clark Boylanda402e52012-12-04 15:23:43 -08001#! /usr/bin/env python
2# Copyright (C) 2011 OpenStack, LLC.
3# Copyright (c) 2012 Hewlett-Packard Development Company, L.P.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
17import ConfigParser
Clark Boylanda402e52012-12-04 15:23:43 -080018import os
19import StringIO
20
21
22GERRIT_CONFIG = os.environ.get(
23 'GERRIT_CONFIG',
24 '/home/gerrit2/review_site/etc/gerrit.config')
25GERRIT_SECURE_CONFIG = os.environ.get(
26 'GERRIT_SECURE_CONFIG',
27 '/home/gerrit2/review_site/etc/secure.config')
28db_connection = None
29
30
31def get_broken_config(filename):
Monty Taylor061919f2013-06-02 11:35:42 -040032 """gerrit config ini files are broken and have leading tabs."""
Clark Boylanda402e52012-12-04 15:23:43 -080033 text = ""
34 for line in open(filename, "r"):
35 text += line.lstrip()
36
37 fp = StringIO.StringIO(text)
38 c = ConfigParser.ConfigParser()
39 c.readfp(fp)
40 return c
41
42
43def connect():
44 global db_connection
45 if not db_connection:
46 gerrit_config = get_broken_config(GERRIT_CONFIG)
47 secure_config = get_broken_config(GERRIT_SECURE_CONFIG)
48
Paul Belanger1b9f5942014-05-07 19:47:11 +000049 DB_TYPE = gerrit_config.get("database", "type")
James E. Blair8b183802014-04-28 15:33:31 -070050 DB_HOST = gerrit_config.get("database", "hostname")
Clark Boylanda402e52012-12-04 15:23:43 -080051 DB_USER = gerrit_config.get("database", "username")
52 DB_PASS = secure_config.get("database", "password")
53 DB_DB = gerrit_config.get("database", "database")
54
Paul Belanger1b9f5942014-05-07 19:47:11 +000055 if DB_TYPE == "MYSQL":
56 import MySQLdb
57 db_connection = MySQLdb.connect(
58 host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_DB)
59 else:
60 import psycopg2
61 db_connection = psycopg2.connect(
62 host=DB_HOST, user=DB_USER, password=DB_PASS, database=DB_DB)
Clark Boylanda402e52012-12-04 15:23:43 -080063 return db_connection