aboutsummaryrefslogtreecommitdiff
path: root/rpkid/rpki-sql-setup
blob: 465e4113ec6c6956e6ba1ea3a6d2836db5e77e52 (plain) (blame)
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
#!/usr/bin/env python

"""
Automated setup of all the pesky SQL stuff we need.  Prompts for MySQL
root password, pulls other information from rpki.conf.

$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 getopt
import sys
import getpass
import rpki.config
import rpki.sql_schemas

from rpki.mysql_import import MySQLdb

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 sql_setup(name):
  """
  Create a new SQL database and construct all its tables.
  """

  database = cfg.get("sql-database", section = name)
  username = cfg.get("sql-username", section = name)
  password = cfg.get("sql-password", section = name)
  schema = read_schema(name)

  if script_purge and database in databases:
    databases.remove(database)
    print "DROP DATABASE IF EXISTS %s;" %  database
    return

  cur = rootdb.cursor()

  if drop and database in databases:
    log("Dropping database %s" % database)
    databases.remove(database)
    try:
      cur.execute("DROP DATABASE IF EXISTS %s" %  database)
    except Exception, e:
      log("Couldn't drop database %s, blundering onwards: %s" % (database, e))

  if create and database not in databases:
    log("Creating database %s" % database)
    cur = rootdb.cursor()
    cur.execute("CREATE DATABASE %s" % database)
    cur.execute("GRANT ALL ON %s.* TO %s@localhost IDENTIFIED BY %%s" % (database, username), (password,))

  rootdb.commit()

  if create and database not in databases:
    databases.add(database)
    db = MySQLdb.connect(db = database, user = username, passwd = password)
    cur = db.cursor()
    for statement in schema:
      if statement.upper().startswith("DROP TABLE"):
        continue
      if verbose:
        log(statement)
      cur.execute(statement)
    db.commit()
    db.close()

def log(text):
  if verbose:
    print "#", text

cfg_file = None

verbose = False
mysql_defaults = None

drop = False
create = True
script_purge = False

opts, argv = getopt.getopt(sys.argv[1:], "c:hv?", ["config=", "help", "missing_only", "mysql_defaults=", "purge", "script_purge", "recreate", "verbose"])
for o, a in opts:
  if o in ("-h", "--help", "-?"):
    print __doc__
    sys.exit(0)
  if o in ("-v", "--verbose"):
    verbose = True
  elif o in ("-c", "--config"):
    cfg_file = a
  elif o == "--purge":
    drop = True
    create = script_purge = False
  elif o == "--recreate":
    drop = create = True
    script_purge = False
  elif o == "--script_purge":
    script_purge = True
    drop = create = False
  elif o == "--mysql_defaults":
    mysql_defaults = a

cfg = rpki.config.parser(cfg_file, "myrpki")

if mysql_defaults is None:
  rootdb = MySQLdb.connect(db = "mysql", user = "root", passwd = getpass.getpass("Please enter your MySQL root password: "))
else:
  mysql_cfg = rpki.config.parser(mysql_defaults, "client")
  rootdb = MySQLdb.connect(db = "mysql", user = mysql_cfg.get("user"), passwd = mysql_cfg.get("password"))

cur = rootdb.cursor()
cur.execute("SHOW DATABASES")
databases = set(d[0] for d in cur.fetchall())
del cur

if cfg.getboolean("start_irdbd", False):
  sql_setup("irdbd")

if cfg.getboolean("start_rpkid", False):
  sql_setup("rpkid")

if cfg.getboolean("start_pubd",  False):
  sql_setup("pubd")

rootdb.close()