diff options
Diffstat (limited to 'rpkid/tests')
-rw-r--r-- | rpkid/tests/Makefile.in | 18 | ||||
-rw-r--r-- | rpkid/tests/myrpki-xml-parse-test.py | 6 | ||||
-rw-r--r-- | rpkid/tests/rcynic.conf | 1 | ||||
-rw-r--r-- | rpkid/tests/smoketest.py | 167 | ||||
-rw-r--r-- | rpkid/tests/sql-cleaner.py | 21 | ||||
-rw-r--r-- | rpkid/tests/sql-dumper.py | 17 | ||||
-rw-r--r-- | rpkid/tests/testpoke.py | 12 | ||||
-rw-r--r-- | rpkid/tests/yamlconf.py | 788 | ||||
-rw-r--r-- | rpkid/tests/yamltest.py | 302 |
9 files changed, 1123 insertions, 209 deletions
diff --git a/rpkid/tests/Makefile.in b/rpkid/tests/Makefile.in index 35cd70c3..e4820738 100644 --- a/rpkid/tests/Makefile.in +++ b/rpkid/tests/Makefile.in @@ -63,9 +63,25 @@ yamltest: ${PYTHON} sql-cleaner.py ${PYTHON} yamltest.py ${YAMLTEST_CONFIG} +YAMLCONF_CONFIG = ${YAMLTEST_CONFIG} + +yamlconf: + rm -rf yamltest.dir rcynic-data + ${PYTHON} sql-cleaner.py + ${PYTHON} yamlconf.py --loopback ${YAMLCONF_CONFIG} + @echo + ${PYTHON} yamltest.py --skip_config --synchronize ${YAMLCONF_CONFIG} + +yamlconf-profile: + rm -rf yamltest.dir rcynic-data + ${PYTHON} sql-cleaner.py + ${PYTHON} yamlconf.py --loopback --profile yamlconf.prof ${YAMLCONF_CONFIG} + @echo + ${PYTHON} yamltest.py --skip_config --synchronize --profile ${YAMLCONF_CONFIG} + backup: ${PYTHON} sql-dumper.py - tar cvvzf yamltest.backup.$$(TZ='' date +%Y.%m.%d.%H.%M.%S).tgz screenlog.* yamltest.dir backup.*.sql + tar cvvJf yamltest.backup.$$(TZ='' date +%Y.%m.%d.%H.%M.%S).txz screenlog.* yamltest.dir backup.*.sql rm backup.*.sql distclean: clean diff --git a/rpkid/tests/myrpki-xml-parse-test.py b/rpkid/tests/myrpki-xml-parse-test.py index 5aaf5cbf..6818dbe5 100644 --- a/rpkid/tests/myrpki-xml-parse-test.py +++ b/rpkid/tests/myrpki-xml-parse-test.py @@ -3,7 +3,7 @@ Test parser and display tool for myrpki.xml files. $Id$ -Copyright (C) 2009--2010 Internet Systems Consortium ("ISC") +Copyright (C) 2009--2012 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 @@ -29,9 +29,9 @@ if False: relaxng.assertValid(tree) -def showitems(x): +def showitems(y): if False: - for k, v in x.items(): + for k, v in y.items(): if v: print " ", k, v diff --git a/rpkid/tests/rcynic.conf b/rpkid/tests/rcynic.conf index ade1c1a3..ea31fe58 100644 --- a/rpkid/tests/rcynic.conf +++ b/rpkid/tests/rcynic.conf @@ -11,5 +11,4 @@ use-stderr = yes log-level = log_debug max-parallel-fetches = 32 -#trust-anchor = yamltest.dir/RIR/publication/root.cer trust-anchor-locator = yamltest.dir/root.tal diff --git a/rpkid/tests/smoketest.py b/rpkid/tests/smoketest.py index bb97108b..67e31fed 100644 --- a/rpkid/tests/smoketest.py +++ b/rpkid/tests/smoketest.py @@ -17,7 +17,7 @@ things that don't belong in yaml_script. $Id$ -Copyright (C) 2009--2011 Internet Systems Consortium ("ISC") +Copyright (C) 2009--2012 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 @@ -46,9 +46,25 @@ OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ -import os, yaml, warnings, subprocess, signal, time, getopt, sys, errno -import rpki.resource_set, rpki.sundial, rpki.x509, rpki.http -import rpki.log, rpki.left_right, rpki.config, rpki.publication, rpki.async +# pylint: disable=W0621 + +import os +import yaml +import subprocess +import signal +import time +import getopt +import sys +import errno +import rpki.resource_set +import rpki.sundial +import rpki.x509 +import rpki.http +import rpki.log +import rpki.left_right +import rpki.config +import rpki.publication +import rpki.async from rpki.mysql_import import MySQLdb @@ -158,6 +174,11 @@ class CouldntIssueBSCEECertificate(Exception): Couldn't issue BSC EE certificate """ +sql_conversions = MySQLdb.converters.conversions.copy() +sql_conversions.update({ + rpki.sundial.datetime : MySQLdb.converters.DateTime2literal, + MySQLdb.converters.FIELD_TYPE.DATETIME : rpki.sundial.datetime.DateTime_or_None }) + def main(): """ Main program. @@ -194,21 +215,21 @@ def main(): # Apparently os.walk() can't tell the difference between directories # and symlinks to directories, so we have to handle both. for root, dirs, files in os.walk(".", topdown = False): - for file in files: - if not file.endswith(".key"): - os.remove(os.path.join(root, file)) - for dir in dirs: + for fn in files: + if not fn.endswith(".key"): + os.remove(os.path.join(root, fn)) + for d in dirs: try: - os.rmdir(os.path.join(root, dir)) + os.rmdir(os.path.join(root, d)) except OSError, e: if e.errno == errno.ENOTDIR: - os.remove(os.path.join(root, dir)) + os.remove(os.path.join(root, d)) else: raise rpki.log.info("Reading master YAML configuration") y = yaml_script.pop(0) - + rpki.log.info("Constructing internal allocation database") db = allocation_db(y) @@ -218,6 +239,7 @@ def main(): rpki.log.info("Constructing BPKI keys and certs for pubd") setup_bpki_cert_chain(pubd_name, ee = ("PUBD", "IRBE")) + for a in db: a.setup_bpki_certs() @@ -322,13 +344,15 @@ def main(): for proc, name in ((rootd_process, "rootd"), (pubd_process, "pubd"), (rsyncd_process, "rsyncd")): - if proc is not None: + # pylint: disable=E1103 + if proc is not None and proc.poll() is None: rpki.log.info("Killing %s, pid %s" % (name, proc.pid)) try: - os.kill(proc.pid, signal.SIGTERM) + proc.terminate() except OSError: pass - proc.wait() + if proc is not None: + rpki.log.info("Daemon %s, pid %s exited with code %s" % (name, proc.pid, proc.wait())) def cmd_sleep(cb, interval): """ @@ -409,17 +433,14 @@ class allocation_db(list): self.root.regen_margin = rpki.sundial.timedelta.parse(cfg.get("regen_margin", "1d")).convert_to_seconds() for a in self: if a.sia_base is None: - a.sia_base = (rootd_sia if a.is_root else a.parent.sia_base) + a.name + "/" + a.sia_base = (rootd_sia + "root/trunk/" if a.is_root else a.parent.sia_base) + a.name + "/" if a.base.valid_until is None: a.base.valid_until = a.parent.base.valid_until if a.crl_interval is None: a.crl_interval = a.parent.crl_interval if a.regen_margin is None: a.regen_margin = a.parent.regen_margin - i = 0 - for j in xrange(4): - i = a.sia_base.index("/", i) + 1 - a.client_handle = a.sia_base[i:].rstrip("/") + a.client_handle = "/".join(a.sia_base.split("/")[4:]).rstrip("/") self.root.closure() self.map = dict((a.name, a) for a in self) self.engines = [a for a in self if a.is_engine] @@ -471,6 +492,8 @@ class allocation(object): crl_interval = None regen_margin = None last_cms_time = None + rpkid_process = None + irdbd_process = None def __init__(self, yaml, db, parent = None): """ @@ -482,7 +505,7 @@ class allocation(object): self.kids = [allocation(k, db, self) for k in yaml.get("kids", ())] valid_until = None if "valid_until" in yaml: - valid_until = rpki.sundial.datetime.fromdatetime(yaml.get("valid_until")) + valid_until = rpki.sundial.datetime.from_datetime(yaml.get("valid_until")) if valid_until is None and "valid_for" in yaml: valid_until = rpki.sundial.now() + rpki.sundial.timedelta.parse(yaml["valid_for"]) self.base = rpki.resource_set.resource_bag( @@ -498,9 +521,9 @@ class allocation(object): self.roa_requests = [roa_request.parse(y) for y in yaml.get("roa_request", yaml.get("route_origin", ()))] for r in self.roa_requests: if r.v4: - self.base.v4 = self.base.v4.union(r.v4.to_resource_set()) + self.base.v4 |= r.v4.to_resource_set() if r.v6: - self.base.v6 = self.base.v6.union(r.v6.to_resource_set()) + self.base.v6 |= r.v6.to_resource_set() self.hosted_by = yaml.get("hosted_by") self.extra_conf = yaml.get("extra_conf", []) self.hosts = [] @@ -511,7 +534,7 @@ class allocation(object): """ resources = self.base for kid in self.kids: - resources = resources.union(kid.closure()) + resources |= kid.closure() self.resources = resources return resources @@ -531,31 +554,31 @@ class allocation(object): rpki.async.iterator(yaml.items(), loop, cb) def apply_add_as(self, text, cb): - self.base.asn = self.base.asn.union(rpki.resource_set.resource_set_as(text)) + self.base.asn |= rpki.resource_set.resource_set_as(text) cb() def apply_add_v4(self, text, cb): - self.base.v4 = self.base.v4.union(rpki.resource_set.resource_set_ipv4(text)) + self.base.v4 |= rpki.resource_set.resource_set_ipv4(text) cb() def apply_add_v6(self, text, cb): - self.base.v6 = self.base.v6.union(rpki.resource_set.resource_set_ipv6(text)) + self.base.v6 |= rpki.resource_set.resource_set_ipv6(text) cb() def apply_sub_as(self, text, cb): - self.base.asn = self.base.asn.difference(rpki.resource_set.resource_set_as(text)) + self.base.asn |= rpki.resource_set.resource_set_as(text) cb() def apply_sub_v4(self, text, cb): - self.base.v4 = self.base.v4.difference(rpki.resource_set.resource_set_ipv4(text)) + self.base.v4 |= rpki.resource_set.resource_set_ipv4(text) cb() def apply_sub_v6(self, text, cb): - self.base.v6 = self.base.v6.difference(rpki.resource_set.resource_set_ipv6(text)) + self.base.v6 |= rpki.resource_set.resource_set_ipv6(text) cb() def apply_valid_until(self, stamp, cb): - self.base.valid_until = rpki.sundial.datetime.fromdatetime(stamp) + self.base.valid_until = rpki.sundial.datetime.from_datetime(stamp) cb() def apply_valid_for(self, text, cb): @@ -711,7 +734,8 @@ class allocation(object): Set up this entity's IRDB. """ rpki.log.info("Setting up MySQL for %s" % self.name) - db = MySQLdb.connect(user = "rpki", db = self.rpki_db_name, passwd = rpki_db_pass) + db = MySQLdb.connect(user = "rpki", db = self.rpki_db_name, passwd = rpki_db_pass, + conv = sql_conversions) cur = db.cursor() db.autocommit(True) for sql in rpki_sql: @@ -721,7 +745,8 @@ class allocation(object): if "DROP TABLE IF EXISTS" not in sql.upper(): raise db.close() - db = MySQLdb.connect(user = "irdb", db = self.irdb_db_name, passwd = irdb_db_pass) + db = MySQLdb.connect(user = "irdb", db = self.irdb_db_name, passwd = irdb_db_pass, + conv = sql_conversions) cur = db.cursor() db.autocommit(True) for sql in irdb_sql: @@ -733,7 +758,7 @@ class allocation(object): for s in [self] + self.hosts: for kid in s.kids: cur.execute("INSERT registrant (registrant_handle, registry_handle, valid_until) VALUES (%s, %s, %s)", - (kid.name, s.name, kid.resources.valid_until.to_sql())) + (kid.name, s.name, kid.resources.valid_until)) db.close() def sync_sql(self): @@ -743,7 +768,8 @@ class allocation(object): this entity. """ rpki.log.info("Updating MySQL data for IRDB %s" % self.name) - db = MySQLdb.connect(user = "irdb", db = self.irdb_db_name, passwd = irdb_db_pass) + db = MySQLdb.connect(user = "irdb", db = self.irdb_db_name, passwd = irdb_db_pass, + conv = sql_conversions) cur = db.cursor() db.autocommit(True) cur.execute("DELETE FROM registrant_asn") @@ -760,7 +786,7 @@ class allocation(object): cur.execute("INSERT registrant_net (start_ip, end_ip, version, registrant_id) VALUES (%s, %s, 4, %s)", (v4_range.min, v4_range.max, registrant_id)) for v6_range in kid.resources.v6: cur.execute("INSERT registrant_net (start_ip, end_ip, version, registrant_id) VALUES (%s, %s, 6, %s)", (v6_range.min, v6_range.max, registrant_id)) - cur.execute("UPDATE registrant SET valid_until = %s WHERE registrant_id = %s", (kid.resources.valid_until.to_sql(), registrant_id)) + cur.execute("UPDATE registrant SET valid_until = %s WHERE registrant_id = %s", (kid.resources.valid_until, registrant_id)) for r in s.roa_requests: cur.execute("INSERT roa_request (roa_request_handle, asn) VALUES (%s, %s)", (s.name, r.asn)) roa_request_id = cur.lastrowid @@ -782,17 +808,18 @@ class allocation(object): """ Kill daemons for this entity. """ - rpki.log.info("Killing daemons for %s" % self.name) - try: - for proc in (self.rpkid_process, self.irdbd_process): + # pylint: disable=E1103 + for proc, name in ((self.rpkid_process, "rpkid"), + (self.irdbd_process, "irdbd")): + if proc is not None and proc.poll() is None: + rpki.log.info("Killing daemon %s pid %s for %s" % (name, proc.pid, self.name)) try: - rpki.log.info("Killing pid %d" % proc.pid) - os.kill(proc.pid, signal.SIGTERM) + proc.terminate() except OSError: pass - proc.wait() - except AttributeError: - pass + if proc is not None: + rpki.log.info("Daemon %s pid %s for %s exited with code %s" % ( + name, proc.pid, self.name, proc.wait())) def call_rpkid(self, pdus, cb): """ @@ -1140,7 +1167,7 @@ def setup_rootd(rpkid, rootd_yaml): f.close() s = "exec >/dev/null 2>&1\n" #s = "set -x\n" - if not os.path.exists(rootd_name + ".key"): + if not os.path.exists("root.key"): s += rootd_fmt_2 % d s += rootd_fmt_3 % d subprocess.check_call(s, shell = True) @@ -1175,15 +1202,15 @@ def setup_publication(pubd_sql): Set up publication daemon. """ rpki.log.info("Configure publication daemon") - pubd_dir = os.getcwd() + "/publication/" + publication_dir = os.getcwd() + "/publication" assert rootd_sia.startswith("rsync://") - i = 0 - for j in xrange(4): - i = rootd_sia.index("/", i + 1) global rsyncd_dir - rsyncd_dir = pubd_dir.rstrip("/") + rootd_sia[i:] - os.makedirs(rsyncd_dir) - db = MySQLdb.connect(db = pubd_db_name, user = pubd_db_user, passwd = pubd_db_pass) + rsyncd_dir = publication_dir + "/".join(rootd_sia.split("/")[4:]) + if not rsyncd_dir.endswith("/"): + rsyncd_dir += "/" + os.makedirs(rsyncd_dir + "root/trunk") + db = MySQLdb.connect(db = pubd_db_name, user = pubd_db_user, passwd = pubd_db_pass, + conv = sql_conversions) cur = db.cursor() db.autocommit(True) for sql in pubd_sql: @@ -1198,7 +1225,7 @@ def setup_publication(pubd_sql): "pubd_db_name" : pubd_db_name, "pubd_db_user" : pubd_db_user, "pubd_db_pass" : pubd_db_pass, - "pubd_dir" : pubd_dir } + "pubd_dir" : rsyncd_dir } f = open(pubd_name + ".conf", "w") f.write(pubd_fmt_1 % d) f.close() @@ -1432,21 +1459,21 @@ child-bpki-cert = %(rootd_name)s-TA-%(rpkid_name)s-SELF.cer server-port = %(rootd_port)s -rpki-root-dir = %(rsyncd_dir)s -rpki-base-uri = %(rootd_sia)s -rpki-root-cert-uri = %(rootd_sia)s%(rootd_name)s.cer +rpki-root-dir = %(rsyncd_dir)sroot +rpki-base-uri = %(rootd_sia)sroot/ +rpki-root-cert-uri = %(rootd_sia)sroot.cer -rpki-root-key = %(rootd_name)s.key -rpki-root-cert = %(rootd_name)s.cer +rpki-root-key = root.key +rpki-root-cert = root.cer rpki-subject-pkcs10 = %(rootd_name)s.subject.pkcs10 rpki-subject-lifetime = %(lifetime)s -rpki-root-crl = Bandicoot.crl -rpki-root-manifest = Bandicoot.mft +rpki-root-crl = root.crl +rpki-root-manifest = root.mft -rpki-class-name = Wombat -rpki-subject-cert = Wombat.cer +rpki-class-name = trunk +rpki-subject-cert = trunk.cer include-bpki-crl = yes enable_tracebacks = yes @@ -1455,7 +1482,6 @@ enable_tracebacks = yes default_bits = 2048 encrypt_key = no distinguished_name = req_dn -#req_extensions = req_x509_ext prompt = no default_md = sha256 default_days = 60 @@ -1472,7 +1498,7 @@ authorityKeyIdentifier = keyid:always basicConstraints = critical,CA:true subjectKeyIdentifier = hash keyUsage = critical,keyCertSign,cRLSign -subjectInfoAccess = 1.3.6.1.5.5.7.48.5;URI:%(rootd_sia)s,1.3.6.1.5.5.7.48.10;URI:%(rootd_sia)sBandicoot.mft +subjectInfoAccess = 1.3.6.1.5.5.7.48.5;URI:%(rootd_sia)sroot/,1.3.6.1.5.5.7.48.10;URI:%(rootd_sia)sroot/root.mft sbgp-autonomousSysNum = critical,AS:0-4294967295 sbgp-ipAddrBlock = critical,IPv4:0.0.0.0/0,IPv6:0::/0 certificatePolicies = critical, @rpki_certificate_policy @@ -1483,17 +1509,17 @@ policyIdentifier = 1.3.6.1.5.5.7.14.2 ''' rootd_fmt_2 = '''\ -%(openssl)s genrsa -out %(rootd_name)s.key 2048 && +%(openssl)s genrsa -out root.key 2048 && ''' rootd_fmt_3 = '''\ -echo >%(rootd_name)s.tal %(rootd_sia)s%(rootd_name)s.cer && +echo >%(rootd_name)s.tal %(rootd_sia)sroot.cer && echo >>%(rootd_name)s.tal && -%(openssl)s rsa -pubout -in %(rootd_name)s.key | awk '!/-----(BEGIN|END)/' >>%(rootd_name)s.tal && -%(openssl)s req -new -sha256 -key %(rootd_name)s.key -out %(rootd_name)s.req -config %(rootd_name)s.conf -text -extensions req_x509_rpki_ext && -%(openssl)s x509 -req -sha256 -in %(rootd_name)s.req -out %(rootd_name)s.cer -outform DER -extfile %(rootd_name)s.conf -extensions req_x509_rpki_ext \ - -signkey %(rootd_name)s.key && -ln -f %(rootd_name)s.cer %(rsyncd_dir)s +%(openssl)s rsa -pubout -in root.key | awk '!/-----(BEGIN|END)/' >>%(rootd_name)s.tal && +%(openssl)s req -new -sha256 -key root.key -out %(rootd_name)s.req -config %(rootd_name)s.conf -text -extensions req_x509_rpki_ext && +%(openssl)s x509 -req -sha256 -in %(rootd_name)s.req -out root.cer -outform DER -extfile %(rootd_name)s.conf -extensions req_x509_rpki_ext \ + -signkey root.key && +ln -f root.cer %(rsyncd_dir)s ''' rcynic_fmt_1 = '''\ @@ -1504,7 +1530,6 @@ use-links = yes use-syslog = no use-stderr = yes log-level = log_debug -#trust-anchor = %(rootd_name)s.cer trust-anchor-locator = %(rootd_name)s.tal ''' diff --git a/rpkid/tests/sql-cleaner.py b/rpkid/tests/sql-cleaner.py index 5db122e1..34a72fd3 100644 --- a/rpkid/tests/sql-cleaner.py +++ b/rpkid/tests/sql-cleaner.py @@ -3,7 +3,7 @@ $Id$ -Copyright (C) 2009--2011 Internet Systems Consortium ("ISC") +Copyright (C) 2009--2012 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 @@ -18,7 +18,8 @@ OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ -import rpki.config, rpki.sql_schemas +import rpki.config +import rpki.sql_schemas from rpki.mysql_import import MySQLdb cfg = rpki.config.parser(None, "yamltest", allow_missing = True) @@ -34,12 +35,16 @@ for name in ("rpkid", "irdbd", "pubd"): schema = " ".join(schema).strip(";").split(";") schema = [statement.strip() for statement in schema if statement and "DROP TABLE" not in statement] - for i in xrange(12): + db = MySQLdb.connect(user = username, passwd = password) + cur = db.cursor() - database = "%s%d" % (name[:4], i) + cur.execute("SHOW DATABASES") - db = MySQLdb.connect(user = username, db = database, passwd = password) - cur = db.cursor() + databases = [r[0] for r in cur.fetchall() if r[0][:4] == name[:4] and r[0][4:].isdigit()] + + for database in databases: + + cur.execute("USE " + database) cur.execute("SHOW TABLES") tables = [r[0] for r in cur.fetchall()] @@ -52,5 +57,5 @@ for name in ("rpkid", "irdbd", "pubd"): for statement in schema: cur.execute(statement) - cur.close() - db.close() + cur.close() + db.close() diff --git a/rpkid/tests/sql-dumper.py b/rpkid/tests/sql-dumper.py index cff62d4f..e4bb1a28 100644 --- a/rpkid/tests/sql-dumper.py +++ b/rpkid/tests/sql-dumper.py @@ -3,7 +3,7 @@ Dump backup copies of SQL tables used by these programs. $Id$ -Copyright (C) 2009--2010 Internet Systems Consortium ("ISC") +Copyright (C) 2009--2012 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 @@ -18,7 +18,9 @@ OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ -import subprocess, rpki.config +import subprocess +import rpki.config +from rpki.mysql_import import MySQLdb cfg = rpki.config.parser(None, "yamltest", allow_missing = True) @@ -28,5 +30,14 @@ for name in ("rpkid", "irdbd", "pubd"): password = cfg.get("%s_sql_password" % name, "fnord") cmd = ["mysqldump", "-u", username, "-p" + password, "--databases"] - cmd.extend("%s%d" % (name[:4], i) for i in xrange(12)) + + db = MySQLdb.connect(user = username, passwd = password) + cur = db.cursor() + + cur.execute("SHOW DATABASES") + cmd.extend(r[0] for r in cur.fetchall() if r[0][:4] == name[:4] and r[0][4:].isdigit()) + + cur.close() + db.close() + subprocess.check_call(cmd, stdout = open("backup.%s.sql" % name, "w")) diff --git a/rpkid/tests/testpoke.py b/rpkid/tests/testpoke.py index 1f7713a1..49919709 100644 --- a/rpkid/tests/testpoke.py +++ b/rpkid/tests/testpoke.py @@ -12,7 +12,7 @@ Default configuration file is testpoke.yaml, override with --yaml option. $Id$ -Copyright (C) 2010--2011 Internet Systems Consortium ("ISC") +Copyright (C) 2010--2012 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 @@ -138,10 +138,12 @@ def do_list(): def do_issue(): q_pdu = rpki.up_down.issue_pdu() req_key = get_PEM("cert-request-key", rpki.x509.RSA, yaml_req) or cms_key - sia = ((rpki.oids.name2oid["id-ad-caRepository"], ("uri", yaml_req["sia"][0])), - (rpki.oids.name2oid["id-ad-rpkiManifest"], ("uri", yaml_req["sia"][0] + req_key.gSKI() + ".mft"))) q_pdu.class_name = yaml_req["class"] - q_pdu.pkcs10 = rpki.x509.PKCS10.create_ca(req_key, sia) + q_pdu.pkcs10 = rpki.x509.PKCS10.create( + keypair = req_key, + is_ca = True, + caRepository = yaml_req["sia"][0], + rpkiManifest = yaml_req["sia"][0] + req_key.gSKI() + ".mft") query_up_down(q_pdu) def do_revoke(): @@ -152,7 +154,7 @@ def do_revoke(): dispatch = { "list" : do_list, "issue" : do_issue, "revoke" : do_revoke } -def fail(e): +def fail(e): # pylint: disable=W0621 rpki.log.traceback(debug) sys.exit("Testpoke failed: %s" % e) diff --git a/rpkid/tests/yamlconf.py b/rpkid/tests/yamlconf.py new file mode 100644 index 00000000..f9f69ba1 --- /dev/null +++ b/rpkid/tests/yamlconf.py @@ -0,0 +1,788 @@ +""" +Test configuration tool, using the same YAML test description format +as smoketest.py and yamltest.py, but doing just the IRDB configuration +for a massive testbed, via direct use of the rpki.irdb library code. + +For most purposes, you don't want this, but when building a +configuration for tens or hundreds of thousands of elements, being +able to do the initial configuration stage quickly can help a lot. + +$Id$ + +Copyright (C) 2009--2012 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. + +Portions copyright (C) 2007--2008 American Registry for Internet Numbers ("ARIN") + +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 ARIN DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL ARIN 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. +""" + +# pylint: disable=W0702,W0621,W0602 + +import subprocess +import re +import os +import sys +import yaml +import time +import argparse +import rpki.resource_set +import rpki.sundial +import rpki.config +import rpki.log +import rpki.csv_utils +import rpki.x509 +import rpki.sql_schemas + +from rpki.mysql_import import MySQLdb + +section_regexp = re.compile(r"\s*\[\s*(.+?)\s*\]\s*$") +variable_regexp = re.compile(r"\s*([-a-zA-Z0-9_]+)\s*=\s*(.+?)\s*$") + +flat_publication = False +only_one_pubd = True +yaml_file = None +loopback = False +quiet = False +dns_suffix = None +mysql_rootuser = None +mysql_rootpass = None +publication_base = None +publication_root = None + +# The SQL username mismatch between rpkid/examples/rpki.conf and +# rpkid/tests/smoketest.setup.sql is completely stupid and really +# should be cleaned up at some point...but not today, at least not as +# part of writing this program. These default values are wired into +# yamltest to match smoketest.setup.sql, so wire them in here too but +# in a more obvious way. + +config_overrides = { + "irdbd_sql_username" : "irdb", "irdbd_sql_password" : "fnord", + "rpkid_sql_username" : "rpki", "rpkid_sql_password" : "fnord", + "pubd_sql_username" : "pubd", "pubd_sql_password" : "fnord" } + +def cleanpath(*names): + return os.path.normpath(os.path.join(*names)) + +this_dir = os.getcwd() +test_dir = None +rpki_conf = None + +class roa_request(object): + """ + Representation of a ROA request. + """ + + def __init__(self, asn, ipv4, ipv6): + self.asn = asn + self.v4 = rpki.resource_set.roa_prefix_set_ipv4("".join(ipv4.split())) if ipv4 else None + self.v6 = rpki.resource_set.roa_prefix_set_ipv6("".join(ipv6.split())) if ipv6 else None + + def __eq__(self, other): + return self.asn == other.asn and self.v4 == other.v4 and self.v6 == other.v6 + + def __hash__(self): + v4 = tuple(self.v4) if self.v4 is not None else None + v6 = tuple(self.v6) if self.v6 is not None else None + return self.asn.__hash__() + v4.__hash__() + v6.__hash__() + + def __str__(self): + if self.v4 and self.v6: + return "%s: %s,%s" % (self.asn, self.v4, self.v6) + else: + return "%s: %s" % (self.asn, self.v4 or self.v6) + + @classmethod + def parse(cls, y): + return cls(y.get("asn"), y.get("ipv4"), y.get("ipv6")) + +class allocation_db(list): + """ + Allocation database. + """ + + def __init__(self, y): + list.__init__(self) + self.root = allocation(y, self) + assert self.root.is_root + if self.root.crl_interval is None: + self.root.crl_interval = 24 * 60 * 60 + if self.root.regen_margin is None: + self.root.regen_margin = 24 * 60 * 60 + if self.root.base.valid_until is None: + self.root.base.valid_until = rpki.sundial.now() + rpki.sundial.timedelta(days = 2) + for a in self: + if a.base.valid_until is None: + a.base.valid_until = a.parent.base.valid_until + if a.crl_interval is None: + a.crl_interval = a.parent.crl_interval + if a.regen_margin is None: + a.regen_margin = a.parent.regen_margin + self.root.closure() + self.map = dict((a.name, a) for a in self) + for a in self: + if a.is_hosted: + a.hosted_by = self.map[a.hosted_by] + a.hosted_by.hosts.append(a) + assert not a.is_root and not a.hosted_by.is_hosted + + def dump(self): + for a in self: + a.dump() + + +class allocation(object): + """ + One entity in our allocation database. Every entity in the database + is assumed to hold resources. Entities that don't have the + hosted_by property run their own copies of rpkid, irdbd, and pubd. + """ + + base_port = 4400 + base_engine = -1 + parent = None + crl_interval = None + regen_margin = None + engine = -1 + rpkid_port = 4404 + irdbd_port = 4403 + pubd_port = 4402 + rootd_port = 4401 + rsync_port = 873 + + @classmethod + def allocate_port(cls): + cls.base_port += 1 + return cls.base_port + + @classmethod + def allocate_engine(cls): + cls.base_engine += 1 + return cls.base_engine + + def __init__(self, y, db, parent = None): + db.append(self) + self.name = y["name"] + self.parent = parent + self.kids = [allocation(k, db, self) for k in y.get("kids", ())] + valid_until = None + if "valid_until" in y: + valid_until = rpki.sundial.datetime.from_datetime(y.get("valid_until")) + if valid_until is None and "valid_for" in y: + valid_until = rpki.sundial.now() + rpki.sundial.timedelta.parse(y["valid_for"]) + self.base = rpki.resource_set.resource_bag( + asn = rpki.resource_set.resource_set_as(y.get("asn")), + v4 = rpki.resource_set.resource_set_ipv4(y.get("ipv4")), + v6 = rpki.resource_set.resource_set_ipv6(y.get("ipv6")), + valid_until = valid_until) + if "crl_interval" in y: + self.crl_interval = rpki.sundial.timedelta.parse(y["crl_interval"]).convert_to_seconds() + if "regen_margin" in y: + self.regen_margin = rpki.sundial.timedelta.parse(y["regen_margin"]).convert_to_seconds() + self.roa_requests = [roa_request.parse(r) for r in y.get("roa_request", ())] + for r in self.roa_requests: + if r.v4: + self.base.v4 |= r.v4.to_resource_set() + if r.v6: + self.base.v6 |= r.v6.to_resource_set() + self.hosted_by = y.get("hosted_by") + self.hosts = [] + if not self.is_hosted: + self.engine = self.allocate_engine() + if loopback and not self.is_hosted: + self.rpkid_port = self.allocate_port() + self.irdbd_port = self.allocate_port() + if loopback and self.runs_pubd: + self.pubd_port = self.allocate_port() + self.rsync_port = self.allocate_port() + if loopback and self.is_root: + self.rootd_port = self.allocate_port() + + def closure(self): + resources = self.base + for kid in self.kids: + resources |= kid.closure() + self.resources = resources + return resources + + @property + def hostname(self): + if loopback: + return "localhost" + elif dns_suffix: + return self.name + "." + dns_suffix.lstrip(".") + else: + return self.name + + @property + def rsync_server(self): + if loopback: + return "%s:%s" % (self.pubd.hostname, self.pubd.rsync_port) + else: + return self.pubd.hostname + + def dump(self): + if not quiet: + print str(self) + + def __str__(self): + s = self.name + ":\n" + if self.resources.asn: s += " ASNs: %s\n" % self.resources.asn + if self.resources.v4: s += " IPv4: %s\n" % self.resources.v4 + if self.resources.v6: s += " IPv6: %s\n" % self.resources.v6 + if self.kids: s += " Kids: %s\n" % ", ".join(k.name for k in self.kids) + if self.parent: s += " Up: %s\n" % self.parent.name + if self.is_hosted: s += " Host: %s\n" % self.hosted_by.name + if self.hosts: s += " Hosts: %s\n" % ", ".join(h.name for h in self.hosts) + for r in self.roa_requests: s += " ROA: %s\n" % r + if not self.is_hosted: s += " IPort: %s\n" % self.irdbd_port + if self.runs_pubd: s += " PPort: %s\n" % self.pubd_port + if not self.is_hosted: s += " RPort: %s\n" % self.rpkid_port + if self.runs_pubd: s += " SPort: %s\n" % self.rsync_port + if self.is_root: s += " TPort: %s\n" % self.rootd_port + return s + " Until: %s\n" % self.resources.valid_until + + @property + def is_root(self): + return self.parent is None + + @property + def is_hosted(self): + return self.hosted_by is not None + + @property + def runs_pubd(self): + return self.is_root or not (self.is_hosted or only_one_pubd) + + def path(self, *names): + return cleanpath(test_dir, self.host.name, *names) + + def csvout(self, fn): + path = self.path(fn) + if not quiet: + print "Writing", path + return rpki.csv_utils.csv_writer(path) + + def up_down_url(self): + return "http://%s:%d/up-down/%s/%s" % (self.parent.host.hostname, + self.parent.host.rpkid_port, + self.parent.name, + self.name) + + def dump_asns(self, fn): + with self.csvout(fn) as f: + for k in self.kids: + f.writerows((k.name, a) for a in k.resources.asn) + + def dump_prefixes(self, fn): + with self.csvout(fn) as f: + for k in self.kids: + f.writerows((k.name, p) for p in (k.resources.v4 + k.resources.v6)) + + def dump_roas(self, fn): + with self.csvout(fn) as f: + for g1, r in enumerate(self.roa_requests): + f.writerows((p, r.asn, "G%08d%08d" % (g1, g2)) + for g2, p in enumerate((r.v4 + r.v6 if r.v4 and r.v6 else r.v4 or r.v6 or ()))) + + @property + def pubd(self): + s = self + while not s.runs_pubd: + s = s.parent + return s + + @property + def client_handle(self): + path = [] + s = self + if not flat_publication: + while not s.runs_pubd: + path.append(s) + s = s.parent + path.append(s) + return ".".join(i.name for i in reversed(path)) + + @property + def host(self): + return self.hosted_by or self + + @property + def publication_base_directory(self): + if not loopback and publication_base is not None: + return publication_base + else: + return self.path("publication") + + @property + def publication_root_directory(self): + if not loopback and publication_root is not None: + return publication_root + else: + return self.path("publication.root") + + def dump_conf(self): + + r = dict( + handle = self.name, + run_rpkid = str(not self.is_hosted), + run_pubd = str(self.runs_pubd), + run_rootd = str(self.is_root), + irdbd_sql_username = "irdb", + rpkid_sql_username = "rpki", + rpkid_server_host = self.hostname, + rpkid_server_port = str(self.rpkid_port), + irdbd_server_host = "localhost", + irdbd_server_port = str(self.irdbd_port), + rootd_server_port = str(self.rootd_port), + pubd_sql_username = "pubd", + pubd_server_host = self.pubd.hostname, + pubd_server_port = str(self.pubd.pubd_port), + publication_rsync_server = self.rsync_server) + + if loopback: + r.update( + irdbd_sql_database = self.irdb_name, + rpkid_sql_database = "rpki%d" % self.engine, + pubd_sql_database = "pubd%d" % self.engine, + bpki_servers_directory = self.path(), + publication_base_directory = self.publication_base_directory) + + r.update(config_overrides) + + with open(self.path("rpki.conf"), "w") as f: + f.write("# Automatically generated, do not edit\n") + if not quiet: + print "Writing", f.name + + section = None + for line in open(rpki_conf): + m = section_regexp.match(line) + if m: + section = m.group(1) + m = variable_regexp.match(line) + option = m.group(1) if m and section == "myrpki" else None + if option and option in r: + line = "%s = %s\n" % (option, r[option]) + f.write(line) + + def dump_rsyncd(self): + lines = [] + if self.runs_pubd: + lines.extend(( + "# Automatically generated, do not edit", + "port = %d" % self.rsync_port, + "address = %s" % self.hostname, + "log file = rsyncd.log", + "read only = yes", + "use chroot = no", + "[rpki]", + "path = %s" % self.publication_base_directory, + "comment = RPKI test")) + if self.is_root: + assert self.runs_pubd + lines.extend(( + "[root]", + "path = %s" % self.publication_root_directory, + "comment = RPKI test root")) + if lines: + with open(self.path("rsyncd.conf"), "w") as f: + if not quiet: + print "Writing", f.name + f.writelines(line + "\n" for line in lines) + + @property + def irdb_name(self): + return "irdb%d" % self.host.engine + + @property + def irdb(self): + prior_name = self.zoo.handle + return rpki.irdb.database( + self.irdb_name, + on_entry = lambda: self.zoo.reset_identity(self.name), + on_exit = lambda: self.zoo.reset_identity(prior_name)) + + def syncdb(self): + import django.core.management + assert not self.is_hosted + django.core.management.call_command("syncdb", + database = self.irdb_name, + load_initial_data = False, + interactive = False, + verbosity = 0) + + def hire_zookeeper(self): + assert not self.is_hosted + self._zoo = rpki.irdb.Zookeeper( + cfg = rpki.config.parser(self.path("rpki.conf")), + logstream = None if quiet else sys.stdout) + + @property + def zoo(self): + return self.host._zoo + + def dump_root(self): + + assert self.is_root and not self.is_hosted + + root_resources = rpki.resource_set.resource_bag( + asn = rpki.resource_set.resource_set_as("0-4294967295"), + v4 = rpki.resource_set.resource_set_ipv4("0.0.0.0/0"), + v6 = rpki.resource_set.resource_set_ipv6("::/0")) + + root_key = rpki.x509.RSA.generate(quiet = True) + + root_uri = "rsync://%s/rpki/" % self.rsync_server + + root_sia = (root_uri, root_uri + "root.mft", None) + + root_cert = rpki.x509.X509.self_certify( + keypair = root_key, + subject_key = root_key.get_RSApublic(), + serial = 1, + sia = root_sia, + notAfter = rpki.sundial.now() + rpki.sundial.timedelta(days = 365), + resources = root_resources) + + with open(self.path("publication.root", "root.cer"), "wb") as f: + f.write(root_cert.get_DER()) + + with open(self.path("root.key"), "wb") as f: + f.write(root_key.get_DER()) + + with open(cleanpath(test_dir, "root.tal"), "w") as f: + f.write("rsync://%s/root/root.cer\n\n%s" % ( + self.rsync_server, root_key.get_RSApublic().get_Base64())) + + def mkdir(self, *path): + path = self.path(*path) + if not quiet: + print "Creating directory", path + os.makedirs(path) + + def dump_sql(self): + if not self.is_hosted: + with open(self.path("rpkid.sql"), "w") as f: + if not quiet: + print "Writing", f.name + f.write(rpki.sql_schemas.rpkid) + if self.runs_pubd: + with open(self.path("pubd.sql"), "w") as f: + if not quiet: + print "Writing", f.name + f.write(rpki.sql_schemas.pubd) + if not self.is_hosted: + username = config_overrides["irdbd_sql_username"] + password = config_overrides["irdbd_sql_password"] + cmd = ("mysqldump", "-u", username, "-p" + password, self.irdb_name) + with open(self.path("irdbd.sql"), "w") as f: + if not quiet: + print "Writing", f.name + subprocess.check_call(cmd, stdout = f) + + +def pre_django_sql_setup(needed): + + username = config_overrides["irdbd_sql_username"] + password = config_overrides["irdbd_sql_password"] + + # If we have the MySQL root password, just blow away and recreate + # the required databases. Otherwise, check for missing databases, + # then blow away all tables in the required databases. In either + # case, we assume that the Django syncdb code will populate + # databases as necessary, all we need to do here is provide empty + # databases for the Django code to fill in. + + if mysql_rootpass is not None: + if mysql_rootpass: + db = MySQLdb.connect(user = mysql_rootuser, passwd = mysql_rootpass) + else: + db = MySQLdb.connect(user = mysql_rootuser) + cur = db.cursor() + for database in needed: + try: + cur.execute("DROP DATABASE IF EXISTS %s" % database) + except: + pass + cur.execute("CREATE DATABASE %s" % database) + cur.execute("GRANT ALL ON %s.* TO %s@localhost IDENTIFIED BY %%s" % ( + database, username), (password,)) + + else: + db = MySQLdb.connect(user = username, passwd = password) + cur = db.cursor() + cur.execute("SHOW DATABASES") + existing = set(r[0] for r in cur.fetchall()) + if needed - existing: + sys.stderr.write("The following databases are missing:\n") + for database in sorted(needed - existing): + sys.stderr.write(" %s\n" % database) + sys.stderr.write("Please create them manually or put MySQL root password in my config file\n") + sys.exit("Missing databases and MySQL root password not known, can't continue") + for database in needed: + db.select_db(database) + cur.execute("SHOW TABLES") + tables = [r[0] for r in cur.fetchall()] + cur.execute("SET foreign_key_checks = 0") + for table in tables: + cur.execute("DROP TABLE %s" % table) + cur.execute("SET foreign_key_checks = 1") + + cur.close() + db.commit() + db.close() + +class timestamp(object): + + def __init__(self, *args): + self.count = 0 + self.start = self.tick = rpki.sundial.now() + + def __call__(self, *args): + now = rpki.sundial.now() + if not quiet: + print "[Count %s last %s total %s now %s]" % ( + self.count, now - self.tick, now - self.start, now) + self.tick = now + self.count += 1 + + +def main(): + + global flat_publication + global config_overrides + global only_one_pubd + global loopback + global dns_suffix + global mysql_rootuser + global mysql_rootpass + global yaml_file + global test_dir + global rpki_conf + global publication_base + global publication_root + global quiet + + os.environ["TZ"] = "UTC" + time.tzset() + + parser = argparse.ArgumentParser(description = "yamlconf") + parser.add_argument("-c", "--config", help = "configuration file") + parser.add_argument("--dns_suffix", + help = "DNS suffix to add to hostnames") + parser.add_argument("-l", "--loopback", action = "store_true", + help = "Configure for use with yamltest on localhost") + parser.add_argument("-f", "--flat_publication", action = "store_true", + help = "Use flat publication model") + parser.add_argument("-q", "--quiet", action = "store_true", + help = "Work more quietly") + parser.add_argument("--profile", + help = "Filename for profile output") + parser.add_argument("yaml_file", type = argparse.FileType("r"), + help = "YAML file describing network to build") + args = parser.parse_args() + + dns_suffix = args.dns_suffix + loopback = args.loopback + flat_publication = args.flat_publication + quiet = args.quiet + yaml_file = args.yaml_file + + rpki.log.use_syslog = False + rpki.log.init("yamlconf") + + # Allow optional config file for this tool to override default + # passwords: this is mostly so that I can show a complete working + # example without publishing my own server's passwords. + + cfg = rpki.config.parser(args.config, "yamlconf", allow_missing = True) + try: + cfg.set_global_flags() + except: + pass + + # Use of "yamltest.dir" is deliberate: intent is for what we write to + # be usable with "yamltest --skip_config". + + only_one_pubd = cfg.getboolean("only_one_pubd", True) + test_dir = cfg.get("test_directory", cleanpath(this_dir, "yamltest.dir")) + rpki_conf = cfg.get("rpki_conf", cleanpath(this_dir, "..", "examples/rpki.conf")) + mysql_rootuser = cfg.get("mysql_rootuser", "root") + + try: + mysql_rootpass = cfg.get("mysql_rootpass") + except: + pass + + try: + publication_base = cfg.get("publication_base") + except: + pass + + try: + publication_root = cfg.get("publication_root") + except: + pass + + for k in ("rpkid_sql_password", "irdbd_sql_password", "pubd_sql_password", + "rpkid_sql_username", "irdbd_sql_username", "pubd_sql_username"): + if cfg.has_option(k): + config_overrides[k] = cfg.get(k) + + if args.profile: + import cProfile + prof = cProfile.Profile() + try: + prof.runcall(body) + finally: + prof.dump_stats(args.profile) + if not quiet: + print + print "Dumped profile data to %s" % args.profile + else: + body() + +def body(): + + global rpki + + ts = timestamp() + + for root, dirs, files in os.walk(test_dir, topdown = False): + for fn in files: + os.unlink(os.path.join(root, fn)) + for d in dirs: + os.rmdir(os.path.join(root, d)) + + if not quiet: + print + print "Reading YAML", yaml_file.name + + db = allocation_db(yaml.safe_load_all(yaml_file).next()) + + # Show what we loaded + + #db.dump() + + # Do pre-Django SQL setup + + pre_django_sql_setup(set(d.irdb_name for d in db if not d.is_hosted)) + + # Now ready for fun with multiple databases in Django! + + # https://docs.djangoproject.com/en/1.4/topics/db/multi-db/ + # https://docs.djangoproject.com/en/1.4/topics/db/sql/ + + database_template = { + "ENGINE" : "django.db.backends.mysql", + "USER" : config_overrides["irdbd_sql_username"], + "PASSWORD" : config_overrides["irdbd_sql_password"], + "HOST" : "", + "PORT" : "", + "OPTIONS" : { "init_command": "SET storage_engine=INNODB" }} + + databases = dict((d.irdb_name, + dict(database_template, NAME = d.irdb_name)) + for d in db if not d.is_hosted) + + databases["default"] = databases[db.root.irdb_name] + + from django.conf import settings + + settings.configure( + DATABASES = databases, + DATABASE_ROUTERS = ["rpki.irdb.router.DBContextRouter"], + INSTALLED_APPS = ("rpki.irdb",)) + + import rpki.irdb + + rpki.irdb.models.ca_certificate_lifetime = rpki.sundial.timedelta(days = 3652 * 2) + rpki.irdb.models.ee_certificate_lifetime = rpki.sundial.timedelta(days = 3652) + + ts() + + for d in db: + if not quiet: + print + print "Configuring", d.name + + if not d.is_hosted: + d.mkdir() + if d.runs_pubd: + d.mkdir("publication") + if d.is_root: + d.mkdir("publication.root") + + if not d.is_hosted: + d.dump_conf() + d.dump_rsyncd() + + d.dump_asns("%s.asns.csv" % d.name) + d.dump_prefixes("%s.prefixes.csv" % d.name) + d.dump_roas("%s.roas.csv" % d.name) + + if not d.is_hosted: + if not quiet: + print "Initializing SQL" + d.syncdb() + if not quiet: + print "Hiring zookeeper" + d.hire_zookeeper() + + with d.irdb: + if not quiet: + print "Creating identity" + x = d.zoo.initialize() + + if d.is_root: + if not quiet: + print "Creating RPKI root certificate and TAL" + d.dump_root() + x = d.zoo.configure_rootd() + + else: + with d.parent.irdb: + x = d.parent.zoo.configure_child(x.file)[0] + x = d.zoo.configure_parent(x.file)[0] + + with d.pubd.irdb: + x = d.pubd.zoo.configure_publication_client(x.file, flat = flat_publication)[0] + d.zoo.configure_repository(x.file) + + if loopback and not d.is_hosted: + with d.irdb: + d.zoo.write_bpki_files() + + ts() + + if not loopback: + if not quiet: + print + for d in db: + d.dump_sql() + +if __name__ == "__main__": + main() diff --git a/rpkid/tests/yamltest.py b/rpkid/tests/yamltest.py index 74013980..609a2599 100644 --- a/rpkid/tests/yamltest.py +++ b/rpkid/tests/yamltest.py @@ -15,7 +15,7 @@ Still to do: $Id$ -Copyright (C) 2009--2010 Internet Systems Consortium ("ISC") +Copyright (C) 2009--2012 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 @@ -42,19 +42,31 @@ 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 subprocess, re, os, getopt, sys, yaml, signal, time -import rpki.resource_set, rpki.sundial, rpki.config, rpki.log -import rpki.csv_utils, rpki.x509 +# pylint: disable=W0702,W0621 + +import subprocess +import re +import os +import getopt +import sys +import yaml +import signal +import time +import rpki.resource_set +import rpki.sundial +import rpki.config +import rpki.log +import rpki.csv_utils +import rpki.x509 # Nasty regular expressions for parsing config files. Sadly, while # the Python ConfigParser supports writing config files, it does so in # such a limited way that it's easier just to hack this ourselves. -section_regexp = re.compile("\s*\[\s*(.+?)\s*\]\s*$") -variable_regexp = re.compile("\s*([-a-zA-Z0-9_]+)\s*=\s*(.+?)\s*$") +section_regexp = re.compile(r"\s*\[\s*(.+?)\s*\]\s*$") +variable_regexp = re.compile(r"\s*([-a-zA-Z0-9_]+)\s*=\s*(.+?)\s*$") def cleanpath(*names): """ @@ -99,11 +111,11 @@ class roa_request(object): return "%s: %s" % (self.asn, self.v4 or self.v6) @classmethod - def parse(cls, yaml): + def parse(cls, y): """ Parse a ROA request from YAML format. """ - return cls(yaml.get("asn"), yaml.get("ipv4"), yaml.get("ipv6")) + return cls(y.get("asn"), y.get("ipv4"), y.get("ipv6")) class allocation_db(list): """ @@ -121,12 +133,6 @@ class allocation_db(list): if self.root.base.valid_until is None: self.root.base.valid_until = rpki.sundial.now() + rpki.sundial.timedelta(days = 2) for a in self: - if a.sia_base is None: - if a.runs_pubd: - base = "rsync://localhost:%d/rpki/" % a.rsync_port - else: - base = a.parent.sia_base - a.sia_base = base + a.name + "/" if a.base.valid_until is None: a.base.valid_until = a.parent.base.valid_until if a.crl_interval is None: @@ -168,6 +174,7 @@ class allocation(object): pubd_port = -1 rsync_port = -1 rootd_port = -1 + rpkic_counter = 0L @classmethod def allocate_port(cls): @@ -195,7 +202,7 @@ class allocation(object): self.kids = [allocation(k, db, self) for k in yaml.get("kids", ())] valid_until = None if "valid_until" in yaml: - valid_until = rpki.sundial.datetime.fromdatetime(yaml.get("valid_until")) + valid_until = rpki.sundial.datetime.from_datetime(yaml.get("valid_until")) if valid_until is None and "valid_for" in yaml: valid_until = rpki.sundial.now() + rpki.sundial.timedelta.parse(yaml["valid_for"]) self.base = rpki.resource_set.resource_bag( @@ -203,7 +210,6 @@ class allocation(object): v4 = rpki.resource_set.resource_set_ipv4(yaml.get("ipv4")), v6 = rpki.resource_set.resource_set_ipv6(yaml.get("ipv6")), valid_until = valid_until) - self.sia_base = yaml.get("sia_base") if "crl_interval" in yaml: self.crl_interval = rpki.sundial.timedelta.parse(yaml["crl_interval"]).convert_to_seconds() if "regen_margin" in yaml: @@ -211,9 +217,9 @@ class allocation(object): self.roa_requests = [roa_request.parse(y) for y in yaml.get("roa_request", yaml.get("route_origin", ()))] for r in self.roa_requests: if r.v4: - self.base.v4 = self.base.v4.union(r.v4.to_resource_set()) + self.base.v4 |= r.v4.to_resource_set() if r.v6: - self.base.v6 = self.base.v6.union(r.v6.to_resource_set()) + self.base.v6 |= r.v6.to_resource_set() self.hosted_by = yaml.get("hosted_by") self.hosts = [] if not self.is_hosted: @@ -233,7 +239,7 @@ class allocation(object): """ resources = self.base for kid in self.kids: - resources = resources.union(kid.closure()) + resources |= kid.closure() self.resources = resources return resources @@ -250,7 +256,6 @@ class allocation(object): if self.resources.v6: s += " IPv6: %s\n" % self.resources.v6 if self.kids: s += " Kids: %s\n" % ", ".join(k.name for k in self.kids) if self.parent: s += " Up: %s\n" % self.parent.name - if self.sia_base: s += " SIA: %s\n" % self.sia_base if self.is_hosted: s += " Host: %s\n" % self.hosted_by.name if self.hosts: s += " Hosts: %s\n" % ", ".join(h.name for h in self.hosts) for r in self.roa_requests: s += " ROA: %s\n" % r @@ -300,41 +305,48 @@ class allocation(object): """ Construct service URL for this node's parent. """ - parent_port = self.parent.hosted_by.rpkid_port if self.parent.is_hosted else self.parent.rpkid_port - return "http://localhost:%d/up-down/%s/%s" % (parent_port, self.parent.name, self.name) + return "http://localhost:%d/up-down/%s/%s" % (self.parent.host.rpkid_port, + self.parent.name, + self.name) - def dump_asns(self, fn, skip_rpkic = False): + def dump_asns(self): """ Write Autonomous System Numbers CSV file. """ - f = self.csvout(fn) - for k in self.kids: - f.writerows((k.name, a) for a in k.resources.asn) - f.close() - if not skip_rpkic: + fn = "%s.asns.csv" % d.name + if not skip_config: + f = self.csvout(fn) + for k in self.kids: + f.writerows((k.name, a) for a in k.resources.asn) + f.close() + if not stop_after_config: self.run_rpkic("load_asns", fn) - def dump_prefixes(self, fn, skip_rpkic = False): + def dump_prefixes(self): """ Write prefixes CSV file. """ - f = self.csvout(fn) - for k in self.kids: - f.writerows((k.name, p) for p in (k.resources.v4 + k.resources.v6)) - f.close() - if not skip_rpkic: + fn = "%s.prefixes.csv" % d.name + if not skip_config: + f = self.csvout(fn) + for k in self.kids: + f.writerows((k.name, p) for p in (k.resources.v4 + k.resources.v6)) + f.close() + if not stop_after_config: self.run_rpkic("load_prefixes", fn) - def dump_roas(self, fn, skip_rpkic = False): + def dump_roas(self): """ Write ROA CSV file. """ - f = self.csvout(fn) - for g1, r in enumerate(self.roa_requests): - f.writerows((p, r.asn, "G%08d%08d" % (g1, g2)) - for g2, p in enumerate((r.v4 + r.v6 if r.v4 and r.v6 else r.v4 or r.v6 or ()))) - f.close() - if not skip_rpkic: + fn = "%s.roas.csv" % d.name + if not skip_config: + f = self.csvout(fn) + for g1, r in enumerate(self.roa_requests): + f.writerows((p, r.asn, "G%08d%08d" % (g1, g2)) + for g2, p in enumerate((r.v4 + r.v6 if r.v4 and r.v6 else r.v4 or r.v6 or ()))) + f.close() + if not stop_after_config: self.run_rpkic("load_roa_requests", fn) @property @@ -365,7 +377,7 @@ class allocation(object): def host(self): return self.hosted_by or self - def dump_conf(self, fn): + def dump_conf(self): """ Write configuration file for OpenSSL and RPKI tools. """ @@ -392,7 +404,7 @@ class allocation(object): r.update(config_overrides) - f = open(self.path(fn), "w") + f = open(self.path("rpki.conf"), "w") f.write("# Automatically generated, do not edit\n") print "Writing", f.name @@ -409,13 +421,13 @@ class allocation(object): f.close() - def dump_rsyncd(self, fn): + def dump_rsyncd(self): """ Write rsyncd configuration file. """ if self.runs_pubd: - f = open(self.path(fn), "w") + f = open(self.path("rsyncd.conf"), "w") print "Writing", f.name f.writelines(s + "\n" for s in ("# Automatically generated, do not edit", @@ -426,9 +438,20 @@ class allocation(object): "read only = yes", "use chroot = no", "path = %s" % self.path("publication"), - "comment = RPKI test")) + "comment = RPKI test", + "[root]", + "log file = rsyncd_root.log", + "read only = yes", + "use chroot = no", + "path = %s" % self.path("publication.root"), + "comment = RPKI test root")) f.close() + @classmethod + def next_rpkic_counter(cls): + cls.rpkic_counter += 10000 + return str(cls.rpkic_counter) + def run_rpkic(self, *args): """ Run rpkic for this entity. @@ -439,7 +462,9 @@ class allocation(object): cmd.append(self.path("rpkic.%s.prof" % rpki.sundial.now())) cmd.extend(a for a in args if a is not None) print 'Running "%s"' % " ".join(cmd) - subprocess.check_call(cmd, cwd = self.host.path()) + env = os.environ.copy() + env["YAMLTEST_RPKIC_COUNTER"] = self.next_rpkic_counter() + subprocess.check_call(cmd, cwd = self.host.path(), env = env) def run_python_daemon(self, prog): """ @@ -502,10 +527,12 @@ skip_config = False flat_publication = False profile = False stop_after_config = False +synchronize = False opts, argv = getopt.getopt(sys.argv[1:], "c:fhkp:?", - ["config=", "flat_publication", "help", "keep_going", - "pidfile=", "skip_config", "stop_after_config", "profile"]) + ["config=", "flat_publication", "help", + "keep_going", "pidfile=", "profile", + "skip_config", "stop_after_config", "synchronize"]) for o, a in opts: if o in ("-h", "--help", "-?"): print __doc__ @@ -522,6 +549,8 @@ for o, a in opts: skip_config = True elif o == "--stop_after_config": stop_after_config = True + elif o == "--synchronize": + synchronize = True elif o == "--profile": profile = True @@ -556,13 +585,14 @@ try: "rpkid_sql_username", "irdbd_sql_username", "pubd_sql_username") if cfg.has_option(k)) - # Start clean + # Start clean, maybe - for root, dirs, files in os.walk(test_dir, topdown = False): - for file in files: - os.unlink(os.path.join(root, file)) - for dir in dirs: - os.rmdir(os.path.join(root, dir)) + if not skip_config: + for root, dirs, files in os.walk(test_dir, topdown = False): + for fn in files: + os.unlink(os.path.join(root, fn)) + for d in dirs: + os.rmdir(os.path.join(root, d)) # Read first YAML doc in file and process as compact description of # test layout and resource allocations. Ignore subsequent YAML docs, @@ -574,62 +604,69 @@ try: #db.dump() - # Set up each entity in our test + if skip_config: + + print "Skipping pre-daemon configuration, assuming you already did that" + + else: + + # Set up each entity in our test - for d in db: - if not d.is_hosted: - os.makedirs(d.path()) - d.dump_conf("rpki.conf") - if d.runs_pubd: - d.dump_rsyncd("rsyncd.conf") + for d in db: + if not d.is_hosted: + os.makedirs(d.path()) + d.dump_conf() + if d.runs_pubd: + d.dump_rsyncd() - # Initialize BPKI and generate self-descriptor for each entity. + # Initialize BPKI and generate self-descriptor for each entity. - for d in db: - d.run_rpkic("initialize") + for d in db: + d.run_rpkic("initialize") - # Create publication directories. + # Create publication directories. - for d in db: - if d.is_root or d.runs_pubd: - os.makedirs(d.path("publication")) + for d in db: + if d.runs_pubd: + os.makedirs(d.path("publication")) + if d.is_root: + os.makedirs(d.path("publication.root")) - # Create RPKI root certificate. + # Create RPKI root certificate. - print "Creating rootd RPKI root certificate" + print "Creating rootd RPKI root certificate" - root_resources = rpki.resource_set.resource_bag( - asn = rpki.resource_set.resource_set_as("0-4294967295"), - v4 = rpki.resource_set.resource_set_ipv4("0.0.0.0/0"), - v6 = rpki.resource_set.resource_set_ipv6("::/0")) + root_resources = rpki.resource_set.resource_bag( + asn = rpki.resource_set.resource_set_as("0-4294967295"), + v4 = rpki.resource_set.resource_set_ipv4("0.0.0.0/0"), + v6 = rpki.resource_set.resource_set_ipv6("::/0")) - root_key = rpki.x509.RSA.generate(quiet = True) + root_key = rpki.x509.RSA.generate(quiet = True) - root_uri = "rsync://localhost:%d/rpki/" % db.root.pubd.rsync_port + root_uri = "rsync://localhost:%d/rpki/" % db.root.pubd.rsync_port - root_sia = ((rpki.oids.name2oid["id-ad-caRepository"], ("uri", root_uri)), - (rpki.oids.name2oid["id-ad-rpkiManifest"], ("uri", root_uri + "root.mnf"))) + root_sia = (root_uri, root_uri + "root.mft", None) - root_cert = rpki.x509.X509.self_certify( - keypair = root_key, - subject_key = root_key.get_RSApublic(), - serial = 1, - sia = root_sia, - notAfter = rpki.sundial.now() + rpki.sundial.timedelta(days = 365), - resources = root_resources) + root_cert = rpki.x509.X509.self_certify( + keypair = root_key, + subject_key = root_key.get_RSApublic(), + serial = 1, + sia = root_sia, + notAfter = rpki.sundial.now() + rpki.sundial.timedelta(days = 365), + resources = root_resources) - f = open(db.root.path("publication/root.cer"), "wb") - f.write(root_cert.get_DER()) - f.close() + f = open(db.root.path("publication.root/root.cer"), "wb") + f.write(root_cert.get_DER()) + f.close() - f = open(db.root.path("root.key"), "wb") - f.write(root_key.get_DER()) - f.close() + f = open(db.root.path("root.key"), "wb") + f.write(root_key.get_DER()) + f.close() - f = open(os.path.join(test_dir, "root.tal"), "w") - f.write(root_uri + "root.cer\n") - f.write(root_key.get_RSApublic().get_Base64()) - f.close() + f = open(os.path.join(test_dir, "root.tal"), "w") + f.write("rsync://localhost:%d/root/root.cer\n\n" % db.root.pubd.rsync_port) + f.write(root_key.get_RSApublic().get_Base64()) + f.close() # From here on we need to pay attention to initialization order. We # used to do all the pre-configure_daemons stuff before running any @@ -643,16 +680,16 @@ try: for d in db: - print - print "Running daemons for", d.name - if d.is_root: - progs.append(d.run_rootd()) if not d.is_hosted: + print + print "Running daemons for", d.name + if d.is_root: + progs.append(d.run_rootd()) progs.append(d.run_irdbd()) progs.append(d.run_rpkid()) - if d.runs_pubd: - progs.append(d.run_pubd()) - progs.append(d.run_rsyncd()) + if d.runs_pubd: + progs.append(d.run_pubd()) + progs.append(d.run_rsyncd()) print print "Giving daemons time to start up" @@ -661,7 +698,7 @@ try: if skip_config: - print "Skipping configure_*, you'll have to do that yourself" + print "Skipping configure_*, you'll have to do that yourself if needed" else: @@ -670,7 +707,7 @@ try: print print "Configuring", d.name print - if d.is_root: + if d.is_root: assert not d.is_hosted d.run_rpkic("configure_publication_client", "--flat" if flat_publication else None, @@ -693,22 +730,31 @@ try: d.pubd.path("%s.repository-response.xml" % d.client_handle)) print - print - print "Loading CSV files" - print + print + print "Done with initial configuration" + print - for d in db: - d.dump_asns("%s.asns.csv" % d.name, stop_after_config) - d.dump_prefixes("%s.prefixes.csv" % d.name, stop_after_config) - d.dump_roas("%s.roas.csv" % d.name, stop_after_config) + if synchronize: + print + print "Synchronizing" + print + for d in db: + if not d.is_hosted: + d.run_rpkic("synchronize") - print - print "Done with initial configuration" - print + if synchronize or not skip_config: + print + print "Loading CSV files" + print + for d in db: + d.dump_asns() + d.dump_prefixes() + d.dump_roas() # Wait until something terminates. if not stop_after_config: + print print "Waiting for daemons to exit" signal.signal(signal.SIGCHLD, lambda *dont_care: None) while (any(p.poll() is None for p in progs) @@ -723,9 +769,31 @@ try: print signal.signal(signal.SIGCHLD, signal.SIG_DFL) + + if profile: + how_long = 300 + else: + how_long = 30 + + how_often = how_long / 2 + + for i in xrange(how_long): + if i % how_often == 0: + for p in progs: + if p.poll() is None: + print "Politely nudging pid %d" % p.pid + p.terminate() + print + if all(p.poll() is not None for p in progs): + break + time.sleep(1) + for p in progs: if p.poll() is None: - os.kill(p.pid, signal.SIGTERM) + print "Pulling the plug on pid %d" % p.pid + p.kill() + + for p in progs: print "Program pid %d %r returned %d" % (p.pid, p, p.wait()) finally: |