Commit 9a152138 authored by Jérome Perrin's avatar Jérome Perrin

More python3 compatibility

Printing using file= argument to print only worksfor binary files so we
cannot use constructs like print(b'', file=io.BytesIO()) because it
would actually print "b''" on python 3.

Change also the stdout capture in test to use text files.
parent be9ef7a2
Pipeline #6405 failed with stage
in 0 seconds
...@@ -77,7 +77,7 @@ class RetryingCaucaseClient(CaucaseClient): ...@@ -77,7 +77,7 @@ class RetryingCaucaseClient(CaucaseClient):
next_try = datetime.datetime.utcnow() + datetime.timedelta(0, 10) next_try = datetime.datetime.utcnow() + datetime.timedelta(0, 10)
print( print(
'Got a network error, retrying at %s, %s: %r' % ( 'Got a network error, retrying at %s, %s: %r' % (
next_try.strftime(b'%Y-%m-%d %H:%M:%S +0000'), next_try.strftime('%Y-%m-%d %H:%M:%S +0000'),
exception.__class__.__name__, exception.__class__.__name__,
str(exception), str(exception),
), ),
...@@ -114,7 +114,7 @@ class CLICaucaseClient(object): ...@@ -114,7 +114,7 @@ class CLICaucaseClient(object):
utils.load_certificate_request(csr_pem) utils.load_certificate_request(csr_pem)
print( print(
self._client.createCertificateSigningRequest(csr_pem), self._client.createCertificateSigningRequest(csr_pem),
utils.toBytes(csr_path), utils.toUnicode(csr_path),
) )
def getCSR(self, csr_id_path_list): def getCSR(self, csr_id_path_list):
...@@ -142,10 +142,10 @@ class CLICaucaseClient(object): ...@@ -142,10 +142,10 @@ class CLICaucaseClient(object):
except CaucaseError as e: except CaucaseError as e:
if e.args[0] != httplib.NOT_FOUND: if e.args[0] != httplib.NOT_FOUND:
raise raise
print(crt_id, b'not found - maybe CSR was rejected ?') print(crt_id, 'not found - maybe CSR was rejected ?')
error = True error = True
else: else:
print(crt_id, b'CSR still pending') print(crt_id, 'CSR still pending')
warning = True warning = True
else: else:
print(crt_id, end=' ') print(crt_id, end=' ')
...@@ -154,15 +154,15 @@ class CLICaucaseClient(object): ...@@ -154,15 +154,15 @@ class CLICaucaseClient(object):
ca_list, ca_list,
None, None,
)): )):
print(b'was (originally) automatically approved') print('was (originally) automatically approved')
else: else:
print(b'was (originally) manually approved') print('was (originally) manually approved')
if os.path.exists(crt_path): if os.path.exists(crt_path):
try: try:
key_pem = utils.getKey(crt_path) key_pem = utils.getKey(crt_path)
except ValueError: except ValueError:
print( print(
b'Expected to find exactly one privatekey key in %s, skipping' % ( 'Expected to find exactly one privatekey key in %s, skipping' % (
crt_path, crt_path,
), ),
file=sys.stderr, file=sys.stderr,
...@@ -173,7 +173,7 @@ class CLICaucaseClient(object): ...@@ -173,7 +173,7 @@ class CLICaucaseClient(object):
utils.validateCertAndKey(crt_pem, key_pem) utils.validateCertAndKey(crt_pem, key_pem)
except ValueError: except ValueError:
print( print(
b'Key in %s does not match retrieved certificate, skipping' % ( 'Key in %s does not match retrieved certificate, skipping' % (
crt_path, crt_path,
), ),
file=sys.stderr, file=sys.stderr,
...@@ -193,7 +193,7 @@ class CLICaucaseClient(object): ...@@ -193,7 +193,7 @@ class CLICaucaseClient(object):
crt, key, _ = utils.getKeyPair(crt_path, key_path) crt, key, _ = utils.getKeyPair(crt_path, key_path)
except ValueError: except ValueError:
print( print(
b'Could not find (exactly) one matching key pair in %s, skipping' % ( 'Could not find (exactly) one matching key pair in %s, skipping' % (
[x for x in set((crt_path, key_path)) if x], [x for x in set((crt_path, key_path)) if x],
), ),
file=sys.stderr, file=sys.stderr,
...@@ -223,7 +223,7 @@ class CLICaucaseClient(object): ...@@ -223,7 +223,7 @@ class CLICaucaseClient(object):
) )
except ValueError: except ValueError:
print( print(
b'Could not find (exactly) one matching key pair in %s, skipping' % ( 'Could not find (exactly) one matching key pair in %s, skipping' % (
[x for x in set((crt_path, key_path)) if x], [x for x in set((crt_path, key_path)) if x],
), ),
file=sys.stderr, file=sys.stderr,
...@@ -239,11 +239,11 @@ class CLICaucaseClient(object): ...@@ -239,11 +239,11 @@ class CLICaucaseClient(object):
except exceptions.CertificateVerificationError: except exceptions.CertificateVerificationError:
print( print(
crt_path, crt_path,
b'was not signed by this CA, revoked or otherwise invalid, skipping', 'was not signed by this CA, revoked or otherwise invalid, skipping',
) )
continue continue
if renewal_deadline < old_crt.not_valid_after: if renewal_deadline < old_crt.not_valid_after:
print(crt_path, b'did not reach renew threshold, not renewing') print(crt_path, 'did not reach renew threshold, not renewing')
continue continue
new_key_pem, new_crt_pem = self._client.renewCertificate( new_key_pem, new_crt_pem = self._client.renewCertificate(
old_crt=old_crt, old_crt=old_crt,
...@@ -271,22 +271,22 @@ class CLICaucaseClient(object): ...@@ -271,22 +271,22 @@ class CLICaucaseClient(object):
""" """
--list-csr --list-csr
""" """
print(b'-- pending', mode, b'CSRs --') print('-- pending', mode, 'CSRs --')
print( print(
b'%20s | %s' % ( '%20s | %s' % (
b'csr_id', 'csr_id',
b'subject preview (fetch csr and check full content !)', 'subject preview (fetch csr and check full content !)',
), ),
) )
for entry in self._client.getPendingCertificateRequestList(): for entry in self._client.getPendingCertificateRequestList():
csr = utils.load_certificate_request(utils.toBytes(entry['csr'])) csr = utils.load_certificate_request(utils.toBytes(entry['csr']))
print( print(
b'%20s | %r' % ( '%20s | %r' % (
utils.toBytes(entry['id']), entry['id'],
utils.toBytes(repr(csr.subject)), repr(csr.subject),
), ),
) )
print(b'-- end of pending', mode, b'CSRs --') print('-- end of pending', mode, 'CSRs --')
def signCSR(self, csr_id_list): def signCSR(self, csr_id_list):
""" """
...@@ -330,7 +330,7 @@ class CLICaucaseClient(object): ...@@ -330,7 +330,7 @@ class CLICaucaseClient(object):
crt_pem = utils.getCert(crt_path) crt_pem = utils.getCert(crt_path)
except ValueError: except ValueError:
print( print(
b'Could not load a single certificate in %s, skipping' % ( 'Could not load a single certificate in %s, skipping' % (
crt_path, crt_path,
), ),
file=sys.stderr, file=sys.stderr,
...@@ -553,8 +553,8 @@ def main(argv=None): ...@@ -553,8 +553,8 @@ def main(argv=None):
sign_csr_id_set.intersection(sign_with_csr_id_set) sign_csr_id_set.intersection(sign_with_csr_id_set)
): ):
print( print(
b'A given CSR_ID cannot be in more than one of --sign-csr, ' 'A given CSR_ID cannot be in more than one of --sign-csr, '
b'--sign-csr-with and --reject-csr', '--sign-csr-with and --reject-csr',
file=sys.stderr, file=sys.stderr,
) )
raise SystemExit(STATUS_ERROR) raise SystemExit(STATUS_ERROR)
...@@ -790,12 +790,12 @@ def updater(argv=None, until=utils.until): ...@@ -790,12 +790,12 @@ def updater(argv=None, until=utils.until):
ca_crt_pem_list=utils.getCertList(args.cas_ca) ca_crt_pem_list=utils.getCertList(args.cas_ca)
) )
if args.crt and not utils.hasOneCert(args.crt): if args.crt and not utils.hasOneCert(args.crt):
print(b'Bootstraping...') print('Bootstraping...')
csr_pem = utils.getCertRequest(args.csr) csr_pem = utils.getCertRequest(args.csr)
# Quick sanity check before bothering server # Quick sanity check before bothering server
utils.load_certificate_request(csr_pem) utils.load_certificate_request(csr_pem)
csr_id = client.createCertificateSigningRequest(csr_pem) csr_id = client.createCertificateSigningRequest(csr_pem)
print(b'Waiting for signature of', csr_id) print('Waiting for signature of', csr_id)
while True: while True:
try: try:
crt_pem = client.getCertificate(csr_id) crt_pem = client.getCertificate(csr_id)
...@@ -813,12 +813,12 @@ def updater(argv=None, until=utils.until): ...@@ -813,12 +813,12 @@ def updater(argv=None, until=utils.until):
crt_file.write(crt_pem) crt_file.write(crt_pem)
updated = True updated = True
break break
print(b'Bootstrap done') print('Bootstrap done')
next_deadline = datetime.datetime.utcnow() next_deadline = datetime.datetime.utcnow()
while True: while True:
print( print(
b'Next wake-up at', 'Next wake-up at',
next_deadline.strftime(b'%Y-%m-%d %H:%M:%S +0000'), next_deadline.strftime('%Y-%m-%d %H:%M:%S +0000'),
) )
now = until(next_deadline) now = until(next_deadline)
next_deadline = now + max_sleep next_deadline = now + max_sleep
...@@ -831,7 +831,7 @@ def updater(argv=None, until=utils.until): ...@@ -831,7 +831,7 @@ def updater(argv=None, until=utils.until):
ca_crt_pem_list=utils.getCertList(args.cas_ca) ca_crt_pem_list=utils.getCertList(args.cas_ca)
) )
if RetryingCaucaseClient.updateCAFile(ca_url, args.ca): if RetryingCaucaseClient.updateCAFile(ca_url, args.ca):
print(b'Got new CA') print('Got new CA')
updated = True updated = True
# Note: CRL expiration should happen several time during CA renewal # Note: CRL expiration should happen several time during CA renewal
# period, so it should not be needed to keep track of CA expiration # period, so it should not be needed to keep track of CA expiration
...@@ -841,7 +841,7 @@ def updater(argv=None, until=utils.until): ...@@ -841,7 +841,7 @@ def updater(argv=None, until=utils.until):
for x in utils.getCertList(args.ca) for x in utils.getCertList(args.ca)
] ]
if RetryingCaucaseClient.updateCRLFile(ca_url, args.crl, ca_crt_list): if RetryingCaucaseClient.updateCRLFile(ca_url, args.crl, ca_crt_list):
print(b'Got new CRL') print('Got new CRL')
updated = True updated = True
with open(args.crl, 'rb') as crl_file: with open(args.crl, 'rb') as crl_file:
next_deadline = min( next_deadline = min(
...@@ -852,7 +852,7 @@ def updater(argv=None, until=utils.until): ...@@ -852,7 +852,7 @@ def updater(argv=None, until=utils.until):
crt_pem, key_pem, key_path = utils.getKeyPair(args.crt, args.key) crt_pem, key_pem, key_path = utils.getKeyPair(args.crt, args.key)
crt = utils.load_certificate(crt_pem, ca_crt_list, None) crt = utils.load_certificate(crt_pem, ca_crt_list, None)
if crt.not_valid_after - threshold <= now: if crt.not_valid_after - threshold <= now:
print(b'Renewing', args.crt) print('Renewing', args.crt)
new_key_pem, new_crt_pem = client.renewCertificate( new_key_pem, new_crt_pem = client.renewCertificate(
old_crt=crt, old_crt=crt,
old_key=utils.load_privatekey(key_pem), old_key=utils.load_privatekey(key_pem),
...@@ -882,7 +882,7 @@ def updater(argv=None, until=utils.until): ...@@ -882,7 +882,7 @@ def updater(argv=None, until=utils.until):
if args.on_renew is not None: if args.on_renew is not None:
status = os.system(args.on_renew) status = os.system(args.on_renew)
if status: if status:
print(b'Renewal hook exited with status:', status, file=sys.stderr) print('Renewal hook exited with status:', status, file=sys.stderr)
raise SystemExit(STATUS_ERROR) raise SystemExit(STATUS_ERROR)
updated = False updated = False
except (utils.SleepInterrupt, SystemExit): except (utils.SleepInterrupt, SystemExit):
...@@ -1003,4 +1003,4 @@ def key_id(argv=None): ...@@ -1003,4 +1003,4 @@ def key_id(argv=None):
backup_file.read(struct.calcsize('<I')), backup_file.read(struct.calcsize('<I')),
) )
for key_entry in json.loads(backup_file.read(header_len))['key_list']: for key_entry in json.loads(backup_file.read(header_len))['key_list']:
print(b' ', key_entry['id'].encode('utf-8')) print(' ', key_entry['id'].encode('utf-8'))
...@@ -1050,11 +1050,11 @@ def manage(argv=None): ...@@ -1050,11 +1050,11 @@ def manage(argv=None):
found_from = ', '.join(ca_pair['from']) found_from = ', '.join(ca_pair['from'])
crt = ca_pair['crt'] crt = ca_pair['crt']
if crt is None: if crt is None:
print(b'No certificate correspond to', found_from, b'- skipping') print('No certificate correspond to', found_from, '- skipping')
continue continue
expiration = utils.datetime2timestamp(crt.not_valid_after) expiration = utils.datetime2timestamp(crt.not_valid_after)
if expiration < now: if expiration < now:
print(b'Skipping expired certificate from', found_from) print('Skipping expired certificate from', found_from)
del import_ca_dict[identifier] del import_ca_dict[identifier]
continue continue
if not args.import_bad_ca: if not args.import_bad_ca:
...@@ -1073,11 +1073,11 @@ def manage(argv=None): ...@@ -1073,11 +1073,11 @@ def manage(argv=None):
or not key_usage.key_cert_sign or not key_usage.crl_sign or not key_usage.key_cert_sign or not key_usage.crl_sign
) )
if failed: if failed:
print(b'Skipping non-CA certificate from', found_from) print('Skipping non-CA certificate from', found_from)
continue continue
key = ca_pair['key'] key = ca_pair['key']
if key is None: if key is None:
print(b'No private key correspond to', found_from, b'- skipping') print('No private key correspond to', found_from, '- skipping')
continue continue
imported += 1 imported += 1
cas_db.appendCAKeyPair( cas_db.appendCAKeyPair(
...@@ -1089,7 +1089,7 @@ def manage(argv=None): ...@@ -1089,7 +1089,7 @@ def manage(argv=None):
) )
if not imported: if not imported:
raise ValueError('No CA certificate imported') raise ValueError('No CA certificate imported')
print(b'Imported %i CA certificates' % imported) print('Imported %i CA certificates' % imported)
if args.import_crl: if args.import_crl:
db = SQLite3Storage(db_path, table_prefix='cas') db = SQLite3Storage(db_path, table_prefix='cas')
trusted_ca_crt_set = [ trusted_ca_crt_set = [
...@@ -1112,7 +1112,7 @@ def manage(argv=None): ...@@ -1112,7 +1112,7 @@ def manage(argv=None):
already_revoked_count += 1 already_revoked_count += 1
else: else:
revoked_count += 1 revoked_count += 1
print(b'Revoked %i certificates (%i were already revoked)' % ( print('Revoked %i certificates (%i were already revoked)' % (
revoked_count, revoked_count,
already_revoked_count, already_revoked_count,
)) ))
......
...@@ -30,7 +30,8 @@ import functools ...@@ -30,7 +30,8 @@ import functools
import glob import glob
import HTMLParser import HTMLParser
import httplib import httplib
from io import BytesIO, StringIO from io import BytesIO
from StringIO import StringIO
import ipaddress import ipaddress
import json import json
import os import os
...@@ -287,7 +288,7 @@ def print_buffer_on_error(func): ...@@ -287,7 +288,7 @@ def print_buffer_on_error(func):
try: try:
return func(self, *args, **kw) return func(self, *args, **kw)
except Exception: # pragma : no cover except Exception: # pragma : no cover
sys.stdout.write(utils.toBytes(os.linesep)) sys.stdout.write(os.linesep)
sys.stdout.write(self.caucase_test_output.getvalue()) sys.stdout.write(self.caucase_test_output.getvalue())
raise raise
return wrapper return wrapper
...@@ -295,11 +296,11 @@ def print_buffer_on_error(func): ...@@ -295,11 +296,11 @@ def print_buffer_on_error(func):
@contextlib.contextmanager @contextlib.contextmanager
def captureStdout(): def captureStdout():
""" """
Replace stdout with a BytesIO object for the duration of the context manager, Replace stdout with a StringIO object for the duration of the context manager,
and provide it to caller. and provide it to caller.
""" """
orig_stdout = sys.stdout orig_stdout = sys.stdout
sys.stdout = stdout = BytesIO() sys.stdout = stdout = StringIO()
try: try:
yield stdout yield stdout
finally: finally:
...@@ -337,7 +338,7 @@ class CaucaseTest(unittest.TestCase): ...@@ -337,7 +338,7 @@ class CaucaseTest(unittest.TestCase):
self._server_backup_path = os.path.join(server_dir, 'backup') self._server_backup_path = os.path.join(server_dir, 'backup')
self._server_cors_store = os.path.join(server_dir, 'cors.key') self._server_cors_store = os.path.join(server_dir, 'cors.key')
# pylint: enable=bad-whitespace # pylint: enable=bad-whitespace
self.caucase_test_output = BytesIO() self.caucase_test_output = StringIO()
os.mkdir(self._server_backup_path) os.mkdir(self._server_backup_path)
self._server_netloc = netloc = os.getenv( self._server_netloc = netloc = os.getenv(
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment