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
|
#!/usr/bin/env python
# $Id$
#
# Copyright (C) 2009--2013 Internet Systems Consortium ("ISC")
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
import sys
import getpass
import argparse
import rpki.config
import rpki.sql_schemas
from rpki.mysql_import import MySQLdb
class RootDB(object):
"""
Class to wrap MySQL actions that require root-equivalent access so
we can defer such actions until we're sure they're really needed.
Overall goal here is to prompt the user for the root password once
at most, and not at all when not necessary.
"""
def __init__(self, mysql_defaults = None):
self.initialized = False
self.mysql_defaults = mysql_defaults
def __getattr__(self, name):
if self.initialized:
raise AttributeError
if self.mysql_defaults is None:
self.db = MySQLdb.connect(db = "mysql",
user = "root",
passwd = getpass.getpass("Please enter your MySQL root password: "))
else:
mysql_cfg = rpki.config.parser(self.mysql_defaults, "client")
self.db = MySQLdb.connect(db = "mysql",
user = mysql_cfg.get("user"),
passwd = mysql_cfg.get("password"))
self.cur = self.db.cursor()
self.cur.execute("SHOW DATABASES")
self.databases = set(d[0] for d in self.cur.fetchall())
self.initialized = True
return getattr(self, name)
def close(self):
if self.initialized:
self.db.close()
class UserDB(object):
"""
Class to wrap MySQL access parameters for a particular database.
"""
def __init__(self, name):
self.database = cfg.get("sql-database", section = name)
self.username = cfg.get("sql-username", section = name)
self.password = cfg.get("sql-password", section = name)
self.db = None
self.cur = None
def open(self):
self.db = MySQLdb.connect(db = self.database, user = self.username, passwd = self.password)
self.cur = self.db.cursor()
def commit(self):
self.db.commit()
def close(self):
if self.db is not None:
self.db.close()
self.db = None
self.cur = None
@property
def exists_and_accessible(self):
try:
db = MySQLdb.connect(db = self.database, user = self.username, passwd = self.password)
db.close()
return True
except:
return False
def read_schema(name):
"""
Convert an SQL file into a list of SQL statements.
"""
lines = []
for line in getattr(rpki.sql_schemas, name, "").splitlines():
line = " ".join(line.split())
if line and not line.startswith("--"):
lines.append(line)
return [statement.strip() for statement in " ".join(lines).rstrip(";").split(";") if statement.strip()]
def do_drop(name):
db = UserDB(name)
if db.database in root.databases:
log("DROP DATABASE %s" % db.database)
root.cur.execute("DROP DATABASE %s" % db.database)
root.db.commit()
def do_create(name):
db = UserDB(name)
log("CREATE DATABASE %s" % db.database)
root.cur.execute("CREATE DATABASE %s" % db.database)
log("GRANT ALL ON %s.* TO %s@localhost IDENTIFIED BY ###" % (db.database, db.username))
root.cur.execute("GRANT ALL ON %s.* TO %s@localhost IDENTIFIED BY %%s" % (db.database, db.username),
(db.password,))
root.db.commit()
db.open()
for statement in read_schema(name):
if not statement.upper().startswith("DROP TABLE"):
log(statement)
db.cur.execute(statement)
db.commit()
db.close()
def do_script_drop(name):
db = UserDB(name)
print "DROP DATABASE IF EXISTS %s;" % db.database
def do_drop_and_create(name):
do_drop(name)
do_create(name)
def do_fix_grants(name):
db = UserDB(name)
if not db.exists_and_accessible:
log("GRANT ALL ON %s.* TO %s@localhost IDENTIFIED BY ###" % (db.database, db.username))
root.cur.execute("GRANT ALL ON %s.* TO %s@localhost IDENTIFIED BY %%s" % (db.database, db.username),
(db.password,))
root.db.commit()
def do_create_if_missing(name):
db = UserDB(name)
if not db.exists_and_accessible:
do_create(name)
def log(text):
if args.verbose:
print "#", text
parser = argparse.ArgumentParser(description = """\
Automated setup of all SQL stuff used by the RPKI CA tools. Pulls
configuration from rpki.conf, prompts for MySQL password when needed.
""")
group = parser.add_mutually_exclusive_group()
parser.add_argument("-c", "--config",
help = "specify alternate location for rpki.conf")
parser.add_argument("-v", "--verbose", action = "store_true",
help = "whistle while you work")
parser.add_argument("--mysql-defaults",
help = "specify MySQL root access credentials via a configuration file")
group.add_argument("--create",
action = "store_const", dest = "dispatch", const = do_create,
help = "create databases and load schemas")
group.add_argument("--drop",
action = "store_const", dest = "dispatch", const = do_drop,
help = "drop databases")
group.add_argument("--script-drop",
action = "store_const", dest = "dispatch", const = do_script_drop,
help = "send SQL commands to drop databases to standard output")
group.add_argument("--drop-and-create",
action = "store_const", dest = "dispatch", const = do_drop_and_create,
help = "drop databases then recreate them and load schemas")
group.add_argument("--fix-grants",
action = "store_const", dest = "dispatch", const = do_fix_grants,
help = "whack database access to match current configuration file")
group.add_argument("--create-if-missing",
action = "store_const", dest = "dispatch", const = do_create_if_missing,
help = "create databases and load schemas if they don't exist already")
parser.set_defaults(dispatch = do_create_if_missing)
args = parser.parse_args()
cfg = rpki.config.parser(args.config, "myrpki")
root = RootDB(args.mysql_defaults)
try:
if cfg.getboolean("start_irdbd", False):
args.dispatch("irdbd")
if cfg.getboolean("start_rpkid", False):
args.dispatch("rpkid")
if cfg.getboolean("start_pubd", False):
args.dispatch("pubd")
root.close()
except Exception, e:
sys.exit(str(e))
|