text
stringlengths 81
112k
|
---|
Install just the base environment, no distutils patches etc
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear):
"""Install just the base environment, no distutils patches etc"""
if sys.executable.startswith(bin_dir):
print 'Please use the *system* python to run this script'
return
if clear:
rmtree(lib_dir)
## FIXME: why not delete it?
## Maybe it should delete everything with #!/path/to/venv/python in it
logger.notify('Not deleting %s', bin_dir)
if hasattr(sys, 'real_prefix'):
logger.notify('Using real prefix %r' % sys.real_prefix)
prefix = sys.real_prefix
else:
prefix = sys.prefix
mkdir(lib_dir)
fix_lib64(lib_dir)
stdlib_dirs = [os.path.dirname(os.__file__)]
if sys.platform == 'win32':
stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs'))
elif sys.platform == 'darwin':
stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages'))
for stdlib_dir in stdlib_dirs:
if not os.path.isdir(stdlib_dir):
continue
if hasattr(os, 'symlink'):
logger.info('Symlinking Python bootstrap modules')
else:
logger.info('Copying Python bootstrap modules')
logger.indent += 2
try:
for fn in os.listdir(stdlib_dir):
if fn != 'site-packages' and os.path.splitext(fn)[0] in REQUIRED_MODULES:
copyfile(join(stdlib_dir, fn), join(lib_dir, fn))
finally:
logger.indent -= 2
mkdir(join(lib_dir, 'site-packages'))
writefile(join(lib_dir, 'site.py'), SITE_PY)
writefile(join(lib_dir, 'orig-prefix.txt'), prefix)
site_packages_filename = join(lib_dir, 'no-global-site-packages.txt')
if not site_packages:
writefile(site_packages_filename, '')
else:
if os.path.exists(site_packages_filename):
logger.info('Deleting %s' % site_packages_filename)
os.unlink(site_packages_filename)
stdinc_dir = join(prefix, 'include', py_version)
if os.path.exists(stdinc_dir):
copyfile(stdinc_dir, inc_dir)
else:
logger.debug('No include dir %s' % stdinc_dir)
if sys.exec_prefix != prefix:
if sys.platform == 'win32':
exec_dir = join(sys.exec_prefix, 'lib')
elif is_jython:
exec_dir = join(sys.exec_prefix, 'Lib')
else:
exec_dir = join(sys.exec_prefix, 'lib', py_version)
for fn in os.listdir(exec_dir):
copyfile(join(exec_dir, fn), join(lib_dir, fn))
if is_jython:
# Jython has either jython-dev.jar and javalib/ dir, or just
# jython.jar
for name in 'jython-dev.jar', 'javalib', 'jython.jar':
src = join(prefix, name)
if os.path.exists(src):
copyfile(src, join(home_dir, name))
# XXX: registry should always exist after Jython 2.5rc1
src = join(prefix, 'registry')
if os.path.exists(src):
copyfile(src, join(home_dir, 'registry'), symlink=False)
copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'),
symlink=False)
mkdir(bin_dir)
py_executable = join(bin_dir, os.path.basename(sys.executable))
if 'Python.framework' in prefix:
if re.search(r'/Python(?:-32|-64)*$', py_executable):
# The name of the python executable is not quite what
# we want, rename it.
py_executable = os.path.join(
os.path.dirname(py_executable), 'python')
logger.notify('New %s executable in %s', expected_exe, py_executable)
if sys.executable != py_executable:
## FIXME: could I just hard link?
executable = sys.executable
if sys.platform == 'cygwin' and os.path.exists(executable + '.exe'):
# Cygwin misreports sys.executable sometimes
executable += '.exe'
py_executable += '.exe'
logger.info('Executable actually exists in %s' % executable)
shutil.copyfile(executable, py_executable)
make_exe(py_executable)
if sys.platform == 'win32' or sys.platform == 'cygwin':
pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe')
if os.path.exists(pythonw):
logger.info('Also created pythonw.exe')
shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe'))
if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe:
secondary_exe = os.path.join(os.path.dirname(py_executable),
expected_exe)
py_executable_ext = os.path.splitext(py_executable)[1]
if py_executable_ext == '.exe':
# python2.4 gives an extension of '.4' :P
secondary_exe += py_executable_ext
if os.path.exists(secondary_exe):
logger.warn('Not overwriting existing %s script %s (you must use %s)'
% (expected_exe, secondary_exe, py_executable))
else:
logger.notify('Also creating executable in %s' % secondary_exe)
shutil.copyfile(sys.executable, secondary_exe)
make_exe(secondary_exe)
if 'Python.framework' in prefix:
logger.debug('MacOSX Python framework detected')
# Make sure we use the the embedded interpreter inside
# the framework, even if sys.executable points to
# the stub executable in ${sys.prefix}/bin
# See http://groups.google.com/group/python-virtualenv/
# browse_thread/thread/17cab2f85da75951
shutil.copy(
os.path.join(
prefix, 'Resources/Python.app/Contents/MacOS/%s' % os.path.basename(sys.executable)),
py_executable)
# Copy the framework's dylib into the virtual
# environment
virtual_lib = os.path.join(home_dir, '.Python')
if os.path.exists(virtual_lib):
os.unlink(virtual_lib)
copyfile(
os.path.join(prefix, 'Python'),
virtual_lib)
# And then change the install_name of the copied python executable
try:
call_subprocess(
["install_name_tool", "-change",
os.path.join(prefix, 'Python'),
'@executable_path/../.Python',
py_executable])
except:
logger.fatal(
"Could not call install_name_tool -- you must have Apple's development tools installed")
raise
# Some tools depend on pythonX.Y being present
py_executable_version = '%s.%s' % (
sys.version_info[0], sys.version_info[1])
if not py_executable.endswith(py_executable_version):
# symlinking pythonX.Y > python
pth = py_executable + '%s.%s' % (
sys.version_info[0], sys.version_info[1])
if os.path.exists(pth):
os.unlink(pth)
os.symlink('python', pth)
else:
# reverse symlinking python -> pythonX.Y (with --python)
pth = join(bin_dir, 'python')
if os.path.exists(pth):
os.unlink(pth)
os.symlink(os.path.basename(py_executable), pth)
if sys.platform == 'win32' and ' ' in py_executable:
# There's a bug with subprocess on Windows when using a first
# argument that has a space in it. Instead we have to quote
# the value:
py_executable = '"%s"' % py_executable
cmd = [py_executable, '-c', 'import sys; print sys.prefix']
logger.info('Testing executable with %s %s "%s"' % tuple(cmd))
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE)
proc_stdout, proc_stderr = proc.communicate()
proc_stdout = os.path.normcase(os.path.abspath(proc_stdout.strip()))
if proc_stdout != os.path.normcase(os.path.abspath(home_dir)):
logger.fatal(
'ERROR: The executable %s is not functioning' % py_executable)
logger.fatal(
'ERROR: It thinks sys.prefix is %r (should be %r)'
% (proc_stdout, os.path.normcase(os.path.abspath(home_dir))))
logger.fatal(
'ERROR: virtualenv is not compatible with this system or executable')
if sys.platform == 'win32':
logger.fatal(
'Note: some Windows users have reported this error when they installed Python for "Only this user". The problem may be resolvable if you install Python "For all users". (See https://bugs.launchpad.net/virtualenv/+bug/352844)')
sys.exit(100)
else:
logger.info('Got sys.prefix result: %r' % proc_stdout)
pydistutils = os.path.expanduser('~/.pydistutils.cfg')
if os.path.exists(pydistutils):
logger.notify('Please make sure you remove any previous custom paths from '
'your %s file.' % pydistutils)
## FIXME: really this should be calculated earlier
return py_executable
|
Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
instead of lib/pythonX.Y. If this is such a platform we'll just create a
symlink so lib64 points to lib
def fix_lib64(lib_dir):
"""
Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
instead of lib/pythonX.Y. If this is such a platform we'll just create a
symlink so lib64 points to lib
"""
if [p for p in distutils.sysconfig.get_config_vars().values()
if isinstance(p, basestring) and 'lib64' in p]:
logger.debug('This system uses lib64; symlinking lib64 to lib')
assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], (
"Unexpected python lib dir: %r" % lib_dir)
lib_parent = os.path.dirname(lib_dir)
assert os.path.basename(lib_parent) == 'lib', (
"Unexpected parent dir: %r" % lib_parent)
copyfile(lib_parent, os.path.join(os.path.dirname(lib_parent), 'lib64'))
|
If the executable given isn't an absolute path, search $PATH for the interpreter
def resolve_interpreter(exe):
"""
If the executable given isn't an absolute path, search $PATH for the interpreter
"""
if os.path.abspath(exe) != exe:
paths = os.environ.get('PATH', '').split(os.pathsep)
for path in paths:
if os.path.exists(os.path.join(path, exe)):
exe = os.path.join(path, exe)
break
if not os.path.exists(exe):
logger.fatal('The executable %s (from --python=%s) does not exist' % (exe, exe))
sys.exit(3)
return exe
|
Makes the already-existing environment use relative paths, and takes out
the #!-based environment selection in scripts.
def make_environment_relocatable(home_dir):
"""
Makes the already-existing environment use relative paths, and takes out
the #!-based environment selection in scripts.
"""
activate_this = os.path.join(home_dir, 'bin', 'activate_this.py')
if not os.path.exists(activate_this):
logger.fatal(
'The environment doesn\'t have a file %s -- please re-run virtualenv '
'on this environment to update it' % activate_this)
fixup_scripts(home_dir)
fixup_pth_and_egg_link(home_dir)
|
<Purpose>
Generate public and private RSA keys, with modulus length 'bits'. In
addition, a keyid identifier for the RSA key is generated. The object
returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the
form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The public and private keys are strings in PEM format.
Although the PyCA cryptography library and/or its crypto backend might set
a minimum key size, generate() enforces a minimum key size of 2048 bits.
If 'bits' is unspecified, a 3072-bit RSA key is generated, which is the key
size recommended by securesystemslib. These key size restrictions are only
enforced for keys generated within securesystemslib. RSA keys with sizes
lower than what we recommended may still be imported (e.g., with
import_rsakey_from_pem().
>>> rsa_key = generate_rsa_key(bits=2048)
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key)
True
>>> public = rsa_key['keyval']['public']
>>> private = rsa_key['keyval']['private']
>>> securesystemslib.formats.PEMRSA_SCHEMA.matches(public)
True
>>> securesystemslib.formats.PEMRSA_SCHEMA.matches(private)
True
<Arguments>
bits:
The key size, or key length, of the RSA key. 'bits' must be 2048, or
greater, and a multiple of 256.
scheme:
The signature scheme used by the key. It must be one of
['rsassa-pss-sha256'].
<Exceptions>
securesystemslib.exceptions.FormatError, if 'bits' is improperly or invalid
(i.e., not an integer and not at least 2048).
ValueError, if an exception occurs after calling the RSA key generation
routine. The 'ValueError' exception is raised by the key generation
function of the cryptography library called.
<Side Effects>
None.
<Returns>
A dictionary containing the RSA keys and other identifying information.
Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
def generate_rsa_key(bits=_DEFAULT_RSA_KEY_BITS, scheme='rsassa-pss-sha256'):
"""
<Purpose>
Generate public and private RSA keys, with modulus length 'bits'. In
addition, a keyid identifier for the RSA key is generated. The object
returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the
form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The public and private keys are strings in PEM format.
Although the PyCA cryptography library and/or its crypto backend might set
a minimum key size, generate() enforces a minimum key size of 2048 bits.
If 'bits' is unspecified, a 3072-bit RSA key is generated, which is the key
size recommended by securesystemslib. These key size restrictions are only
enforced for keys generated within securesystemslib. RSA keys with sizes
lower than what we recommended may still be imported (e.g., with
import_rsakey_from_pem().
>>> rsa_key = generate_rsa_key(bits=2048)
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key)
True
>>> public = rsa_key['keyval']['public']
>>> private = rsa_key['keyval']['private']
>>> securesystemslib.formats.PEMRSA_SCHEMA.matches(public)
True
>>> securesystemslib.formats.PEMRSA_SCHEMA.matches(private)
True
<Arguments>
bits:
The key size, or key length, of the RSA key. 'bits' must be 2048, or
greater, and a multiple of 256.
scheme:
The signature scheme used by the key. It must be one of
['rsassa-pss-sha256'].
<Exceptions>
securesystemslib.exceptions.FormatError, if 'bits' is improperly or invalid
(i.e., not an integer and not at least 2048).
ValueError, if an exception occurs after calling the RSA key generation
routine. The 'ValueError' exception is raised by the key generation
function of the cryptography library called.
<Side Effects>
None.
<Returns>
A dictionary containing the RSA keys and other identifying information.
Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
"""
# Does 'bits' have the correct format? This check will ensure 'bits'
# conforms to 'securesystemslib.formats.RSAKEYBITS_SCHEMA'. 'bits' must be
# an integer object, with a minimum value of 2048. Raise
# 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(bits)
securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme)
# Begin building the RSA key dictionary.
rsakey_dict = {}
keytype = 'rsa'
public = None
private = None
# Generate the public and private RSA keys. The pyca/cryptography module is
# used to generate the actual key. Raise 'ValueError' if 'bits' is less than
# 1024, although a 2048-bit minimum is enforced by
# securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match().
public, private = securesystemslib.pyca_crypto_keys.generate_rsa_public_and_private(bits)
# When loading in PEM keys, extract_pem() is called, which strips any
# leading or trailing new line characters. Do the same here before generating
# the keyid.
public = extract_pem(public, private_pem=False)
private = extract_pem(private, private_pem=True)
# Generate the keyid of the RSA key. Note: The private key material is not
# included in the generation of the 'keyid' identifier. Convert any '\r\n'
# (e.g., Windows) newline characters to '\n' so that a consistent keyid is
# generated.
key_value = {'public': public.replace('\r\n', '\n'),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
# Build the 'rsakey_dict' dictionary. Update 'key_value' with the RSA
# private key prior to adding 'key_value' to 'rsakey_dict'.
key_value['private'] = private
rsakey_dict['keytype'] = keytype
rsakey_dict['scheme'] = scheme
rsakey_dict['keyid'] = keyid
rsakey_dict['keyid_hash_algorithms'] = securesystemslib.settings.HASH_ALGORITHMS
rsakey_dict['keyval'] = key_value
return rsakey_dict
|
<Purpose>
Generate public and private ECDSA keys, with NIST P-256 + SHA256 (for
hashing) being the default scheme. In addition, a keyid identifier for the
ECDSA key is generated. The object returned conforms to
'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form:
{'keytype': 'ecdsa-sha2-nistp256',
'scheme', 'ecdsa-sha2-nistp256',
'keyid': keyid,
'keyval': {'public': '',
'private': ''}}
The public and private keys are strings in TODO format.
>>> ecdsa_key = generate_ecdsa_key(scheme='ecdsa-sha2-nistp256')
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key)
True
<Arguments>
scheme:
The ECDSA signature scheme. By default, ECDSA NIST P-256 is used, with
SHA256 for hashing.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'scheme' is improperly
formatted or invalid (i.e., not one of the supported ECDSA signature
schemes).
<Side Effects>
None.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
def generate_ecdsa_key(scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Generate public and private ECDSA keys, with NIST P-256 + SHA256 (for
hashing) being the default scheme. In addition, a keyid identifier for the
ECDSA key is generated. The object returned conforms to
'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form:
{'keytype': 'ecdsa-sha2-nistp256',
'scheme', 'ecdsa-sha2-nistp256',
'keyid': keyid,
'keyval': {'public': '',
'private': ''}}
The public and private keys are strings in TODO format.
>>> ecdsa_key = generate_ecdsa_key(scheme='ecdsa-sha2-nistp256')
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key)
True
<Arguments>
scheme:
The ECDSA signature scheme. By default, ECDSA NIST P-256 is used, with
SHA256 for hashing.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'scheme' is improperly
formatted or invalid (i.e., not one of the supported ECDSA signature
schemes).
<Side Effects>
None.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
"""
# Does 'scheme' have the correct format?
# This check will ensure 'scheme' is properly formatted and is a supported
# ECDSA signature scheme. Raise 'securesystemslib.exceptions.FormatError' if
# the check fails.
securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme)
# Begin building the ECDSA key dictionary.
ecdsa_key = {}
keytype = 'ecdsa-sha2-nistp256'
public = None
private = None
# Generate the public and private ECDSA keys with one of the supported
# libraries.
public, private = \
securesystemslib.ecdsa_keys.generate_public_and_private(scheme)
# Generate the keyid of the Ed25519 key. 'key_value' corresponds to the
# 'keyval' entry of the 'Ed25519KEY_SCHEMA' dictionary. The private key
# information is not included in the generation of the 'keyid' identifier.
# Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a
# consistent keyid is generated.
key_value = {'public': public.replace('\r\n', '\n'),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
# Build the 'ed25519_key' dictionary. Update 'key_value' with the Ed25519
# private key prior to adding 'key_value' to 'ed25519_key'.
key_value['private'] = private
ecdsa_key['keytype'] = keytype
ecdsa_key['scheme'] = scheme
ecdsa_key['keyid'] = keyid
ecdsa_key['keyval'] = key_value
# Add "keyid_hash_algorithms" so that equal ECDSA keys with different keyids
# can be associated using supported keyid_hash_algorithms.
ecdsa_key['keyid_hash_algorithms'] = \
securesystemslib.settings.HASH_ALGORITHMS
return ecdsa_key
|
<Purpose>
Generate public and private ED25519 keys, both of length 32-bytes, although
they are hexlified to 64 bytes. In addition, a keyid identifier generated
for the returned ED25519 object. The object returned conforms to
'securesystemslib.formats.ED25519KEY_SCHEMA' and has the form:
{'keytype': 'ed25519',
'scheme': 'ed25519',
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '9ccf3f02b17f82febf5dd3bab878b767d8408...',
'private': 'ab310eae0e229a0eceee3947b6e0205dfab3...'}}
>>> ed25519_key = generate_ed25519_key()
>>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key)
True
>>> len(ed25519_key['keyval']['public'])
64
>>> len(ed25519_key['keyval']['private'])
64
<Arguments>
scheme:
The signature scheme used by the generated Ed25519 key.
<Exceptions>
None.
<Side Effects>
The ED25519 keys are generated by calling either the optimized pure Python
implementation of ed25519, or the ed25519 routines provided by 'pynacl'.
<Returns>
A dictionary containing the ED25519 keys and other identifying information.
Conforms to 'securesystemslib.formats.ED25519KEY_SCHEMA'.
def generate_ed25519_key(scheme='ed25519'):
"""
<Purpose>
Generate public and private ED25519 keys, both of length 32-bytes, although
they are hexlified to 64 bytes. In addition, a keyid identifier generated
for the returned ED25519 object. The object returned conforms to
'securesystemslib.formats.ED25519KEY_SCHEMA' and has the form:
{'keytype': 'ed25519',
'scheme': 'ed25519',
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '9ccf3f02b17f82febf5dd3bab878b767d8408...',
'private': 'ab310eae0e229a0eceee3947b6e0205dfab3...'}}
>>> ed25519_key = generate_ed25519_key()
>>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key)
True
>>> len(ed25519_key['keyval']['public'])
64
>>> len(ed25519_key['keyval']['private'])
64
<Arguments>
scheme:
The signature scheme used by the generated Ed25519 key.
<Exceptions>
None.
<Side Effects>
The ED25519 keys are generated by calling either the optimized pure Python
implementation of ed25519, or the ed25519 routines provided by 'pynacl'.
<Returns>
A dictionary containing the ED25519 keys and other identifying information.
Conforms to 'securesystemslib.formats.ED25519KEY_SCHEMA'.
"""
# Are the arguments properly formatted? If not, raise an
# 'securesystemslib.exceptions.FormatError' exceptions.
securesystemslib.formats.ED25519_SIG_SCHEMA.check_match(scheme)
# Begin building the Ed25519 key dictionary.
ed25519_key = {}
keytype = 'ed25519'
public = None
private = None
# Generate the public and private Ed25519 key with the 'pynacl' library.
# Unlike in the verification of Ed25519 signatures, do not fall back to the
# optimized, pure python implementation provided by PyCA. Ed25519 should
# always be generated with a backend like libsodium to prevent side-channel
# attacks.
public, private = \
securesystemslib.ed25519_keys.generate_public_and_private()
# Generate the keyid of the Ed25519 key. 'key_value' corresponds to the
# 'keyval' entry of the 'Ed25519KEY_SCHEMA' dictionary. The private key
# information is not included in the generation of the 'keyid' identifier.
key_value = {'public': binascii.hexlify(public).decode(),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
# Build the 'ed25519_key' dictionary. Update 'key_value' with the Ed25519
# private key prior to adding 'key_value' to 'ed25519_key'.
key_value['private'] = binascii.hexlify(private).decode()
ed25519_key['keytype'] = keytype
ed25519_key['scheme'] = scheme
ed25519_key['keyid'] = keyid
ed25519_key['keyid_hash_algorithms'] = securesystemslib.settings.HASH_ALGORITHMS
ed25519_key['keyval'] = key_value
return ed25519_key
|
<Purpose>
Return a dictionary conformant to 'securesystemslib.formats.KEY_SCHEMA'.
If 'private' is True, include the private key. The dictionary
returned has the form:
{'keytype': keytype,
'scheme' : scheme,
'keyval': {'public': '...',
'private': '...'}}
or if 'private' is False:
{'keytype': keytype,
'scheme': scheme,
'keyval': {'public': '...',
'private': ''}}
>>> ed25519_key = generate_ed25519_key()
>>> key_val = ed25519_key['keyval']
>>> keytype = ed25519_key['keytype']
>>> scheme = ed25519_key['scheme']
>>> ed25519_metadata = \
format_keyval_to_metadata(keytype, scheme, key_val, private=True)
>>> securesystemslib.formats.KEY_SCHEMA.matches(ed25519_metadata)
True
<Arguments>
key_type:
The 'rsa' or 'ed25519' strings.
scheme:
The signature scheme used by the key.
key_value:
A dictionary containing a private and public keys.
'key_value' is of the form:
{'public': '...',
'private': '...'}},
conformant to 'securesystemslib.formats.KEYVAL_SCHEMA'.
private:
Indicates if the private key should be included in the dictionary
returned.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'key_value' does not conform to
'securesystemslib.formats.KEYVAL_SCHEMA', or if the private key is not
present in 'key_value' if requested by the caller via 'private'.
<Side Effects>
None.
<Returns>
A 'securesystemslib.formats.KEY_SCHEMA' dictionary.
def format_keyval_to_metadata(keytype, scheme, key_value, private=False):
"""
<Purpose>
Return a dictionary conformant to 'securesystemslib.formats.KEY_SCHEMA'.
If 'private' is True, include the private key. The dictionary
returned has the form:
{'keytype': keytype,
'scheme' : scheme,
'keyval': {'public': '...',
'private': '...'}}
or if 'private' is False:
{'keytype': keytype,
'scheme': scheme,
'keyval': {'public': '...',
'private': ''}}
>>> ed25519_key = generate_ed25519_key()
>>> key_val = ed25519_key['keyval']
>>> keytype = ed25519_key['keytype']
>>> scheme = ed25519_key['scheme']
>>> ed25519_metadata = \
format_keyval_to_metadata(keytype, scheme, key_val, private=True)
>>> securesystemslib.formats.KEY_SCHEMA.matches(ed25519_metadata)
True
<Arguments>
key_type:
The 'rsa' or 'ed25519' strings.
scheme:
The signature scheme used by the key.
key_value:
A dictionary containing a private and public keys.
'key_value' is of the form:
{'public': '...',
'private': '...'}},
conformant to 'securesystemslib.formats.KEYVAL_SCHEMA'.
private:
Indicates if the private key should be included in the dictionary
returned.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'key_value' does not conform to
'securesystemslib.formats.KEYVAL_SCHEMA', or if the private key is not
present in 'key_value' if requested by the caller via 'private'.
<Side Effects>
None.
<Returns>
A 'securesystemslib.formats.KEY_SCHEMA' dictionary.
"""
# Does 'keytype' have the correct format?
# This check will ensure 'keytype' has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.KEYTYPE_SCHEMA.check_match(keytype)
# Does 'scheme' have the correct format?
securesystemslib.formats.SCHEME_SCHEMA.check_match(scheme)
# Does 'key_value' have the correct format?
securesystemslib.formats.KEYVAL_SCHEMA.check_match(key_value)
if private is True:
# If the caller requests (via the 'private' argument) to include a private
# key in the returned dictionary, ensure the private key is actually
# present in 'key_val' (a private key is optional for 'KEYVAL_SCHEMA'
# dicts).
if 'private' not in key_value:
raise securesystemslib.exceptions.FormatError('The required private key'
' is missing from: ' + repr(key_value))
else:
return {'keytype': keytype, 'scheme': scheme, 'keyval': key_value}
else:
public_key_value = {'public': key_value['public']}
return {'keytype': keytype,
'scheme': scheme,
'keyid_hash_algorithms': securesystemslib.settings.HASH_ALGORITHMS,
'keyval': public_key_value}
|
<Purpose>
Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA)
according to the keytype of 'key_metadata'. The dict returned by this
function has the exact format as the dict returned by one of the key
generations functions, like generate_ed25519_key(). The dict returned
has the form:
{'keytype': keytype,
'scheme': scheme,
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '...',
'private': '...'}}
For example, RSA key dictionaries in RSAKEY_SCHEMA format should be used by
modules storing a collection of keys, such as with keydb.py. RSA keys as
stored in metadata files use a different format, so this function should be
called if an RSA key is extracted from one of these metadata files and need
converting. The key generation functions create an entirely new key and
return it in the format appropriate for 'keydb.py'.
>>> ed25519_key = generate_ed25519_key()
>>> key_val = ed25519_key['keyval']
>>> keytype = ed25519_key['keytype']
>>> scheme = ed25519_key['scheme']
>>> ed25519_metadata = \
format_keyval_to_metadata(keytype, scheme, key_val, private=True)
>>> ed25519_key_2, junk = format_metadata_to_key(ed25519_metadata)
>>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key_2)
True
>>> ed25519_key == ed25519_key_2
True
<Arguments>
key_metadata:
The key dictionary as stored in Metadata files, conforming to
'securesystemslib.formats.KEY_SCHEMA'. It has the form:
{'keytype': '...',
'scheme': scheme,
'keyval': {'public': '...',
'private': '...'}}
<Exceptions>
securesystemslib.exceptions.FormatError, if 'key_metadata' does not conform
to 'securesystemslib.formats.KEY_SCHEMA'.
<Side Effects>
None.
<Returns>
In the case of an RSA key, a dictionary conformant to
'securesystemslib.formats.RSAKEY_SCHEMA'.
def format_metadata_to_key(key_metadata):
"""
<Purpose>
Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA)
according to the keytype of 'key_metadata'. The dict returned by this
function has the exact format as the dict returned by one of the key
generations functions, like generate_ed25519_key(). The dict returned
has the form:
{'keytype': keytype,
'scheme': scheme,
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '...',
'private': '...'}}
For example, RSA key dictionaries in RSAKEY_SCHEMA format should be used by
modules storing a collection of keys, such as with keydb.py. RSA keys as
stored in metadata files use a different format, so this function should be
called if an RSA key is extracted from one of these metadata files and need
converting. The key generation functions create an entirely new key and
return it in the format appropriate for 'keydb.py'.
>>> ed25519_key = generate_ed25519_key()
>>> key_val = ed25519_key['keyval']
>>> keytype = ed25519_key['keytype']
>>> scheme = ed25519_key['scheme']
>>> ed25519_metadata = \
format_keyval_to_metadata(keytype, scheme, key_val, private=True)
>>> ed25519_key_2, junk = format_metadata_to_key(ed25519_metadata)
>>> securesystemslib.formats.ED25519KEY_SCHEMA.matches(ed25519_key_2)
True
>>> ed25519_key == ed25519_key_2
True
<Arguments>
key_metadata:
The key dictionary as stored in Metadata files, conforming to
'securesystemslib.formats.KEY_SCHEMA'. It has the form:
{'keytype': '...',
'scheme': scheme,
'keyval': {'public': '...',
'private': '...'}}
<Exceptions>
securesystemslib.exceptions.FormatError, if 'key_metadata' does not conform
to 'securesystemslib.formats.KEY_SCHEMA'.
<Side Effects>
None.
<Returns>
In the case of an RSA key, a dictionary conformant to
'securesystemslib.formats.RSAKEY_SCHEMA'.
"""
# Does 'key_metadata' have the correct format?
# This check will ensure 'key_metadata' has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.KEY_SCHEMA.check_match(key_metadata)
# Construct the dictionary to be returned.
key_dict = {}
keytype = key_metadata['keytype']
scheme = key_metadata['scheme']
key_value = key_metadata['keyval']
# Convert 'key_value' to 'securesystemslib.formats.KEY_SCHEMA' and generate
# its hash The hash is in hexdigest form.
default_keyid = _get_keyid(keytype, scheme, key_value)
keyids = set()
keyids.add(default_keyid)
for hash_algorithm in securesystemslib.settings.HASH_ALGORITHMS:
keyid = _get_keyid(keytype, scheme, key_value, hash_algorithm)
keyids.add(keyid)
# All the required key values gathered. Build 'key_dict'.
# 'keyid_hash_algorithms'
key_dict['keytype'] = keytype
key_dict['scheme'] = scheme
key_dict['keyid'] = default_keyid
key_dict['keyid_hash_algorithms'] = securesystemslib.settings.HASH_ALGORITHMS
key_dict['keyval'] = key_value
return key_dict, keyids
|
Return the keyid of 'key_value'.
def _get_keyid(keytype, scheme, key_value, hash_algorithm = 'sha256'):
"""Return the keyid of 'key_value'."""
# 'keyid' will be generated from an object conformant to KEY_SCHEMA,
# which is the format Metadata files (e.g., root.json) store keys.
# 'format_keyval_to_metadata()' returns the object needed by _get_keyid().
key_meta = format_keyval_to_metadata(keytype, scheme, key_value, private=False)
# Convert the key to JSON Canonical format, suitable for adding
# to digest objects.
key_update_data = securesystemslib.formats.encode_canonical(key_meta)
# Create a digest object and call update(), using the JSON
# canonical format of 'rskey_meta' as the update data.
digest_object = securesystemslib.hash.digest(hash_algorithm)
digest_object.update(key_update_data.encode('utf-8'))
# 'keyid' becomes the hexadecimal representation of the hash.
keyid = digest_object.hexdigest()
return keyid
|
<Purpose>
Return a signature dictionary of the form:
{'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'sig': '...'}.
The signing process will use the private key in
key_dict['keyval']['private'] and 'data' to generate the signature.
The following signature schemes are supported:
'RSASSA-PSS'
RFC3447 - RSASSA-PSS
http://www.ietf.org/rfc/rfc3447.
'ed25519'
ed25519 - high-speed high security signatures
http://ed25519.cr.yp.to/
Which signature to generate is determined by the key type of 'key_dict'
and the available cryptography library specified in 'settings'.
>>> ed25519_key = generate_ed25519_key()
>>> data = 'The quick brown fox jumps over the lazy dog'
>>> signature = create_signature(ed25519_key, data)
>>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature)
True
>>> len(signature['sig'])
128
>>> rsa_key = generate_rsa_key(2048)
>>> signature = create_signature(rsa_key, data)
>>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature)
True
>>> ecdsa_key = generate_ecdsa_key()
>>> signature = create_signature(ecdsa_key, data)
>>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature)
True
<Arguments>
key_dict:
A dictionary containing the keys. An example RSA key dict has the
form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The public and private keys are strings in PEM format.
data:
Data to be signed. This should be a bytes object; data should be
encoded/serialized before it is passed here. The same value can be be
passed into securesystemslib.verify_signature() (along with the public
key) to later verify the signature.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'key_dict' is improperly
formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict'
specifies an unsupported key type or signing scheme.
TypeError, if 'key_dict' contains an invalid keytype.
<Side Effects>
The cryptography library specified in 'settings' is called to perform the
actual signing routine.
<Returns>
A signature dictionary conformant to
'securesystemslib_format.SIGNATURE_SCHEMA'.
def create_signature(key_dict, data):
"""
<Purpose>
Return a signature dictionary of the form:
{'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'sig': '...'}.
The signing process will use the private key in
key_dict['keyval']['private'] and 'data' to generate the signature.
The following signature schemes are supported:
'RSASSA-PSS'
RFC3447 - RSASSA-PSS
http://www.ietf.org/rfc/rfc3447.
'ed25519'
ed25519 - high-speed high security signatures
http://ed25519.cr.yp.to/
Which signature to generate is determined by the key type of 'key_dict'
and the available cryptography library specified in 'settings'.
>>> ed25519_key = generate_ed25519_key()
>>> data = 'The quick brown fox jumps over the lazy dog'
>>> signature = create_signature(ed25519_key, data)
>>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature)
True
>>> len(signature['sig'])
128
>>> rsa_key = generate_rsa_key(2048)
>>> signature = create_signature(rsa_key, data)
>>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature)
True
>>> ecdsa_key = generate_ecdsa_key()
>>> signature = create_signature(ecdsa_key, data)
>>> securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature)
True
<Arguments>
key_dict:
A dictionary containing the keys. An example RSA key dict has the
form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The public and private keys are strings in PEM format.
data:
Data to be signed. This should be a bytes object; data should be
encoded/serialized before it is passed here. The same value can be be
passed into securesystemslib.verify_signature() (along with the public
key) to later verify the signature.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'key_dict' is improperly
formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict'
specifies an unsupported key type or signing scheme.
TypeError, if 'key_dict' contains an invalid keytype.
<Side Effects>
The cryptography library specified in 'settings' is called to perform the
actual signing routine.
<Returns>
A signature dictionary conformant to
'securesystemslib_format.SIGNATURE_SCHEMA'.
"""
# Does 'key_dict' have the correct format?
# This check will ensure 'key_dict' has the appropriate number of objects
# and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
# The key type of 'key_dict' must be either 'rsa' or 'ed25519'.
securesystemslib.formats.ANYKEY_SCHEMA.check_match(key_dict)
# Signing the 'data' object requires a private key. 'rsassa-pss-sha256',
# 'ed25519', and 'ecdsa-sha2-nistp256' are the only signing schemes currently
# supported. RSASSA-PSS keys and signatures can be generated and verified by
# pyca_crypto_keys.py, and Ed25519 keys by PyNaCl and PyCA's optimized, pure
# python implementation of Ed25519.
signature = {}
keytype = key_dict['keytype']
scheme = key_dict['scheme']
public = key_dict['keyval']['public']
private = key_dict['keyval']['private']
keyid = key_dict['keyid']
sig = None
if keytype == 'rsa':
if scheme == 'rsassa-pss-sha256':
private = private.replace('\r\n', '\n')
sig, scheme = securesystemslib.pyca_crypto_keys.create_rsa_signature(
private, data, scheme)
else:
raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported'
' RSA signature scheme specified: ' + repr(scheme))
elif keytype == 'ed25519':
public = binascii.unhexlify(public.encode('utf-8'))
private = binascii.unhexlify(private.encode('utf-8'))
sig, scheme = securesystemslib.ed25519_keys.create_signature(
public, private, data, scheme)
elif keytype == 'ecdsa-sha2-nistp256':
sig, scheme = securesystemslib.ecdsa_keys.create_signature(
public, private, data, scheme)
# 'securesystemslib.formats.ANYKEY_SCHEMA' should have detected invalid key
# types. This is a defensive check against an invalid key type.
else: # pragma: no cover
raise TypeError('Invalid key type.')
# Build the signature dictionary to be returned.
# The hexadecimal representation of 'sig' is stored in the signature.
signature['keyid'] = keyid
signature['sig'] = binascii.hexlify(sig).decode()
return signature
|
<Purpose>
Determine whether the private key belonging to 'key_dict' produced
'signature'. verify_signature() will use the public key found in
'key_dict', the 'sig' objects contained in 'signature', and 'data' to
complete the verification.
>>> ed25519_key = generate_ed25519_key()
>>> data = 'The quick brown fox jumps over the lazy dog'
>>> signature = create_signature(ed25519_key, data)
>>> verify_signature(ed25519_key, signature, data)
True
>>> verify_signature(ed25519_key, signature, 'bad_data')
False
>>> rsa_key = generate_rsa_key()
>>> signature = create_signature(rsa_key, data)
>>> verify_signature(rsa_key, signature, data)
True
>>> verify_signature(rsa_key, signature, 'bad_data')
False
>>> ecdsa_key = generate_ecdsa_key()
>>> signature = create_signature(ecdsa_key, data)
>>> verify_signature(ecdsa_key, signature, data)
True
>>> verify_signature(ecdsa_key, signature, 'bad_data')
False
<Arguments>
key_dict:
A dictionary containing the keys and other identifying information.
If 'key_dict' is an RSA key, it has the form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The public and private keys are strings in PEM format.
signature:
The signature dictionary produced by one of the key generation functions.
'signature' has the form:
{'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'sig': sig}.
Conformant to 'securesystemslib.formats.SIGNATURE_SCHEMA'.
data:
Data that the signature is expected to be over. This should be a bytes
object; data should be encoded/serialized before it is passed here.)
This is the same value that can be passed into
securesystemslib.create_signature() in order to create the signature.
<Exceptions>
securesystemslib.exceptions.FormatError, raised if either 'key_dict' or
'signature' are improperly formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict' or
'signature' specifies an unsupported algorithm.
securesystemslib.exceptions.CryptoError, if the KEYID in the given
'key_dict' does not match the KEYID in 'signature'.
<Side Effects>
The cryptography library specified in 'settings' called to do the actual
verification.
<Returns>
Boolean. True if the signature is valid, False otherwise.
def verify_signature(key_dict, signature, data):
"""
<Purpose>
Determine whether the private key belonging to 'key_dict' produced
'signature'. verify_signature() will use the public key found in
'key_dict', the 'sig' objects contained in 'signature', and 'data' to
complete the verification.
>>> ed25519_key = generate_ed25519_key()
>>> data = 'The quick brown fox jumps over the lazy dog'
>>> signature = create_signature(ed25519_key, data)
>>> verify_signature(ed25519_key, signature, data)
True
>>> verify_signature(ed25519_key, signature, 'bad_data')
False
>>> rsa_key = generate_rsa_key()
>>> signature = create_signature(rsa_key, data)
>>> verify_signature(rsa_key, signature, data)
True
>>> verify_signature(rsa_key, signature, 'bad_data')
False
>>> ecdsa_key = generate_ecdsa_key()
>>> signature = create_signature(ecdsa_key, data)
>>> verify_signature(ecdsa_key, signature, data)
True
>>> verify_signature(ecdsa_key, signature, 'bad_data')
False
<Arguments>
key_dict:
A dictionary containing the keys and other identifying information.
If 'key_dict' is an RSA key, it has the form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The public and private keys are strings in PEM format.
signature:
The signature dictionary produced by one of the key generation functions.
'signature' has the form:
{'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'sig': sig}.
Conformant to 'securesystemslib.formats.SIGNATURE_SCHEMA'.
data:
Data that the signature is expected to be over. This should be a bytes
object; data should be encoded/serialized before it is passed here.)
This is the same value that can be passed into
securesystemslib.create_signature() in order to create the signature.
<Exceptions>
securesystemslib.exceptions.FormatError, raised if either 'key_dict' or
'signature' are improperly formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'key_dict' or
'signature' specifies an unsupported algorithm.
securesystemslib.exceptions.CryptoError, if the KEYID in the given
'key_dict' does not match the KEYID in 'signature'.
<Side Effects>
The cryptography library specified in 'settings' called to do the actual
verification.
<Returns>
Boolean. True if the signature is valid, False otherwise.
"""
# Does 'key_dict' have the correct format?
# This check will ensure 'key_dict' has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.ANYKEY_SCHEMA.check_match(key_dict)
# Does 'signature' have the correct format?
securesystemslib.formats.SIGNATURE_SCHEMA.check_match(signature)
# Verify that the KEYID in 'key_dict' matches the KEYID listed in the
# 'signature'.
if key_dict['keyid'] != signature['keyid']:
raise securesystemslib.exceptions.CryptoError('The KEYID ('
' ' + repr(key_dict['keyid']) + ' ) in the given key does not match'
' the KEYID ( ' + repr(signature['keyid']) + ' ) in the signature.')
else:
logger.debug('The KEYIDs of key_dict and the signature match.')
# Using the public key belonging to 'key_dict'
# (i.e., rsakey_dict['keyval']['public']), verify whether 'signature'
# was produced by key_dict's corresponding private key
# key_dict['keyval']['private'].
sig = signature['sig']
sig = binascii.unhexlify(sig.encode('utf-8'))
public = key_dict['keyval']['public']
keytype = key_dict['keytype']
scheme = key_dict['scheme']
valid_signature = False
if keytype == 'rsa':
if scheme == 'rsassa-pss-sha256':
valid_signature = securesystemslib.pyca_crypto_keys.verify_rsa_signature(sig,
scheme, public, data)
else:
raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported'
' signature scheme is specified: ' + repr(scheme))
elif keytype == 'ed25519':
if scheme == 'ed25519':
public = binascii.unhexlify(public.encode('utf-8'))
valid_signature = securesystemslib.ed25519_keys.verify_signature(public,
scheme, sig, data, use_pynacl=USE_PYNACL)
else:
raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported'
' signature scheme is specified: ' + repr(scheme))
elif keytype == 'ecdsa-sha2-nistp256':
if scheme == 'ecdsa-sha2-nistp256':
valid_signature = securesystemslib.ecdsa_keys.verify_signature(public,
scheme, sig, data)
else:
raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported'
' signature scheme is specified: ' + repr(scheme))
# 'securesystemslib.formats.ANYKEY_SCHEMA' should have detected invalid key
# types. This is a defensive check against an invalid key type.
else: # pragma: no cover
raise TypeError('Unsupported key type.')
return valid_signature
|
<Purpose>
Import the private RSA key stored in 'pem', and generate its public key
(which will also be included in the returned rsakey object). In addition,
a keyid identifier for the RSA key is generated. The object returned
conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The private key is a string in PEM format.
>>> rsa_key = generate_rsa_key()
>>> scheme = rsa_key['scheme']
>>> private = rsa_key['keyval']['private']
>>> passphrase = 'secret'
>>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase)
>>> rsa_key2 = import_rsakey_from_private_pem(encrypted_pem, scheme, passphrase)
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key)
True
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2)
True
<Arguments>
pem:
A string in PEM format. The private key is extracted and returned in
an rsakey object.
scheme:
The signature scheme used by the imported key.
password: (optional)
The password, or passphrase, to decrypt the private part of the RSA key
if it is encrypted. 'password' is not used directly as the encryption
key, a stronger encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies
an unsupported key type.
<Side Effects>
None.
<Returns>
A dictionary containing the RSA keys and other identifying information.
Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
def import_rsakey_from_private_pem(pem, scheme='rsassa-pss-sha256', password=None):
"""
<Purpose>
Import the private RSA key stored in 'pem', and generate its public key
(which will also be included in the returned rsakey object). In addition,
a keyid identifier for the RSA key is generated. The object returned
conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form:
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...',
'private': '-----BEGIN RSA PRIVATE KEY----- ...'}}
The private key is a string in PEM format.
>>> rsa_key = generate_rsa_key()
>>> scheme = rsa_key['scheme']
>>> private = rsa_key['keyval']['private']
>>> passphrase = 'secret'
>>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase)
>>> rsa_key2 = import_rsakey_from_private_pem(encrypted_pem, scheme, passphrase)
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key)
True
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2)
True
<Arguments>
pem:
A string in PEM format. The private key is extracted and returned in
an rsakey object.
scheme:
The signature scheme used by the imported key.
password: (optional)
The password, or passphrase, to decrypt the private part of the RSA key
if it is encrypted. 'password' is not used directly as the encryption
key, a stronger encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies
an unsupported key type.
<Side Effects>
None.
<Returns>
A dictionary containing the RSA keys and other identifying information.
Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
"""
# Does 'pem' have the correct format?
# This check will ensure 'pem' conforms to
# 'securesystemslib.formats.PEMRSA_SCHEMA'.
securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem)
# Is 'scheme' properly formatted?
securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme)
if password is not None:
securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
else:
logger.debug('The password/passphrase is unset. The PEM is expected'
' to be unencrypted.')
# Begin building the RSA key dictionary.
rsakey_dict = {}
keytype = 'rsa'
public = None
private = None
# Generate the public and private RSA keys. The pyca/cryptography library
# performs the actual crypto operations.
public, private = \
securesystemslib.pyca_crypto_keys.create_rsa_public_and_private_from_pem(
pem, password)
public = extract_pem(public, private_pem=False)
private = extract_pem(private, private_pem=True)
# Generate the keyid of the RSA key. 'key_value' corresponds to the
# 'keyval' entry of the 'RSAKEY_SCHEMA' dictionary. The private key
# information is not included in the generation of the 'keyid' identifier.
# Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a
# consistent keyid is generated.
key_value = {'public': public.replace('\r\n', '\n'),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
# Build the 'rsakey_dict' dictionary. Update 'key_value' with the RSA
# private key prior to adding 'key_value' to 'rsakey_dict'.
key_value['private'] = private
rsakey_dict['keytype'] = keytype
rsakey_dict['scheme'] = scheme
rsakey_dict['keyid'] = keyid
rsakey_dict['keyval'] = key_value
return rsakey_dict
|
<Purpose>
Generate an RSA key object from 'pem'. In addition, a keyid identifier for
the RSA key is generated. The object returned conforms to
'securesystemslib.formats.RSAKEY_SCHEMA' and has the form:
{'keytype': 'rsa',
'keyid': keyid,
'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...',
'private': ''}}
The public portion of the RSA key is a string in PEM format.
>>> rsa_key = generate_rsa_key()
>>> public = rsa_key['keyval']['public']
>>> rsa_key['keyval']['private'] = ''
>>> rsa_key2 = import_rsakey_from_public_pem(public)
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key)
True
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2)
True
<Arguments>
pem:
A string in PEM format (it should contain a public RSA key).
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
Only the public portion of the PEM is extracted. Leading or trailing
whitespace is not included in the PEM string stored in the rsakey object
returned.
<Returns>
A dictionary containing the RSA keys and other identifying information.
Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
def import_rsakey_from_public_pem(pem, scheme='rsassa-pss-sha256'):
"""
<Purpose>
Generate an RSA key object from 'pem'. In addition, a keyid identifier for
the RSA key is generated. The object returned conforms to
'securesystemslib.formats.RSAKEY_SCHEMA' and has the form:
{'keytype': 'rsa',
'keyid': keyid,
'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...',
'private': ''}}
The public portion of the RSA key is a string in PEM format.
>>> rsa_key = generate_rsa_key()
>>> public = rsa_key['keyval']['public']
>>> rsa_key['keyval']['private'] = ''
>>> rsa_key2 = import_rsakey_from_public_pem(public)
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key)
True
>>> securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key2)
True
<Arguments>
pem:
A string in PEM format (it should contain a public RSA key).
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
Only the public portion of the PEM is extracted. Leading or trailing
whitespace is not included in the PEM string stored in the rsakey object
returned.
<Returns>
A dictionary containing the RSA keys and other identifying information.
Conforms to 'securesystemslib.formats.RSAKEY_SCHEMA'.
"""
# Does 'pem' have the correct format?
# This check will ensure arguments has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem)
# Does 'scheme' have the correct format?
securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme)
# Ensure the PEM string has a public header and footer. Although a simple
# validation of 'pem' is performed here, a fully valid PEM string is needed
# later to successfully verify signatures. Performing stricter validation of
# PEMs are left to the external libraries that use 'pem'.
if is_pem_public(pem):
public_pem = extract_pem(pem, private_pem=False)
else:
raise securesystemslib.exceptions.FormatError('Invalid public'
' pem: ' + repr(pem))
# Begin building the RSA key dictionary.
rsakey_dict = {}
keytype = 'rsa'
# Generate the keyid of the RSA key. 'key_value' corresponds to the
# 'keyval' entry of the 'RSAKEY_SCHEMA' dictionary. The private key
# information is not included in the generation of the 'keyid' identifier.
# Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a
# consistent keyid is generated.
key_value = {'public': public_pem.replace('\r\n', '\n'),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
rsakey_dict['keytype'] = keytype
rsakey_dict['scheme'] = scheme
rsakey_dict['keyid'] = keyid
rsakey_dict['keyval'] = key_value
# Add "keyid_hash_algorithms" so that equal RSA keys with different keyids
# can be associated using supported keyid_hash_algorithms.
rsakey_dict['keyid_hash_algorithms'] = \
securesystemslib.settings.HASH_ALGORITHMS
return rsakey_dict
|
<Purpose>
Extract only the portion of the pem that includes the header and footer,
with any leading and trailing characters removed. The string returned has
the following form:
'-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----'
or
'-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----'
Note: This function assumes "pem" is a valid pem in the following format:
pem header + key material + key footer. Crypto libraries (e.g., pyca's
cryptography) that parse the pem returned by this function are expected to
fully validate the pem.
<Arguments>
pem:
A string in PEM format.
private_pem:
Boolean that indicates whether 'pem' is a private PEM. Private PEMs
are not shown in exception messages.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
Only the public and private portion of the PEM is extracted. Leading or
trailing whitespace is not included in the returned PEM string.
<Returns>
A PEM string (excluding leading and trailing newline characters).
That is: pem header + key material + pem footer.
def extract_pem(pem, private_pem=False):
"""
<Purpose>
Extract only the portion of the pem that includes the header and footer,
with any leading and trailing characters removed. The string returned has
the following form:
'-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----'
or
'-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----'
Note: This function assumes "pem" is a valid pem in the following format:
pem header + key material + key footer. Crypto libraries (e.g., pyca's
cryptography) that parse the pem returned by this function are expected to
fully validate the pem.
<Arguments>
pem:
A string in PEM format.
private_pem:
Boolean that indicates whether 'pem' is a private PEM. Private PEMs
are not shown in exception messages.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
Only the public and private portion of the PEM is extracted. Leading or
trailing whitespace is not included in the returned PEM string.
<Returns>
A PEM string (excluding leading and trailing newline characters).
That is: pem header + key material + pem footer.
"""
if private_pem:
pem_header = '-----BEGIN RSA PRIVATE KEY-----'
pem_footer = '-----END RSA PRIVATE KEY-----'
else:
pem_header = '-----BEGIN PUBLIC KEY-----'
pem_footer = '-----END PUBLIC KEY-----'
header_start = 0
footer_start = 0
# Raise error message if the expected header or footer is not found in 'pem'.
try:
header_start = pem.index(pem_header)
except ValueError:
# Be careful not to print private key material in exception message.
if not private_pem:
raise securesystemslib.exceptions.FormatError('Required PEM'
' header ' + repr(pem_header) + '\n not found in PEM'
' string: ' + repr(pem))
else:
raise securesystemslib.exceptions.FormatError('Required PEM'
' header ' + repr(pem_header) + '\n not found in private PEM string.')
try:
# Search for 'pem_footer' after the PEM header.
footer_start = pem.index(pem_footer, header_start + len(pem_header))
except ValueError:
# Be careful not to print private key material in exception message.
if not private_pem:
raise securesystemslib.exceptions.FormatError('Required PEM'
' footer ' + repr(pem_footer) + '\n not found in PEM'
' string ' + repr(pem))
else:
raise securesystemslib.exceptions.FormatError('Required PEM'
' footer ' + repr(pem_footer) + '\n not found in private PEM string.')
# Extract only the public portion of 'pem'. Leading or trailing whitespace
# is excluded.
pem = pem[header_start:footer_start + len(pem_footer)]
return pem
|
<Purpose>
Return a string containing 'key_object' in encrypted form. Encrypted
strings may be safely saved to a file. The corresponding decrypt_key()
function can be applied to the encrypted string to restore the original key
object. 'key_object' is a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA).
This function relies on the pyca_crypto_keys.py module to perform the
actual encryption.
Encrypted keys use AES-256-CTR-Mode, and passwords are strengthened with
PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in
'securesystemslib.settings.PBKDF2_ITERATIONS' by the user).
http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29
https://en.wikipedia.org/wiki/PBKDF2
>>> ed25519_key = generate_ed25519_key()
>>> password = 'secret'
>>> encrypted_key = encrypt_key(ed25519_key, password).encode('utf-8')
>>> securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.matches(encrypted_key)
True
<Arguments>
key_object:
A key (containing also the private key portion) of the form
'securesystemslib.formats.ANYKEY_SCHEMA'
password:
The password, or passphrase, to encrypt the private part of the RSA
key. 'password' is not used directly as the encryption key, a stronger
encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if 'key_object' cannot be
encrypted.
<Side Effects>
None.
<Returns>
An encrypted string of the form:
'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'.
def encrypt_key(key_object, password):
"""
<Purpose>
Return a string containing 'key_object' in encrypted form. Encrypted
strings may be safely saved to a file. The corresponding decrypt_key()
function can be applied to the encrypted string to restore the original key
object. 'key_object' is a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA).
This function relies on the pyca_crypto_keys.py module to perform the
actual encryption.
Encrypted keys use AES-256-CTR-Mode, and passwords are strengthened with
PBKDF2-HMAC-SHA256 (100K iterations by default, but may be overriden in
'securesystemslib.settings.PBKDF2_ITERATIONS' by the user).
http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29
https://en.wikipedia.org/wiki/PBKDF2
>>> ed25519_key = generate_ed25519_key()
>>> password = 'secret'
>>> encrypted_key = encrypt_key(ed25519_key, password).encode('utf-8')
>>> securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.matches(encrypted_key)
True
<Arguments>
key_object:
A key (containing also the private key portion) of the form
'securesystemslib.formats.ANYKEY_SCHEMA'
password:
The password, or passphrase, to encrypt the private part of the RSA
key. 'password' is not used directly as the encryption key, a stronger
encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if 'key_object' cannot be
encrypted.
<Side Effects>
None.
<Returns>
An encrypted string of the form:
'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'.
"""
# Does 'key_object' have the correct format?
# This check will ensure 'key_object' has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.ANYKEY_SCHEMA.check_match(key_object)
# Does 'password' have the correct format?
securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
# Encrypted string of 'key_object'. The encrypted string may be safely saved
# to a file and stored offline.
encrypted_key = None
# Generate an encrypted string of 'key_object' using AES-256-CTR-Mode, where
# 'password' is strengthened with PBKDF2-HMAC-SHA256.
encrypted_key = securesystemslib.pyca_crypto_keys.encrypt_key(key_object, password)
return encrypted_key
|
<Purpose>
Return a string containing 'encrypted_key' in non-encrypted form. The
decrypt_key() function can be applied to the encrypted string to restore
the original key object, a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA).
This function calls pyca_crypto_keys.py to perform the actual decryption.
Encrypted keys use AES-256-CTR-Mode and passwords are strengthened with
PBKDF2-HMAC-SHA256 (100K iterations be default, but may be overriden in
'settings.py' by the user).
http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29
https://en.wikipedia.org/wiki/PBKDF2
>>> ed25519_key = generate_ed25519_key()
>>> password = 'secret'
>>> encrypted_key = encrypt_key(ed25519_key, password)
>>> decrypted_key = decrypt_key(encrypted_key.encode('utf-8'), password)
>>> securesystemslib.formats.ANYKEY_SCHEMA.matches(decrypted_key)
True
>>> decrypted_key == ed25519_key
True
<Arguments>
encrypted_key:
An encrypted key (additional data is also included, such as salt, number
of password iterations used for the derived encryption key, etc) of the
form 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'. 'encrypted_key'
should have been generated with encrypt_key().
password:
The password, or passphrase, to decrypt 'encrypted_key'. 'password' is
not used directly as the encryption key, a stronger encryption key is
derived from it. The supported general-purpose module takes care of
re-deriving the encryption key.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if 'encrypted_key' cannot be
decrypted.
<Side Effects>
None.
<Returns>
A key object of the form: 'securesystemslib.formats.ANYKEY_SCHEMA' (e.g.,
RSAKEY_SCHEMA, ED25519KEY_SCHEMA).
def decrypt_key(encrypted_key, passphrase):
"""
<Purpose>
Return a string containing 'encrypted_key' in non-encrypted form. The
decrypt_key() function can be applied to the encrypted string to restore
the original key object, a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA).
This function calls pyca_crypto_keys.py to perform the actual decryption.
Encrypted keys use AES-256-CTR-Mode and passwords are strengthened with
PBKDF2-HMAC-SHA256 (100K iterations be default, but may be overriden in
'settings.py' by the user).
http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29
https://en.wikipedia.org/wiki/PBKDF2
>>> ed25519_key = generate_ed25519_key()
>>> password = 'secret'
>>> encrypted_key = encrypt_key(ed25519_key, password)
>>> decrypted_key = decrypt_key(encrypted_key.encode('utf-8'), password)
>>> securesystemslib.formats.ANYKEY_SCHEMA.matches(decrypted_key)
True
>>> decrypted_key == ed25519_key
True
<Arguments>
encrypted_key:
An encrypted key (additional data is also included, such as salt, number
of password iterations used for the derived encryption key, etc) of the
form 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA'. 'encrypted_key'
should have been generated with encrypt_key().
password:
The password, or passphrase, to decrypt 'encrypted_key'. 'password' is
not used directly as the encryption key, a stronger encryption key is
derived from it. The supported general-purpose module takes care of
re-deriving the encryption key.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if 'encrypted_key' cannot be
decrypted.
<Side Effects>
None.
<Returns>
A key object of the form: 'securesystemslib.formats.ANYKEY_SCHEMA' (e.g.,
RSAKEY_SCHEMA, ED25519KEY_SCHEMA).
"""
# Does 'encrypted_key' have the correct format?
# This check ensures 'encrypted_key' has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.ENCRYPTEDKEY_SCHEMA.check_match(encrypted_key)
# Does 'passphrase' have the correct format?
securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase)
# Store and return the decrypted key object.
key_object = None
# Decrypt 'encrypted_key' so that the original key object is restored.
# encrypt_key() generates an encrypted string of the key object using
# AES-256-CTR-Mode, where 'password' is strengthened with PBKDF2-HMAC-SHA256.
key_object = \
securesystemslib.pyca_crypto_keys.decrypt_key(encrypted_key, passphrase)
# The corresponding encrypt_key() encrypts and stores key objects in
# non-metadata format (i.e., original format of key object argument to
# encrypt_key()) prior to returning.
return key_object
|
<Purpose>
Return a string in PEM format (TraditionalOpenSSL), where the private part
of the RSA key is encrypted using the best available encryption for a given
key's backend. This is a curated (by cryptography.io) encryption choice and
the algorithm may change over time.
c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/
#cryptography.hazmat.primitives.serialization.BestAvailableEncryption
>>> rsa_key = generate_rsa_key()
>>> private = rsa_key['keyval']['private']
>>> passphrase = 'secret'
>>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase)
>>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem)
True
<Arguments>
private_key:
The private key string in PEM format.
passphrase:
The passphrase, or password, to encrypt the private part of the RSA key.
'passphrase' is not used directly as the encryption key, a stronger
encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if an RSA key in encrypted PEM
format cannot be created.
TypeError, 'private_key' is unset.
<Side Effects>
None.
<Returns>
A string in PEM format, where the private RSA key is encrypted.
Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'.
def create_rsa_encrypted_pem(private_key, passphrase):
"""
<Purpose>
Return a string in PEM format (TraditionalOpenSSL), where the private part
of the RSA key is encrypted using the best available encryption for a given
key's backend. This is a curated (by cryptography.io) encryption choice and
the algorithm may change over time.
c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/
#cryptography.hazmat.primitives.serialization.BestAvailableEncryption
>>> rsa_key = generate_rsa_key()
>>> private = rsa_key['keyval']['private']
>>> passphrase = 'secret'
>>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase)
>>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem)
True
<Arguments>
private_key:
The private key string in PEM format.
passphrase:
The passphrase, or password, to encrypt the private part of the RSA key.
'passphrase' is not used directly as the encryption key, a stronger
encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if an RSA key in encrypted PEM
format cannot be created.
TypeError, 'private_key' is unset.
<Side Effects>
None.
<Returns>
A string in PEM format, where the private RSA key is encrypted.
Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'.
"""
# Does 'private_key' have the correct format?
# This check will ensure 'private_key' has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key)
# Does 'passphrase' have the correct format?
securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase)
encrypted_pem = None
# Generate the public and private RSA keys. A 2048-bit minimum is enforced by
# create_rsa_encrypted_pem() via a
# securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match().
encrypted_pem = securesystemslib.pyca_crypto_keys.create_rsa_encrypted_pem(
private_key, passphrase)
return encrypted_pem
|
<Purpose>
Checks if a passed PEM formatted string is a PUBLIC key, by looking for the
following pattern:
'-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----'
>>> rsa_key = generate_rsa_key()
>>> public = rsa_key['keyval']['public']
>>> private = rsa_key['keyval']['private']
>>> is_pem_public(public)
True
>>> is_pem_public(private)
False
<Arguments>
pem:
A string in PEM format.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
None
<Returns>
True if 'pem' is public and false otherwise.
def is_pem_public(pem):
"""
<Purpose>
Checks if a passed PEM formatted string is a PUBLIC key, by looking for the
following pattern:
'-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----'
>>> rsa_key = generate_rsa_key()
>>> public = rsa_key['keyval']['public']
>>> private = rsa_key['keyval']['private']
>>> is_pem_public(public)
True
>>> is_pem_public(private)
False
<Arguments>
pem:
A string in PEM format.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
None
<Returns>
True if 'pem' is public and false otherwise.
"""
# Do the arguments have the correct format?
# This check will ensure arguments have the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem)
pem_header = '-----BEGIN PUBLIC KEY-----'
pem_footer = '-----END PUBLIC KEY-----'
try:
header_start = pem.index(pem_header)
pem.index(pem_footer, header_start + len(pem_header))
except ValueError:
return False
return True
|
<Purpose>
Checks if a passed PEM formatted string is a PRIVATE key, by looking for
the following patterns:
'-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----'
'-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'
>>> rsa_key = generate_rsa_key()
>>> private = rsa_key['keyval']['private']
>>> public = rsa_key['keyval']['public']
>>> is_pem_private(private)
True
>>> is_pem_private(public)
False
<Arguments>
pem:
A string in PEM format.
<Exceptions>
securesystemslib.exceptions.FormatError, if any of the arguments are
improperly formatted.
<Side Effects>
None
<Returns>
True if 'pem' is private and false otherwise.
def is_pem_private(pem, keytype='rsa'):
"""
<Purpose>
Checks if a passed PEM formatted string is a PRIVATE key, by looking for
the following patterns:
'-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----'
'-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'
>>> rsa_key = generate_rsa_key()
>>> private = rsa_key['keyval']['private']
>>> public = rsa_key['keyval']['public']
>>> is_pem_private(private)
True
>>> is_pem_private(public)
False
<Arguments>
pem:
A string in PEM format.
<Exceptions>
securesystemslib.exceptions.FormatError, if any of the arguments are
improperly formatted.
<Side Effects>
None
<Returns>
True if 'pem' is private and false otherwise.
"""
# Do the arguments have the correct format?
# This check will ensure arguments have the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem)
securesystemslib.formats.NAME_SCHEMA.check_match(keytype)
if keytype == 'rsa':
pem_header = '-----BEGIN RSA PRIVATE KEY-----'
pem_footer = '-----END RSA PRIVATE KEY-----'
elif keytype == 'ec':
pem_header = '-----BEGIN EC PRIVATE KEY-----'
pem_footer = '-----END EC PRIVATE KEY-----'
else:
raise securesystemslib.exceptions.FormatError('Unsupported key'
' type: ' + repr(keytype) + '. Supported keytypes: ["rsa", "ec"]')
try:
header_start = pem.index(pem_header)
pem.index(pem_footer, header_start + len(pem_header))
except ValueError:
return False
return True
|
<Purpose>
Import the private ECDSA key stored in 'pem', and generate its public key
(which will also be included in the returned ECDSA key object). In addition,
a keyid identifier for the ECDSA key is generated. The object returned
conforms to:
{'keytype': 'ecdsa-sha2-nistp256',
'scheme': 'ecdsa-sha2-nistp256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----',
'private': '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'}}
The private key is a string in PEM format.
>>> ecdsa_key = generate_ecdsa_key()
>>> private_pem = ecdsa_key['keyval']['private']
>>> ecdsa_key = import_ecdsakey_from_private_pem(private_pem)
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key)
True
<Arguments>
pem:
A string in PEM format. The private key is extracted and returned in
an ecdsakey object.
scheme:
The signature scheme used by the imported key.
password: (optional)
The password, or passphrase, to decrypt the private part of the ECDSA
key if it is encrypted. 'password' is not used directly as the encryption
key, a stronger encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies
an unsupported key type.
<Side Effects>
None.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
def import_ecdsakey_from_private_pem(pem, scheme='ecdsa-sha2-nistp256', password=None):
"""
<Purpose>
Import the private ECDSA key stored in 'pem', and generate its public key
(which will also be included in the returned ECDSA key object). In addition,
a keyid identifier for the ECDSA key is generated. The object returned
conforms to:
{'keytype': 'ecdsa-sha2-nistp256',
'scheme': 'ecdsa-sha2-nistp256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----',
'private': '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'}}
The private key is a string in PEM format.
>>> ecdsa_key = generate_ecdsa_key()
>>> private_pem = ecdsa_key['keyval']['private']
>>> ecdsa_key = import_ecdsakey_from_private_pem(private_pem)
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key)
True
<Arguments>
pem:
A string in PEM format. The private key is extracted and returned in
an ecdsakey object.
scheme:
The signature scheme used by the imported key.
password: (optional)
The password, or passphrase, to decrypt the private part of the ECDSA
key if it is encrypted. 'password' is not used directly as the encryption
key, a stronger encryption key is derived from it.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.UnsupportedAlgorithmError, if 'pem' specifies
an unsupported key type.
<Side Effects>
None.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
"""
# Does 'pem' have the correct format?
# This check will ensure 'pem' conforms to
# 'securesystemslib.formats.ECDSARSA_SCHEMA'.
securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem)
# Is 'scheme' properly formatted?
securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme)
if password is not None:
securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
else:
logger.debug('The password/passphrase is unset. The PEM is expected'
' to be unencrypted.')
# Begin building the ECDSA key dictionary.
ecdsakey_dict = {}
keytype = 'ecdsa-sha2-nistp256'
public = None
private = None
public, private = \
securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem(pem,
password)
# Generate the keyid of the ECDSA key. 'key_value' corresponds to the
# 'keyval' entry of the 'ECDSAKEY_SCHEMA' dictionary. The private key
# information is not included in the generation of the 'keyid' identifier.
# Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a
# consistent keyid is generated.
key_value = {'public': public.replace('\r\n', '\n'),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
# Build the 'ecdsakey_dict' dictionary. Update 'key_value' with the ECDSA
# private key prior to adding 'key_value' to 'ecdsakey_dict'.
key_value['private'] = private
ecdsakey_dict['keytype'] = keytype
ecdsakey_dict['scheme'] = scheme
ecdsakey_dict['keyid'] = keyid
ecdsakey_dict['keyval'] = key_value
# Add "keyid_hash_algorithms" so equal ECDSA keys with
# different keyids can be associated using supported keyid_hash_algorithms
ecdsakey_dict['keyid_hash_algorithms'] = \
securesystemslib.settings.HASH_ALGORITHMS
return ecdsakey_dict
|
<Purpose>
Generate an ECDSA key object from 'pem'. In addition, a keyid identifier
for the ECDSA key is generated. The object returned conforms to
'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form:
{'keytype': 'ecdsa-sha2-nistp256',
'scheme': 'ecdsa-sha2-nistp256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...',
'private': ''}}
The public portion of the ECDSA key is a string in PEM format.
>>> ecdsa_key = generate_ecdsa_key()
>>> public = ecdsa_key['keyval']['public']
>>> ecdsa_key['keyval']['private'] = ''
>>> scheme = ecdsa_key['scheme']
>>> ecdsa_key2 = import_ecdsakey_from_public_pem(public, scheme)
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key)
True
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key2)
True
<Arguments>
pem:
A string in PEM format (it should contain a public ECDSA key).
scheme:
The signature scheme used by the imported key.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
Only the public portion of the PEM is extracted. Leading or trailing
whitespace is not included in the PEM string stored in the rsakey object
returned.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
def import_ecdsakey_from_public_pem(pem, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Generate an ECDSA key object from 'pem'. In addition, a keyid identifier
for the ECDSA key is generated. The object returned conforms to
'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form:
{'keytype': 'ecdsa-sha2-nistp256',
'scheme': 'ecdsa-sha2-nistp256',
'keyid': keyid,
'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...',
'private': ''}}
The public portion of the ECDSA key is a string in PEM format.
>>> ecdsa_key = generate_ecdsa_key()
>>> public = ecdsa_key['keyval']['public']
>>> ecdsa_key['keyval']['private'] = ''
>>> scheme = ecdsa_key['scheme']
>>> ecdsa_key2 = import_ecdsakey_from_public_pem(public, scheme)
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key)
True
>>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key2)
True
<Arguments>
pem:
A string in PEM format (it should contain a public ECDSA key).
scheme:
The signature scheme used by the imported key.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
Only the public portion of the PEM is extracted. Leading or trailing
whitespace is not included in the PEM string stored in the rsakey object
returned.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
"""
# Does 'pem' have the correct format?
# This check will ensure arguments has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem)
# Is 'scheme' properly formatted?
securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme)
# Ensure the PEM string has a public header and footer. Although a simple
# validation of 'pem' is performed here, a fully valid PEM string is needed
# later to successfully verify signatures. Performing stricter validation of
# PEMs are left to the external libraries that use 'pem'.
if is_pem_public(pem):
public_pem = extract_pem(pem, private_pem=False)
else:
raise securesystemslib.exceptions.FormatError('Invalid public'
' pem: ' + repr(pem))
# Begin building the ECDSA key dictionary.
ecdsakey_dict = {}
keytype = 'ecdsa-sha2-nistp256'
# Generate the keyid of the ECDSA key. 'key_value' corresponds to the
# 'keyval' entry of the 'ECDSAKEY_SCHEMA' dictionary. The private key
# information is not included in the generation of the 'keyid' identifier.
# Convert any '\r\n' (e.g., Windows) newline characters to '\n' so that a
# consistent keyid is generated.
key_value = {'public': public_pem.replace('\r\n', '\n'),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
ecdsakey_dict['keytype'] = keytype
ecdsakey_dict['scheme'] = scheme
ecdsakey_dict['keyid'] = keyid
ecdsakey_dict['keyval'] = key_value
# Add "keyid_hash_algorithms" so that equal ECDSA keys with different keyids
# can be associated using supported keyid_hash_algorithms.
ecdsakey_dict['keyid_hash_algorithms'] = \
securesystemslib.settings.HASH_ALGORITHMS
return ecdsakey_dict
|
<Purpose>
Import either a public or private ECDSA PEM. In contrast to the other
explicit import functions (import_ecdsakey_from_public_pem and
import_ecdsakey_from_private_pem), this function is useful for when it is
not known whether 'pem' is private or public.
<Arguments>
pem:
A string in PEM format.
scheme:
The signature scheme used by the imported key.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
None.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
def import_ecdsakey_from_pem(pem, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Import either a public or private ECDSA PEM. In contrast to the other
explicit import functions (import_ecdsakey_from_public_pem and
import_ecdsakey_from_private_pem), this function is useful for when it is
not known whether 'pem' is private or public.
<Arguments>
pem:
A string in PEM format.
scheme:
The signature scheme used by the imported key.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.
<Side Effects>
None.
<Returns>
A dictionary containing the ECDSA keys and other identifying information.
Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
"""
# Does 'pem' have the correct format?
# This check will ensure arguments has the appropriate number
# of objects and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem)
# Is 'scheme' properly formatted?
securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme)
public_pem = ''
private_pem = ''
# Ensure the PEM string has a public or private header and footer. Although
# a simple validation of 'pem' is performed here, a fully valid PEM string is
# needed later to successfully verify signatures. Performing stricter
# validation of PEMs are left to the external libraries that use 'pem'.
if is_pem_public(pem):
public_pem = extract_pem(pem, private_pem=False)
elif is_pem_private(pem, 'ec'):
# Return an ecdsakey object (ECDSAKEY_SCHEMA) with the private key included.
return import_ecdsakey_from_private_pem(pem, password=None)
else:
raise securesystemslib.exceptions.FormatError('PEM contains neither a public'
' nor private key: ' + repr(pem))
# Begin building the ECDSA key dictionary.
ecdsakey_dict = {}
keytype = 'ecdsa-sha2-nistp256'
# Generate the keyid of the ECDSA key. 'key_value' corresponds to the
# 'keyval' entry of the 'ECDSAKEY_SCHEMA' dictionary. The private key
# information is not included in the generation of the 'keyid' identifier.
# If a PEM is found to contain a private key, the generated rsakey object
# should be returned above. The following key object is for the case of a
# PEM with only a public key. Convert any '\r\n' (e.g., Windows) newline
# characters to '\n' so that a consistent keyid is generated.
key_value = {'public': public_pem.replace('\r\n', '\n'),
'private': ''}
keyid = _get_keyid(keytype, scheme, key_value)
ecdsakey_dict['keytype'] = keytype
ecdsakey_dict['scheme'] = scheme
ecdsakey_dict['keyid'] = keyid
ecdsakey_dict['keyval'] = key_value
return ecdsakey_dict
|
If success, return a tuple (args, body)
def parse_func_body(self):
"""If success, return a tuple (args, body)"""
self.save()
self._expected = []
if self.next_is_rc(Tokens.OPAR, False): # do not render right hidden
self.handle_hidden_right() # render hidden after new level
args = self.parse_param_list()
if args is not None: # may be an empty table
if self.next_is_rc(Tokens.CPAR, False): # do not render right hidden
self.handle_hidden_right() # render hidden after new level
body = self.parse_block()
if body:
self._expected = []
token = self.next_is_rc(Tokens.END, False)
if token:
body.stop_char = token.stop
self.success()
return args, body
else:
self.abort()
else:
self.abort()
return self.failure()
|
This method provides easier access to all writers inheriting Writer class
:param class_name: name of the parser (name of the parser class which should be used)
:type class_name: str
:return: Writer subclass specified by parser_name
:rtype: Writer subclass
:raise ValueError:
def get_concrete_class(cls, class_name):
"""This method provides easier access to all writers inheriting Writer class
:param class_name: name of the parser (name of the parser class which should be used)
:type class_name: str
:return: Writer subclass specified by parser_name
:rtype: Writer subclass
:raise ValueError:
"""
def recurrent_class_lookup(cls):
for cls in cls.__subclasses__():
if lower(cls.__name__) == lower(class_name):
return cls
elif len(cls.__subclasses__()) > 0:
r = recurrent_class_lookup(cls)
if r is not None:
return r
return None
cls = recurrent_class_lookup(cls)
if cls:
return cls
else:
raise ValueError("'class_name '%s' is invalid" % class_name)
|
Retrieve pupil data
def GetPupil(self):
"""Retrieve pupil data
"""
pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType',
'ApertureValue',
'entrancePupilDiameter',
'entrancePupilPosition',
'exitPupilDiameter',
'exitPupilPosition',
'ApodizationType',
'ApodizationFactor'])
data = self._ilensdataeditor.GetPupil()
return pupil_data(*data)
|
Attempt to ping a list of hosts or networks (can be a single host)
:param targets: List - Name(s) or IP(s) of the host(s).
:param filename: String - name of the file containing hosts to ping
:param status: String - if one of ['alive', 'dead', 'noip'] then only
return results that have that status. If this is not specified,
then all results will be returned.
:return: Type and results depends on whether status is specified:
if status == '': return dict: {targets: results}
if status != '': return list: targets if targets == status
def ping(self, targets=list(), filename=str(), status=str()):
"""
Attempt to ping a list of hosts or networks (can be a single host)
:param targets: List - Name(s) or IP(s) of the host(s).
:param filename: String - name of the file containing hosts to ping
:param status: String - if one of ['alive', 'dead', 'noip'] then only
return results that have that status. If this is not specified,
then all results will be returned.
:return: Type and results depends on whether status is specified:
if status == '': return dict: {targets: results}
if status != '': return list: targets if targets == status
"""
if targets and filename:
raise SyntaxError("You must specify only one of either targets=[] "
"or filename=''.")
elif not targets and not filename:
raise SyntaxError("You must specify either a list of targets or "
"filename='', but not both.")
elif filename:
targets = self.read_file(filename)
my_targets = {'hosts': [], 'nets': []}
addresses = []
# Check for valid networks and add hosts and nets to my_targets
for target in targets:
# Targets may include networks in the format "network mask", or,
# a file could contain multiple hosts or IP's on a single line.
if len(target.split()) > 1:
target_items = target.split()
for item in target_items:
try:
ip = IPAddress(item)
# If it is an IPv4 address or mask put in in addresses
if ip.version == 4:
addresses.append(str(ip))
except AddrFormatError:
# IP Address not detected, so assume it's a host name
my_targets['hosts'].append(item)
except ValueError:
# CIDR network detected
net = IPNetwork(item)
# Make sure it is a CIDR address acceptable to fping
if net.ip.is_unicast() and net.version == 4 and \
net.netmask.netmask_bits() in range(8, 31):
my_targets['nets'].append(target_items[0])
else:
msg = str(str(net) + ':Only IPv4 unicast addresses'
' with bit masks\n '
' from 8 to 30 are supported.')
raise AttributeError(msg)
# Iterate over the IP strings in addresses
while len(addresses) > 1:
ip = IPAddress(addresses[0])
mask = IPAddress(addresses[1])
# Test to see if IP is unicast, and mask is an actual mask
if ip.is_unicast() and mask.is_netmask():
net = IPNetwork(str(ip) + '/' + str(
mask.netmask_bits()))
# Convert ip and mask to CIDR and remove from addresses
my_targets['nets'].append(str(net.cidr))
addresses.pop(0)
addresses.pop(0)
elif ip.is_unicast() and not ip.is_netmask():
# mask was not a mask so only remove IP and start over
my_targets['hosts'].append(str(ip))
addresses.pop(0)
# There could be one more item in addresses, so check it
if addresses:
ip = IPAddress(addresses[0])
if ip.is_unicast() and not ip.is_netmask():
my_targets['hosts'].append(addresses[0])
addresses.pop()
# target has only one item, so check it
else:
try:
ip = IPAddress(target)
if ip.version == 4 and ip.is_unicast() and \
not ip.is_netmask():
my_targets['hosts'].append(target)
else:
msg = str(target + 'Only IPv4 unicast addresses are '
'supported.')
raise AttributeError(msg)
except AddrFormatError:
# IP Address not detected, so assume it's a host name
my_targets['hosts'].append(target)
except ValueError:
# CIDR network detected
net = IPNetwork(target)
if net.ip.is_unicast() and net.version == 4 and \
net.netmask.netmask_bits() in range(8, 31):
my_targets['nets'].append(target)
else:
msg = str(str(net) + ':Only IPv4 unicast addresses'
' with bit masks\n '
' from 8 to 30 are supported.')
raise AttributeError(msg)
"""
Build the list of commands to run.
"""
commands = []
if len(my_targets['hosts']) != 0:
for target in range(len(my_targets['hosts'])):
commands.append([self.fping, '-nV', my_targets['hosts'][
target]])
if len(my_targets['nets']) != 0:
for target in range(len(my_targets['nets'])):
commands.append([self.fping, '-ngV', my_targets['nets'][
target]])
"""
Start pinging each item in my_targets and return the requested results
when done.
"""
pool = ThreadPool(self.num_pools)
raw_results = pool.map(self.get_results, commands)
pool.close()
pool.join()
self.results = {host: result for host, result in csv.reader(
''.join(raw_results).splitlines())}
if not status:
return self.results
elif status == 'alive':
return self.alive
elif status == 'dead':
return self.dead
elif status == 'noip':
return self.noip
else:
raise SyntaxError("Valid status options are 'alive', 'dead' or "
"'noip'")
|
def get_results(cmd: list) -> str:
return lines
Get the ping results using fping.
:param cmd: List - the fping command and its options
:return: String - raw string output containing csv fping results
including the newline characters
def get_results(cmd):
"""
def get_results(cmd: list) -> str:
return lines
Get the ping results using fping.
:param cmd: List - the fping command and its options
:return: String - raw string output containing csv fping results
including the newline characters
"""
try:
return subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
return e.output
|
Reads the lines of a file into a list, and returns the list
:param filename: String - path and name of the file
:return: List - lines within the file
def read_file(filename):
"""
Reads the lines of a file into a list, and returns the list
:param filename: String - path and name of the file
:return: List - lines within the file
"""
lines = []
with open(filename) as f:
for line in f:
if len(line.strip()) != 0:
lines.append(line.strip())
return lines
|
Open a ROOT file with option 'RECREATE' to create a new file (the file will
be overwritten if it already exists), and using the ZLIB compression algorithm
(with compression level 1) for better compatibility with older ROOT versions
(see https://root.cern.ch/doc/v614/release-notes.html#important-notice ).
:param data_out:
:param outputs:
:return:
def _prepare_outputs(self, data_out, outputs):
""" Open a ROOT file with option 'RECREATE' to create a new file (the file will
be overwritten if it already exists), and using the ZLIB compression algorithm
(with compression level 1) for better compatibility with older ROOT versions
(see https://root.cern.ch/doc/v614/release-notes.html#important-notice ).
:param data_out:
:param outputs:
:return:
"""
compress = ROOTModule.ROOT.CompressionSettings(ROOTModule.ROOT.kZLIB, 1)
if isinstance(data_out, (str, unicode)):
self.file_emulation = True
outputs.append(ROOTModule.TFile.Open(data_out, 'RECREATE', '', compress))
# multiple tables - require directory
elif isinstance(data_out, ROOTModule.TFile):
outputs.append(data_out)
else: # assume it's a file like object
self.file_emulation = True
filename = os.path.join(tempfile.mkdtemp(),'tmp.root')
outputs.append(ROOTModule.TFile.Open(filename, 'RECREATE', '', compress))
|
:param data_in:
:type data_in: hepconverter.parsers.ParsedData
:param data_out: filelike object
:type data_out: file
:param args:
:param kwargs:
def write(self, data_in, data_out, *args, **kwargs):
"""
:param data_in:
:type data_in: hepconverter.parsers.ParsedData
:param data_out: filelike object
:type data_out: file
:param args:
:param kwargs:
"""
self._get_tables(data_in)
self.file_emulation = False
outputs = []
self._prepare_outputs(data_out, outputs)
output = outputs[0]
for i in xrange(len(self.tables)):
table = self.tables[i]
self._write_table(output, table)
if data_out != output and hasattr(data_out, 'write'):
output.Flush()
output.ReOpen('read')
file_size = output.GetSize()
buff = bytearray(file_size)
output.ReadBuffer(buff, file_size)
data_out.write(buff)
if self.file_emulation:
filename = output.GetName()
output.Close()
|
itertools recipe
"s -> (s0,s1), (s1,s2), (s2, s3), ...
def _pairwise(iterable):
"""
itertools recipe
"s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
|
Return an iterator of tuples for slicing, in 'length' chunks.
Parameters
----------
length : int
Length of each chunk.
total_length : int
Length of the object we are slicing
Returns
-------
iterable of tuples
Values defining a slice range resulting in length 'length'.
def _groups_of(length, total_length):
"""
Return an iterator of tuples for slicing, in 'length' chunks.
Parameters
----------
length : int
Length of each chunk.
total_length : int
Length of the object we are slicing
Returns
-------
iterable of tuples
Values defining a slice range resulting in length 'length'.
"""
indices = tuple(range(0, total_length, length)) + (None, )
return _pairwise(indices)
|
Save the numeric results of each source into its corresponding target.
Parameters
----------
sources: list
The list of source arrays for saving from; limited to length 1.
targets: list
The list of target arrays for saving to; limited to length 1.
masked: boolean
Uses a masked array from sources if True.
def save(sources, targets, masked=False):
"""
Save the numeric results of each source into its corresponding target.
Parameters
----------
sources: list
The list of source arrays for saving from; limited to length 1.
targets: list
The list of target arrays for saving to; limited to length 1.
masked: boolean
Uses a masked array from sources if True.
"""
# TODO: Remove restriction
assert len(sources) == 1 and len(targets) == 1
array = sources[0]
target = targets[0]
# Request bitesize pieces of the source and assign them to the
# target.
# NB. This algorithm does not use the minimal number of chunks.
# e.g. If the second dimension could be sliced as 0:99, 99:100
# then clearly the first dimension would have to be single
# slices for the 0:99 case, but could be bigger slices for the
# 99:100 case.
# It's not yet clear if this really matters.
all_slices = _all_slices(array)
for index in np.ndindex(*[len(slices) for slices in all_slices]):
keys = tuple(slices[i] for slices, i in zip(all_slices, index))
if masked:
target[keys] = array[keys].masked_array()
else:
target[keys] = array[keys].ndarray()
|
Count the non-masked elements of the array along the given axis.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:return: The Array representing the requested mean.
:rtype: Array
def count(a, axis=None):
"""
Count the non-masked elements of the array along the given axis.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:return: The Array representing the requested mean.
:rtype: Array
"""
axes = _normalise_axis(axis, a)
if axes is None or len(axes) != 1:
msg = "This operation is currently limited to a single axis"
raise AxisSupportError(msg)
return _Aggregation(a, axes[0],
_CountStreamsHandler, _CountMaskedStreamsHandler,
np.dtype('i'), {})
|
Request the minimum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose minimum is to be found.
axis : None, or int, or iterable of ints
Axis or axes along which the operation is performed. The default
(axis=None) is to perform the operation over all the dimensions of the
input array. The axis may be negative, in which case it counts from
the last to the first axis. If axis is a tuple of ints, the operation
is performed over multiple axes.
Returns
-------
out : Array
The Array representing the requested mean.
def min(a, axis=None):
"""
Request the minimum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose minimum is to be found.
axis : None, or int, or iterable of ints
Axis or axes along which the operation is performed. The default
(axis=None) is to perform the operation over all the dimensions of the
input array. The axis may be negative, in which case it counts from
the last to the first axis. If axis is a tuple of ints, the operation
is performed over multiple axes.
Returns
-------
out : Array
The Array representing the requested mean.
"""
axes = _normalise_axis(axis, a)
assert axes is not None and len(axes) == 1
return _Aggregation(a, axes[0],
_MinStreamsHandler, _MinMaskedStreamsHandler,
a.dtype, {})
|
Request the maximum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose maximum is to be found.
axis : None, or int, or iterable of ints
Axis or axes along which the operation is performed. The default
(axis=None) is to perform the operation over all the dimensions of the
input array. The axis may be negative, in which case it counts from
the last to the first axis. If axis is a tuple of ints, the operation
is performed over multiple axes.
Returns
-------
out : Array
The Array representing the requested max.
def max(a, axis=None):
"""
Request the maximum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose maximum is to be found.
axis : None, or int, or iterable of ints
Axis or axes along which the operation is performed. The default
(axis=None) is to perform the operation over all the dimensions of the
input array. The axis may be negative, in which case it counts from
the last to the first axis. If axis is a tuple of ints, the operation
is performed over multiple axes.
Returns
-------
out : Array
The Array representing the requested max.
"""
axes = _normalise_axis(axis, a)
assert axes is not None and len(axes) == 1
return _Aggregation(a, axes[0],
_MaxStreamsHandler, _MaxMaskedStreamsHandler,
a.dtype, {})
|
Request the sum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose summation is to be found.
axis : None, or int, or iterable of ints
Axis or axes along which the operation is performed. The default
(axis=None) is to perform the operation over all the dimensions of the
input array. The axis may be negative, in which case it counts from
the last to the first axis. If axis is a tuple of ints, the operation
is performed over multiple axes.
Returns
-------
out : Array
The Array representing the requested sum.
def sum(a, axis=None):
"""
Request the sum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose summation is to be found.
axis : None, or int, or iterable of ints
Axis or axes along which the operation is performed. The default
(axis=None) is to perform the operation over all the dimensions of the
input array. The axis may be negative, in which case it counts from
the last to the first axis. If axis is a tuple of ints, the operation
is performed over multiple axes.
Returns
-------
out : Array
The Array representing the requested sum.
"""
axes = _normalise_axis(axis, a)
assert axes is not None and len(axes) == 1
return _Aggregation(a, axes[0],
_SumStreamsHandler, _SumMaskedStreamsHandler,
a.dtype, {})
|
Request the mean of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:param float mdtol: Tolerance of missing data. The value in each
element of the resulting array will be masked if the
fraction of masked data contributing to that element
exceeds mdtol. mdtol=0 means no missing data is
tolerated while mdtol=1 will mean the resulting
element will be masked if and only if all the
contributing elements of the source array are masked.
Defaults to 1.
:return: The Array representing the requested mean.
:rtype: Array
def mean(a, axis=None, mdtol=1):
"""
Request the mean of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:param float mdtol: Tolerance of missing data. The value in each
element of the resulting array will be masked if the
fraction of masked data contributing to that element
exceeds mdtol. mdtol=0 means no missing data is
tolerated while mdtol=1 will mean the resulting
element will be masked if and only if all the
contributing elements of the source array are masked.
Defaults to 1.
:return: The Array representing the requested mean.
:rtype: Array
"""
axes = _normalise_axis(axis, a)
if axes is None or len(axes) != 1:
msg = "This operation is currently limited to a single axis"
raise AxisSupportError(msg)
dtype = (np.array([0], dtype=a.dtype) / 1.).dtype
kwargs = dict(mdtol=mdtol)
return _Aggregation(a, axes[0],
_MeanStreamsHandler, _MeanMaskedStreamsHandler,
dtype, kwargs)
|
Request the standard deviation of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:param int ddof: Delta Degrees of Freedom. The divisor used in
calculations is N - ddof, where N represents the
number of elements. By default ddof is zero.
:return: The Array representing the requested standard deviation.
:rtype: Array
def std(a, axis=None, ddof=0):
"""
Request the standard deviation of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:param int ddof: Delta Degrees of Freedom. The divisor used in
calculations is N - ddof, where N represents the
number of elements. By default ddof is zero.
:return: The Array representing the requested standard deviation.
:rtype: Array
"""
axes = _normalise_axis(axis, a)
if axes is None or len(axes) != 1:
msg = "This operation is currently limited to a single axis"
raise AxisSupportError(msg)
dtype = (np.array([0], dtype=a.dtype) / 1.).dtype
return _Aggregation(a, axes[0],
_StdStreamsHandler, _StdMaskedStreamsHandler,
dtype, dict(ddof=ddof))
|
Request the variance of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:param int ddof: Delta Degrees of Freedom. The divisor used in
calculations is N - ddof, where N represents the
number of elements. By default ddof is zero.
:return: The Array representing the requested variance.
:rtype: Array
def var(a, axis=None, ddof=0):
"""
Request the variance of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the input array.
The axis may be negative, in which case it counts from
the last to the first axis.
If axis is a tuple of ints, the operation is performed
over multiple axes.
:type axis: None, or int, or iterable of ints.
:param int ddof: Delta Degrees of Freedom. The divisor used in
calculations is N - ddof, where N represents the
number of elements. By default ddof is zero.
:return: The Array representing the requested variance.
:rtype: Array
"""
axes = _normalise_axis(axis, a)
if axes is None or len(axes) != 1:
msg = "This operation is currently limited to a single axis"
raise AxisSupportError(msg)
dtype = (np.array([0], dtype=a.dtype) / 1.).dtype
return _Aggregation(a, axes[0],
_VarStreamsHandler, _VarMaskedStreamsHandler,
dtype, dict(ddof=ddof))
|
A function to generate the top level biggus ufunc wrappers.
def _ufunc_wrapper(ufunc, name=None):
"""
A function to generate the top level biggus ufunc wrappers.
"""
if not isinstance(ufunc, np.ufunc):
raise TypeError('{} is not a ufunc'.format(ufunc))
ufunc_name = ufunc.__name__
# Get hold of the masked array equivalent, if it exists.
ma_ufunc = getattr(np.ma, ufunc_name, None)
if ufunc.nin == 2 and ufunc.nout == 1:
func = _dual_input_fn_wrapper('np.{}'.format(ufunc_name), ufunc,
ma_ufunc, name)
elif ufunc.nin == 1 and ufunc.nout == 1:
func = _unary_fn_wrapper('np.{}'.format(ufunc_name), ufunc, ma_ufunc,
name)
else:
raise ValueError('Unsupported ufunc {!r} with {} input arrays & {} '
'output arrays.'.format(ufunc_name, ufunc.nin,
ufunc.nout))
return func
|
Returns the shape that results from slicing an array of the given
shape by the given keys.
>>> _sliced_shape(shape=(52350, 70, 90, 180),
... keys=(np.newaxis, slice(None, 10), 3,
... slice(None), slice(2, 3)))
(1, 10, 90, 1)
def _sliced_shape(shape, keys):
"""
Returns the shape that results from slicing an array of the given
shape by the given keys.
>>> _sliced_shape(shape=(52350, 70, 90, 180),
... keys=(np.newaxis, slice(None, 10), 3,
... slice(None), slice(2, 3)))
(1, 10, 90, 1)
"""
keys = _full_keys(keys, len(shape))
sliced_shape = []
shape_dim = -1
for key in keys:
shape_dim += 1
if _is_scalar(key):
continue
elif isinstance(key, slice):
size = len(range(*key.indices(shape[shape_dim])))
sliced_shape.append(size)
elif isinstance(key, np.ndarray) and key.dtype == np.dtype('bool'):
# Numpy boolean indexing.
sliced_shape.append(builtins.sum(key))
elif isinstance(key, (tuple, np.ndarray)):
sliced_shape.append(len(key))
elif key is np.newaxis:
shape_dim -= 1
sliced_shape.append(1)
else:
raise ValueError('Invalid indexing object "{}"'.format(key))
sliced_shape = tuple(sliced_shape)
return sliced_shape
|
Given keys such as those passed to ``__getitem__`` for an
array of ndim, return a fully expanded tuple of keys.
In all instances, the result of this operation should follow:
array[keys] == array[_full_keys(keys, array.ndim)]
def _full_keys(keys, ndim):
"""
Given keys such as those passed to ``__getitem__`` for an
array of ndim, return a fully expanded tuple of keys.
In all instances, the result of this operation should follow:
array[keys] == array[_full_keys(keys, array.ndim)]
"""
if not isinstance(keys, tuple):
keys = (keys,)
# Make keys mutable, and take a copy.
keys = list(keys)
# Count the number of keys which actually slice a dimension.
n_keys_non_newaxis = len([key for key in keys if key is not np.newaxis])
# Numpy allows an extra dimension to be an Ellipsis, we remove it here
# if Ellipsis is in keys, if this doesn't trigger we will raise an
# IndexError.
is_ellipsis = [key is Ellipsis for key in keys]
if n_keys_non_newaxis - 1 >= ndim and any(is_ellipsis):
# Remove the left-most Ellipsis, as numpy does.
keys.pop(is_ellipsis.index(True))
n_keys_non_newaxis -= 1
if n_keys_non_newaxis > ndim:
raise IndexError('Dimensions are over specified for indexing.')
lh_keys = []
# Keys, with the last key first.
rh_keys = []
take_from_left = True
while keys:
if take_from_left:
next_key = keys.pop(0)
keys_list = lh_keys
else:
next_key = keys.pop(-1)
keys_list = rh_keys
if next_key is Ellipsis:
next_key = slice(None)
take_from_left = not take_from_left
keys_list.append(next_key)
middle = [slice(None)] * (ndim - n_keys_non_newaxis)
return tuple(lh_keys + middle + rh_keys[::-1])
|
Assert that the given array is an Array subclass (or numpy array).
If the given array is a numpy.ndarray an appropriate NumpyArrayAdapter
instance is created, otherwise the passed array must be a subclass of
:class:`Array` else a TypeError will be raised.
def ensure_array(array):
"""
Assert that the given array is an Array subclass (or numpy array).
If the given array is a numpy.ndarray an appropriate NumpyArrayAdapter
instance is created, otherwise the passed array must be a subclass of
:class:`Array` else a TypeError will be raised.
"""
if not isinstance(array, Array):
if isinstance(array, np.ndarray):
array = NumpyArrayAdapter(array)
elif np.isscalar(array):
array = ConstantArray([], array)
else:
raise TypeError('The given array should be a `biggus.Array` '
'instance, got {}.'.format(type(array)))
return array
|
Return a human-readable description of the number of bytes required
to store the data of the given array.
For example::
>>> array.nbytes
14000000
>> biggus.size(array)
'13.35 MiB'
Parameters
----------
array : array-like object
The array object must provide an `nbytes` property.
Returns
-------
out : str
The Array representing the requested mean.
def size(array):
"""
Return a human-readable description of the number of bytes required
to store the data of the given array.
For example::
>>> array.nbytes
14000000
>> biggus.size(array)
'13.35 MiB'
Parameters
----------
array : array-like object
The array object must provide an `nbytes` property.
Returns
-------
out : str
The Array representing the requested mean.
"""
nbytes = array.nbytes
if nbytes < (1 << 10):
size = '{} B'.format(nbytes)
elif nbytes < (1 << 20):
size = '{:.02f} KiB'.format(nbytes / (1 << 10))
elif nbytes < (1 << 30):
size = '{:.02f} MiB'.format(nbytes / (1 << 20))
elif nbytes < (1 << 40):
size = '{:.02f} GiB'.format(nbytes / (1 << 30))
else:
size = '{:.02f} TiB'.format(nbytes / (1 << 40))
return size
|
Dispatch the given Chunk onto all the registered output queues.
If the chunk is None, it is silently ignored.
def output(self, chunk):
"""
Dispatch the given Chunk onto all the registered output queues.
If the chunk is None, it is silently ignored.
"""
if chunk is not None:
for queue in self.output_queues:
queue.put(chunk)
|
Emit the Chunk instances which cover the underlying Array.
The Array is divided into chunks with a size limit of
MAX_CHUNK_SIZE which are emitted into all registered output
queues.
def run(self):
"""
Emit the Chunk instances which cover the underlying Array.
The Array is divided into chunks with a size limit of
MAX_CHUNK_SIZE which are emitted into all registered output
queues.
"""
try:
chunk_index = self.chunk_index_gen(self.array.shape,
self.iteration_order)
for key in chunk_index:
# Now we have the slices that describe the next chunk.
# For example, key might be equivalent to
# `[11:12, 0:3, :, :]`.
# Simply "realise" the data for that region and emit it
# as a Chunk to all registered output queues.
if self.masked:
data = self.array[key].masked_array()
else:
data = self.array[key].ndarray()
output_chunk = Chunk(key, data)
self.output(output_chunk)
except:
self.abort()
raise
else:
for queue in self.output_queues:
queue.put(QUEUE_FINISHED)
|
Set the given nodes as inputs for this node.
Creates a limited-size queue.Queue for each input node and
registers each queue as an output of its corresponding node.
def add_input_nodes(self, input_nodes):
"""
Set the given nodes as inputs for this node.
Creates a limited-size queue.Queue for each input node and
registers each queue as an output of its corresponding node.
"""
self.input_queues = [queue.Queue(maxsize=3) for _ in input_nodes]
for input_node, input_queue in zip(input_nodes, self.input_queues):
input_node.add_output_queue(input_queue)
|
Process the input queues in lock-step, and push any results to
the registered output queues.
def run(self):
"""
Process the input queues in lock-step, and push any results to
the registered output queues.
"""
try:
while True:
input_chunks = [input.get() for input in self.input_queues]
for input in self.input_queues:
input.task_done()
if any(chunk is QUEUE_ABORT for chunk in input_chunks):
self.abort()
return
if any(chunk is QUEUE_FINISHED for chunk in input_chunks):
break
self.output(self.process_chunks(input_chunks))
# Finalise the final chunk (process_chunks does this for all
# but the last chunk).
self.output(self.finalise())
except:
self.abort()
raise
else:
for queue in self.output_queues:
queue.put(QUEUE_FINISHED)
|
Store the incoming chunk at the corresponding position in the
result array.
def process_chunks(self, chunks):
"""
Store the incoming chunk at the corresponding position in the
result array.
"""
chunk, = chunks
if chunk.keys:
self.result[chunk.keys] = chunk.data
else:
self.result[...] = chunk.data
|
Return a key of type int, slice, or tuple that is guaranteed
to be valid for the given dimension size.
Raises IndexError/TypeError for invalid keys.
def _cleanup_new_key(self, key, size, axis):
"""
Return a key of type int, slice, or tuple that is guaranteed
to be valid for the given dimension size.
Raises IndexError/TypeError for invalid keys.
"""
if _is_scalar(key):
if key >= size or key < -size:
msg = 'index {0} is out of bounds for axis {1} with' \
' size {2}'.format(key, axis, size)
raise IndexError(msg)
elif isinstance(key, slice):
pass
elif isinstance(key, np.ndarray) and key.dtype == np.dtype('bool'):
if key.size > size:
msg = 'too many boolean indices. Boolean index array ' \
'of size {0} is greater than axis {1} with ' \
'size {2}'.format(key.size, axis, size)
raise IndexError(msg)
elif isinstance(key, collections.Iterable) and \
not isinstance(key, six.string_types):
# Make sure we capture the values in case we've
# been given a one-shot iterable, like a generator.
key = tuple(key)
for sub_key in key:
if sub_key >= size or sub_key < -size:
msg = 'index {0} is out of bounds for axis {1}' \
' with size {2}'.format(sub_key, axis, size)
raise IndexError(msg)
else:
raise TypeError('invalid key {!r}'.format(key))
return key
|
Return a key of type int, slice, or tuple that represents the
combination of new_key with the given indices.
Raises IndexError/TypeError for invalid keys.
def _remap_new_key(self, indices, new_key, axis):
"""
Return a key of type int, slice, or tuple that represents the
combination of new_key with the given indices.
Raises IndexError/TypeError for invalid keys.
"""
size = len(indices)
if _is_scalar(new_key):
if new_key >= size or new_key < -size:
msg = 'index {0} is out of bounds for axis {1}' \
' with size {2}'.format(new_key, axis, size)
raise IndexError(msg)
result_key = indices[new_key]
elif isinstance(new_key, slice):
result_key = indices.__getitem__(new_key)
elif isinstance(new_key, np.ndarray) and \
new_key.dtype == np.dtype('bool'):
# Numpy boolean indexing.
if new_key.size > size:
msg = 'too many boolean indices. Boolean index array ' \
'of size {0} is greater than axis {1} with ' \
'size {2}'.format(new_key.size, axis, size)
raise IndexError(msg)
result_key = tuple(np.array(indices)[new_key])
elif isinstance(new_key, collections.Iterable) and \
not isinstance(new_key, six.string_types):
# Make sure we capture the values in case we've
# been given a one-shot iterable, like a generator.
new_key = tuple(new_key)
for sub_key in new_key:
if sub_key >= size or sub_key < -size:
msg = 'index {0} is out of bounds for axis {1}' \
' with size {2}'.format(sub_key, axis, size)
raise IndexError(msg)
result_key = tuple(indices[key] for key in new_key)
else:
raise TypeError('invalid key {!r}'.format(new_key))
return result_key
|
Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem__`` keys.
inverse - bool
Whether to map old dimension to new dimension (forward), or
new dimension to old dimension (inverse). Default is False
(forward).
Returns
-------
A tuple derived from target which has been ordered based on the new
axes.
def _apply_axes_mapping(self, target, inverse=False):
"""
Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem__`` keys.
inverse - bool
Whether to map old dimension to new dimension (forward), or
new dimension to old dimension (inverse). Default is False
(forward).
Returns
-------
A tuple derived from target which has been ordered based on the new
axes.
"""
if len(target) != self.ndim:
raise ValueError('The target iterable is of length {}, but '
'should be of length {}.'.format(len(target),
self.ndim))
if inverse:
axis_map = self._inverse_axes_map
else:
axis_map = self._forward_axes_map
result = [None] * self.ndim
for axis, item in enumerate(target):
result[axis_map[axis]] = item
return tuple(result)
|
Given input chunk keys, compute what keys will be needed to put
the result into the result array.
As an example of where this gets used - when we aggregate on a
particular axis, the source keys may be ``(0:2, None:None)``, but for
an aggregation on axis 0, they would result in target values on
dimension 2 only and so be ``(None: None, )``.
def output_keys(self, source_keys):
"""
Given input chunk keys, compute what keys will be needed to put
the result into the result array.
As an example of where this gets used - when we aggregate on a
particular axis, the source keys may be ``(0:2, None:None)``, but for
an aggregation on axis 0, they would result in target values on
dimension 2 only and so be ``(None: None, )``.
"""
keys = list(source_keys)
# Remove the aggregated axis from the keys.
del keys[self.axis]
return tuple(keys)
|
Implements scalarmult(B, e) more efficiently.
def scalarmult_B(e):
"""
Implements scalarmult(B, e) more efficiently.
"""
# scalarmult(B, l) is the identity
e = e % l
P = ident
for i in range(253):
if e & 1:
P = edwards_add(P, Bpow[i])
e = e // 2
assert e == 0, e
return P
|
Not safe to use with secret keys or secret data.
See module docstring. This function should be used for testing only.
def publickey_unsafe(sk):
"""
Not safe to use with secret keys or secret data.
See module docstring. This function should be used for testing only.
"""
h = H(sk)
a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2))
A = scalarmult_B(a)
return encodepoint(A)
|
<Purpose>
Generate a pair of ed25519 public and private keys with PyNaCl. The public
and private keys returned conform to
'securesystemslib.formats.ED25519PULIC_SCHEMA' and
'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the
form:
'\xa2F\x99\xe0\x86\x80%\xc8\xee\x11\xb95T\xd9\...'
An ed25519 seed key is a random 32-byte string. Public keys are also 32
bytes.
>>> public, private = generate_public_and_private()
>>> securesystemslib.formats.ED25519PUBLIC_SCHEMA.matches(public)
True
>>> securesystemslib.formats.ED25519SEED_SCHEMA.matches(private)
True
<Arguments>
None.
<Exceptions>
securesystemslib.exceptions.UnsupportedLibraryError, if the PyNaCl ('nacl')
module is unavailable.
NotImplementedError, if a randomness source is not found by 'os.urandom'.
<Side Effects>
The ed25519 keys are generated by first creating a random 32-byte seed
with os.urandom() and then calling PyNaCl's nacl.signing.SigningKey().
<Returns>
A (public, private) tuple that conform to
'securesystemslib.formats.ED25519PUBLIC_SCHEMA' and
'securesystemslib.formats.ED25519SEED_SCHEMA', respectively.
def generate_public_and_private():
"""
<Purpose>
Generate a pair of ed25519 public and private keys with PyNaCl. The public
and private keys returned conform to
'securesystemslib.formats.ED25519PULIC_SCHEMA' and
'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the
form:
'\xa2F\x99\xe0\x86\x80%\xc8\xee\x11\xb95T\xd9\...'
An ed25519 seed key is a random 32-byte string. Public keys are also 32
bytes.
>>> public, private = generate_public_and_private()
>>> securesystemslib.formats.ED25519PUBLIC_SCHEMA.matches(public)
True
>>> securesystemslib.formats.ED25519SEED_SCHEMA.matches(private)
True
<Arguments>
None.
<Exceptions>
securesystemslib.exceptions.UnsupportedLibraryError, if the PyNaCl ('nacl')
module is unavailable.
NotImplementedError, if a randomness source is not found by 'os.urandom'.
<Side Effects>
The ed25519 keys are generated by first creating a random 32-byte seed
with os.urandom() and then calling PyNaCl's nacl.signing.SigningKey().
<Returns>
A (public, private) tuple that conform to
'securesystemslib.formats.ED25519PUBLIC_SCHEMA' and
'securesystemslib.formats.ED25519SEED_SCHEMA', respectively.
"""
# Generate ed25519's seed key by calling os.urandom(). The random bytes
# returned should be suitable for cryptographic use and is OS-specific.
# Raise 'NotImplementedError' if a randomness source is not found.
# ed25519 seed keys are fixed at 32 bytes (256-bit keys).
# http://blog.mozilla.org/warner/2011/11/29/ed25519-keys/
seed = os.urandom(32)
public = None
# Generate the public key. PyNaCl (i.e., 'nacl' module) performs the actual
# key generation.
try:
nacl_key = nacl.signing.SigningKey(seed)
public = nacl_key.verify_key.encode(encoder=nacl.encoding.RawEncoder())
except NameError: # pragma: no cover
raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl'
' library and/or its dependencies unavailable.')
return public, seed
|
<Purpose>
Return a (signature, scheme) tuple, where the signature scheme is 'ed25519'
and is always generated by PyNaCl (i.e., 'nacl'). The signature returned
conforms to 'securesystemslib.formats.ED25519SIGNATURE_SCHEMA', and has the
form:
'\xae\xd7\x9f\xaf\x95{bP\x9e\xa8YO Z\x86\x9d...'
A signature is a 64-byte string.
>>> public, private = generate_public_and_private()
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> scheme = 'ed25519'
>>> signature, scheme = \
create_signature(public, private, data, scheme)
>>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature)
True
>>> scheme == 'ed25519'
True
>>> signature, scheme = \
create_signature(public, private, data, scheme)
>>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature)
True
>>> scheme == 'ed25519'
True
<Arguments>
public:
The ed25519 public key, which is a 32-byte string.
private:
The ed25519 private key, which is a 32-byte string.
data:
Data object used by create_signature() to generate the signature.
scheme:
The signature scheme used to generate the signature.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if a signature cannot be created.
<Side Effects>
nacl.signing.SigningKey.sign() called to generate the actual signature.
<Returns>
A signature dictionary conformat to
'securesystemslib.format.SIGNATURE_SCHEMA'. ed25519 signatures are 64
bytes, however, the hexlified signature is stored in the dictionary
returned.
def create_signature(public_key, private_key, data, scheme):
"""
<Purpose>
Return a (signature, scheme) tuple, where the signature scheme is 'ed25519'
and is always generated by PyNaCl (i.e., 'nacl'). The signature returned
conforms to 'securesystemslib.formats.ED25519SIGNATURE_SCHEMA', and has the
form:
'\xae\xd7\x9f\xaf\x95{bP\x9e\xa8YO Z\x86\x9d...'
A signature is a 64-byte string.
>>> public, private = generate_public_and_private()
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> scheme = 'ed25519'
>>> signature, scheme = \
create_signature(public, private, data, scheme)
>>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature)
True
>>> scheme == 'ed25519'
True
>>> signature, scheme = \
create_signature(public, private, data, scheme)
>>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature)
True
>>> scheme == 'ed25519'
True
<Arguments>
public:
The ed25519 public key, which is a 32-byte string.
private:
The ed25519 private key, which is a 32-byte string.
data:
Data object used by create_signature() to generate the signature.
scheme:
The signature scheme used to generate the signature.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if a signature cannot be created.
<Side Effects>
nacl.signing.SigningKey.sign() called to generate the actual signature.
<Returns>
A signature dictionary conformat to
'securesystemslib.format.SIGNATURE_SCHEMA'. ed25519 signatures are 64
bytes, however, the hexlified signature is stored in the dictionary
returned.
"""
# Does 'public_key' have the correct format?
# This check will ensure 'public_key' conforms to
# 'securesystemslib.formats.ED25519PUBLIC_SCHEMA', which must have length 32
# bytes. Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.ED25519PUBLIC_SCHEMA.check_match(public_key)
# Is 'private_key' properly formatted?
securesystemslib.formats.ED25519SEED_SCHEMA.check_match(private_key)
# Is 'scheme' properly formatted?
securesystemslib.formats.ED25519_SIG_SCHEMA.check_match(scheme)
# Signing the 'data' object requires a seed and public key.
# nacl.signing.SigningKey.sign() generates the signature.
public = public_key
private = private_key
signature = None
# An if-clause is not strictly needed here, since 'ed25519' is the only
# currently supported scheme. Nevertheless, include the conditional
# statement to accommodate schemes that might be added in the future.
if scheme == 'ed25519':
try:
nacl_key = nacl.signing.SigningKey(private)
nacl_sig = nacl_key.sign(data)
signature = nacl_sig.signature
# The unit tests expect required libraries to be installed.
except NameError: # pragma: no cover
raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl'
' library and/or its dependencies unavailable.')
except (ValueError, TypeError, nacl.exceptions.CryptoError) as e:
raise securesystemslib.exceptions.CryptoError('An "ed25519" signature'
' could not be created with PyNaCl.' + str(e))
# This is a defensive check for a valid 'scheme', which should have already
# been validated in the check_match() above.
else: #pragma: no cover
raise securesystemslib.exceptions.UnsupportedAlgorithmError('Unsupported'
' signature scheme is specified: ' + repr(scheme))
return signature, scheme
|
<Purpose>
Determine whether the private key corresponding to 'public_key' produced
'signature'. verify_signature() will use the public key, the 'scheme' and
'sig', and 'data' arguments to complete the verification.
>>> public, private = generate_public_and_private()
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> scheme = 'ed25519'
>>> signature, scheme = \
create_signature(public, private, data, scheme)
>>> verify_signature(public, scheme, signature, data, use_pynacl=False)
True
>>> verify_signature(public, scheme, signature, data, use_pynacl=True)
True
>>> bad_data = b'The sly brown fox jumps over the lazy dog'
>>> bad_signature, scheme = \
create_signature(public, private, bad_data, scheme)
>>> verify_signature(public, scheme, bad_signature, data, use_pynacl=False)
False
<Arguments>
public_key:
The public key is a 32-byte string.
scheme:
'ed25519' signature scheme used by either the pure python
implementation (i.e., ed25519.py) or PyNacl (i.e., 'nacl').
signature:
The signature is a 64-byte string.
data:
Data object used by securesystemslib.ed25519_keys.create_signature() to
generate 'signature'. 'data' is needed here to verify the signature.
use_pynacl:
True, if the ed25519 signature should be verified by PyNaCl. False,
if the signature should be verified with the pure Python implementation
of ed25519 (slower).
<Exceptions>
securesystemslib.exceptions.UnsupportedAlgorithmError. Raised if the
signature scheme 'scheme' is not one supported by
securesystemslib.ed25519_keys.create_signature().
securesystemslib.exceptions.FormatError. Raised if the arguments are
improperly formatted.
<Side Effects>
securesystemslib._vendor.ed25519.ed25519.checkvalid() called to do the
actual verification. nacl.signing.VerifyKey.verify() called if
'use_pynacl' is True.
<Returns>
Boolean. True if the signature is valid, False otherwise.
def verify_signature(public_key, scheme, signature, data, use_pynacl=False):
"""
<Purpose>
Determine whether the private key corresponding to 'public_key' produced
'signature'. verify_signature() will use the public key, the 'scheme' and
'sig', and 'data' arguments to complete the verification.
>>> public, private = generate_public_and_private()
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> scheme = 'ed25519'
>>> signature, scheme = \
create_signature(public, private, data, scheme)
>>> verify_signature(public, scheme, signature, data, use_pynacl=False)
True
>>> verify_signature(public, scheme, signature, data, use_pynacl=True)
True
>>> bad_data = b'The sly brown fox jumps over the lazy dog'
>>> bad_signature, scheme = \
create_signature(public, private, bad_data, scheme)
>>> verify_signature(public, scheme, bad_signature, data, use_pynacl=False)
False
<Arguments>
public_key:
The public key is a 32-byte string.
scheme:
'ed25519' signature scheme used by either the pure python
implementation (i.e., ed25519.py) or PyNacl (i.e., 'nacl').
signature:
The signature is a 64-byte string.
data:
Data object used by securesystemslib.ed25519_keys.create_signature() to
generate 'signature'. 'data' is needed here to verify the signature.
use_pynacl:
True, if the ed25519 signature should be verified by PyNaCl. False,
if the signature should be verified with the pure Python implementation
of ed25519 (slower).
<Exceptions>
securesystemslib.exceptions.UnsupportedAlgorithmError. Raised if the
signature scheme 'scheme' is not one supported by
securesystemslib.ed25519_keys.create_signature().
securesystemslib.exceptions.FormatError. Raised if the arguments are
improperly formatted.
<Side Effects>
securesystemslib._vendor.ed25519.ed25519.checkvalid() called to do the
actual verification. nacl.signing.VerifyKey.verify() called if
'use_pynacl' is True.
<Returns>
Boolean. True if the signature is valid, False otherwise.
"""
# Does 'public_key' have the correct format?
# This check will ensure 'public_key' conforms to
# 'securesystemslib.formats.ED25519PUBLIC_SCHEMA', which must have length 32
# bytes. Raise 'securesystemslib.exceptions.FormatError' if the check fails.
securesystemslib.formats.ED25519PUBLIC_SCHEMA.check_match(public_key)
# Is 'scheme' properly formatted?
securesystemslib.formats.ED25519_SIG_SCHEMA.check_match(scheme)
# Is 'signature' properly formatted?
securesystemslib.formats.ED25519SIGNATURE_SCHEMA.check_match(signature)
# Is 'use_pynacl' properly formatted?
securesystemslib.formats.BOOLEAN_SCHEMA.check_match(use_pynacl)
# Verify 'signature'. Before returning the Boolean result, ensure 'ed25519'
# was used as the signature scheme. Raise
# 'securesystemslib.exceptions.UnsupportedLibraryError' if 'use_pynacl' is
# True but 'nacl' is unavailable.
public = public_key
valid_signature = False
if scheme in _SUPPORTED_ED25519_SIGNING_SCHEMES:
if use_pynacl:
try:
nacl_verify_key = nacl.signing.VerifyKey(public)
nacl_message = nacl_verify_key.verify(data, signature)
valid_signature = True
# The unit tests expect PyNaCl to be installed.
except NameError: # pragma: no cover
raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl'
' library and/or its dependencies unavailable.')
except nacl.exceptions.BadSignatureError:
pass
# Verify 'ed25519' signature with the pure Python implementation.
else:
try:
securesystemslib._vendor.ed25519.ed25519.checkvalid(signature,
data, public)
valid_signature = True
# The pure Python implementation raises 'Exception' if 'signature' is
# invalid.
except Exception as e:
pass
# This is a defensive check for a valid 'scheme', which should have already
# been validated in the ED25519_SIG_SCHEMA.check_match(scheme) above.
else: #pragma: no cover
message = 'Unsupported ed25519 signature scheme: ' + repr(scheme) + '.\n' + \
'Supported schemes: ' + repr(_SUPPORTED_ED25519_SIGNING_SCHEMES) + '.'
raise securesystemslib.exceptions.UnsupportedAlgorithmError(message)
return valid_signature
|
Cleanly deletes a file in `n` attempts (if necessary)
def _delete_file(fileName, n=10):
"""Cleanly deletes a file in `n` attempts (if necessary)"""
status = False
count = 0
while not status and count < n:
try:
_os.remove(fileName)
except OSError:
count += 1
_time.sleep(0.2)
else:
status = True
return status
|
Initiates link with OpticStudio DDE server
def zDDEInit(self):
"""Initiates link with OpticStudio DDE server"""
self.pyver = _get_python_version()
# do this only one time or when there is no channel
if _PyZDDE.liveCh==0:
try:
_PyZDDE.server = _dde.CreateServer()
_PyZDDE.server.Create("ZCLIENT")
except Exception as err:
_sys.stderr.write("{}: DDE server may be in use!".format(str(err)))
return -1
# Try to create individual conversations for each ZEMAX application.
self.conversation = _dde.CreateConversation(_PyZDDE.server)
try:
self.conversation.ConnectTo(self.appName, " ")
except Exception as err:
_sys.stderr.write("{}.\nOpticStudio UI may not be running!\n".format(str(err)))
# should close the DDE server if it exist
self.zDDEClose()
return -1
else:
_PyZDDE.liveCh += 1
self.connection = True
return 0
|
Close the DDE link with Zemax server
def zDDEClose(self):
"""Close the DDE link with Zemax server"""
if _PyZDDE.server and not _PyZDDE.liveCh:
_PyZDDE.server.Shutdown(self.conversation)
_PyZDDE.server = 0
elif _PyZDDE.server and self.connection and _PyZDDE.liveCh == 1:
_PyZDDE.server.Shutdown(self.conversation)
self.connection = False
self.appName = ''
_PyZDDE.liveCh -= 1
_PyZDDE.server = 0
elif self.connection:
_PyZDDE.server.Shutdown(self.conversation)
self.connection = False
self.appName = ''
_PyZDDE.liveCh -= 1
return 0
|
Set global timeout value, in seconds, for all DDE calls
def setTimeout(self, time):
"""Set global timeout value, in seconds, for all DDE calls"""
self.conversation.SetDDETimeout(round(time))
return self.conversation.GetDDETimeout()
|
Send command to DDE client
def _sendDDEcommand(self, cmd, timeout=None):
"""Send command to DDE client"""
reply = self.conversation.Request(cmd, timeout)
if self.pyver > 2:
reply = reply.decode('ascii').rstrip()
return reply
|
Update the lens
def zGetUpdate(self):
"""Update the lens"""
status,ret = -998, None
ret = self._sendDDEcommand("GetUpdate")
if ret != None:
status = int(ret) #Note: Zemax returns -1 if GetUpdate fails.
return status
|
Loads a zmx file into the DDE server
def zLoadFile(self, fileName, append=None):
"""Loads a zmx file into the DDE server"""
reply = None
if append:
cmd = "LoadFile,{},{}".format(fileName, append)
else:
cmd = "LoadFile,{}".format(fileName)
reply = self._sendDDEcommand(cmd)
if reply:
return int(reply) #Note: Zemax returns -999 if update fails.
else:
return -998
|
Copy lens in the Zemax DDE server into LDE
def zPushLens(self, update=None, timeout=None):
"""Copy lens in the Zemax DDE server into LDE"""
reply = None
if update == 1:
reply = self._sendDDEcommand('PushLens,1', timeout)
elif update == 0 or update is None:
reply = self._sendDDEcommand('PushLens,0', timeout)
else:
raise ValueError('Invalid value for flag')
if reply:
return int(reply) # Note: Zemax returns -999 if push lens fails
else:
return -998
|
Saves the lens currently loaded in the server to a Zemax file
def zSaveFile(self, fileName):
"""Saves the lens currently loaded in the server to a Zemax file """
cmd = "SaveFile,{}".format(fileName)
reply = self._sendDDEcommand(cmd)
return int(float(reply.rstrip()))
|
Turn on sync-with-ui
def zSyncWithUI(self):
"""Turn on sync-with-ui"""
if not OpticalSystem._dde_link:
OpticalSystem._dde_link = _get_new_dde_link()
if not self._sync_ui_file:
self._sync_ui_file = _get_sync_ui_filename()
self._sync_ui = True
|
Push lens in ZOS COM server to UI
def zPushLens(self, update=None):
"""Push lens in ZOS COM server to UI"""
self.SaveAs(self._sync_ui_file)
OpticalSystem._dde_link.zLoadFile(self._sync_ui_file)
OpticalSystem._dde_link.zPushLens(update)
|
Copy lens in UI to headless ZOS COM server
def zGetRefresh(self):
"""Copy lens in UI to headless ZOS COM server"""
OpticalSystem._dde_link.zGetRefresh()
OpticalSystem._dde_link.zSaveFile(self._sync_ui_file)
self._iopticalsystem.LoadFile (self._sync_ui_file, False)
|
Saves the current system to the specified file.
@param filename: absolute path (string)
@return: None
@raise: ValueError if path (excluding the zemax file name) is not valid
All future calls to `Save()` will use the same file.
def SaveAs(self, filename):
"""Saves the current system to the specified file.
@param filename: absolute path (string)
@return: None
@raise: ValueError if path (excluding the zemax file name) is not valid
All future calls to `Save()` will use the same file.
"""
directory, zfile = _os.path.split(filename)
if zfile.startswith('pyzos_ui_sync_file'):
self._iopticalsystem.SaveAs(filename)
else: # regular file
if not _os.path.exists(directory):
raise ValueError('{} is not valid.'.format(directory))
else:
self._file_to_save_on_Save = filename # store to use in Save()
self._iopticalsystem.SaveAs(filename)
|
Saves the current system
def Save(self):
"""Saves the current system"""
# This method is intercepted to allow ui_sync
if self._file_to_save_on_Save:
self._iopticalsystem.SaveAs(self._file_to_save_on_Save)
else:
self._iopticalsystem.Save()
|
Return surface data
def zGetSurfaceData(self, surfNum):
"""Return surface data"""
if self.pMode == 0: # Sequential mode
surf_data = _co.namedtuple('surface_data', ['radius', 'thick', 'material', 'semidia',
'conic', 'comment'])
surf = self.pLDE.GetSurfaceAt(surfNum)
return surf_data(surf.pRadius, surf.pThickness, surf.pMaterial, surf.pSemiDiameter,
surf.pConic, surf.pComment)
else:
raise NotImplementedError('Function not implemented for non-sequential mode')
|
Sets surface data
def zSetSurfaceData(self, surfNum, radius=None, thick=None, material=None, semidia=None,
conic=None, comment=None):
"""Sets surface data"""
if self.pMode == 0: # Sequential mode
surf = self.pLDE.GetSurfaceAt(surfNum)
if radius is not None:
surf.pRadius = radius
if thick is not None:
surf.pThickness = thick
if material is not None:
surf.pMaterial = material
if semidia is not None:
surf.pSemiDiameter = semidia
if conic is not None:
surf.pConic = conic
if comment is not None:
surf.pComment = comment
else:
raise NotImplementedError('Function not implemented for non-sequential mode')
|
Sets the default merit function for Sequential Merit Function Editor
Parameters
----------
ofType : integer
optimization function type (0=RMS, ...)
ofData : integer
optimization function data (0=Wavefront, 1=Spot Radius, ...)
ofRef : integer
optimization function reference (0=Centroid, ...)
pupilInteg : integer
pupil integration method (0=Gaussian Quadrature, 1=Rectangular Array)
rings : integer
rings (0=1, 1=2, 2=3, 3=4, ...)
arms : integer
arms (0=6, 1=8, 2=10, 3=12)
obscuration : real
obscuration
delVignetted : boolean
delete vignetted ?
useGlass : boolean
whether to use Glass settings for thickness boundary
glassMin : real
glass mininum thickness
glassMax : real
glass maximum thickness
glassEdge : real
glass edge thickness
useAir : boolean
whether to use Air settings for thickness boundary
airMin : real
air minimum thickness
airMax : real
air maximum thickness
airEdge : real
air edge thickness
axialSymm : boolean
assume axial symmetry
ignoreLatCol : boolean
ignore latent color
addFavOper : boolean
add favorite color
configNum : integer
configuration number (0=All)
startAt : integer
start at
relativeXWgt : real
relative X weight
overallWgt : real
overall weight
def zSetDefaultMeritFunctionSEQ(self, ofType=0, ofData=0, ofRef=0, pupilInteg=0, rings=0,
arms=0, obscuration=0, grid=0, delVignetted=False, useGlass=False,
glassMin=0, glassMax=1000, glassEdge=0, useAir=False, airMin=0,
airMax=1000, airEdge=0, axialSymm=True, ignoreLatCol=False,
addFavOper=False, startAt=1, relativeXWgt=1.0, overallWgt=1.0,
configNum=0):
"""Sets the default merit function for Sequential Merit Function Editor
Parameters
----------
ofType : integer
optimization function type (0=RMS, ...)
ofData : integer
optimization function data (0=Wavefront, 1=Spot Radius, ...)
ofRef : integer
optimization function reference (0=Centroid, ...)
pupilInteg : integer
pupil integration method (0=Gaussian Quadrature, 1=Rectangular Array)
rings : integer
rings (0=1, 1=2, 2=3, 3=4, ...)
arms : integer
arms (0=6, 1=8, 2=10, 3=12)
obscuration : real
obscuration
delVignetted : boolean
delete vignetted ?
useGlass : boolean
whether to use Glass settings for thickness boundary
glassMin : real
glass mininum thickness
glassMax : real
glass maximum thickness
glassEdge : real
glass edge thickness
useAir : boolean
whether to use Air settings for thickness boundary
airMin : real
air minimum thickness
airMax : real
air maximum thickness
airEdge : real
air edge thickness
axialSymm : boolean
assume axial symmetry
ignoreLatCol : boolean
ignore latent color
addFavOper : boolean
add favorite color
configNum : integer
configuration number (0=All)
startAt : integer
start at
relativeXWgt : real
relative X weight
overallWgt : real
overall weight
"""
mfe = self.pMFE
wizard = mfe.pSEQOptimizationWizard
wizard.pType = ofType
wizard.pData = ofData
wizard.pReference = ofRef
wizard.pPupilIntegrationMethod = pupilInteg
wizard.pRing = rings
wizard.pArm = arms
wizard.pObscuration = obscuration
wizard.pGrid = grid
wizard.pIsDeleteVignetteUsed = delVignetted
wizard.pIsGlassUsed = useGlass
wizard.pGlassMin = glassMin
wizard.pGlassMax = glassMax
wizard.pGlassEdge = glassEdge
wizard.pIsAirUsed = useAir
wizard.pAirMin = airMin
wizard.pAirMax = airMax
wizard.pAirEdge = airEdge
wizard.pIsAssumeAxialSymmetryUsed = axialSymm
wizard.pIsIgnoreLateralColorUsed = ignoreLatCol
wizard.pConfiguration = configNum
wizard.pIsAddFavoriteOperandsUsed = addFavOper
wizard.pStartAt = startAt
wizard.pRelativeXWeight = relativeXWgt
wizard.pOverallWeight = overallWgt
wizard.CommonSettings.OK()
|
<Purpose>
Convert 'datetime_object' (in datetime.datetime()) format) to a Unix/POSIX
timestamp. For example, Python's time.time() returns a Unix timestamp, and
includes the number of microseconds. 'datetime_object' is converted to UTC.
>>> datetime_object = datetime.datetime(1985, 10, 26, 1, 22)
>>> timestamp = datetime_to_unix_timestamp(datetime_object)
>>> timestamp
499137720
<Arguments>
datetime_object:
The datetime.datetime() object to convert to a Unix timestamp.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'datetime_object' is not a
datetime.datetime() object.
<Side Effects>
None.
<Returns>
A unix (posix) timestamp (e.g., 499137660).
def datetime_to_unix_timestamp(datetime_object):
"""
<Purpose>
Convert 'datetime_object' (in datetime.datetime()) format) to a Unix/POSIX
timestamp. For example, Python's time.time() returns a Unix timestamp, and
includes the number of microseconds. 'datetime_object' is converted to UTC.
>>> datetime_object = datetime.datetime(1985, 10, 26, 1, 22)
>>> timestamp = datetime_to_unix_timestamp(datetime_object)
>>> timestamp
499137720
<Arguments>
datetime_object:
The datetime.datetime() object to convert to a Unix timestamp.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'datetime_object' is not a
datetime.datetime() object.
<Side Effects>
None.
<Returns>
A unix (posix) timestamp (e.g., 499137660).
"""
# Is 'datetime_object' a datetime.datetime() object?
# Raise 'securesystemslib.exceptions.FormatError' if not.
if not isinstance(datetime_object, datetime.datetime):
message = repr(datetime_object) + ' is not a datetime.datetime() object.'
raise securesystemslib.exceptions.FormatError(message)
unix_timestamp = calendar.timegm(datetime_object.timetuple())
return unix_timestamp
|
<Purpose>
Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format)
to a datetime.datetime() object. 'unix_timestamp' is the number of seconds
since the epoch (January 1, 1970.)
>>> datetime_object = unix_timestamp_to_datetime(1445455680)
>>> datetime_object
datetime.datetime(2015, 10, 21, 19, 28)
<Arguments>
unix_timestamp:
An integer representing the time (e.g., 1445455680). Conformant to
'securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA'.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'unix_timestamp' is improperly
formatted.
<Side Effects>
None.
<Returns>
A datetime.datetime() object corresponding to 'unix_timestamp'.
def unix_timestamp_to_datetime(unix_timestamp):
"""
<Purpose>
Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format)
to a datetime.datetime() object. 'unix_timestamp' is the number of seconds
since the epoch (January 1, 1970.)
>>> datetime_object = unix_timestamp_to_datetime(1445455680)
>>> datetime_object
datetime.datetime(2015, 10, 21, 19, 28)
<Arguments>
unix_timestamp:
An integer representing the time (e.g., 1445455680). Conformant to
'securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA'.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'unix_timestamp' is improperly
formatted.
<Side Effects>
None.
<Returns>
A datetime.datetime() object corresponding to 'unix_timestamp'.
"""
# Is 'unix_timestamp' properly formatted?
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA.check_match(unix_timestamp)
# Convert 'unix_timestamp' to a 'time.struct_time', in UTC. The Daylight
# Savings Time (DST) flag is set to zero. datetime.fromtimestamp() is not
# used because it returns a local datetime.
struct_time = time.gmtime(unix_timestamp)
# Extract the (year, month, day, hour, minutes, seconds) arguments for the
# datetime object to be returned.
datetime_object = datetime.datetime(*struct_time[:6])
return datetime_object
|
<Purpose>
Return the base64 encoding of 'data' with whitespace and '=' signs omitted.
<Arguments>
data:
Binary or buffer of data to convert.
<Exceptions>
securesystemslib.exceptions.FormatError, if the base64 encoding fails or the
argument is invalid.
<Side Effects>
None.
<Returns>
A base64-encoded string.
def format_base64(data):
"""
<Purpose>
Return the base64 encoding of 'data' with whitespace and '=' signs omitted.
<Arguments>
data:
Binary or buffer of data to convert.
<Exceptions>
securesystemslib.exceptions.FormatError, if the base64 encoding fails or the
argument is invalid.
<Side Effects>
None.
<Returns>
A base64-encoded string.
"""
try:
return binascii.b2a_base64(data).decode('utf-8').rstrip('=\n ')
except (TypeError, binascii.Error) as e:
raise securesystemslib.exceptions.FormatError('Invalid base64'
' encoding: ' + str(e))
|
<Purpose>
Parse a base64 encoding with whitespace and '=' signs omitted.
<Arguments>
base64_string:
A string holding a base64 value.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'base64_string' cannot be parsed
due to an invalid base64 encoding.
<Side Effects>
None.
<Returns>
A byte string representing the parsed based64 encoding of
'base64_string'.
def parse_base64(base64_string):
"""
<Purpose>
Parse a base64 encoding with whitespace and '=' signs omitted.
<Arguments>
base64_string:
A string holding a base64 value.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'base64_string' cannot be parsed
due to an invalid base64 encoding.
<Side Effects>
None.
<Returns>
A byte string representing the parsed based64 encoding of
'base64_string'.
"""
if not isinstance(base64_string, six.string_types):
message = 'Invalid argument: '+repr(base64_string)
raise securesystemslib.exceptions.FormatError(message)
extra = len(base64_string) % 4
if extra:
padding = '=' * (4 - extra)
base64_string = base64_string + padding
try:
return binascii.a2b_base64(base64_string.encode('utf-8'))
except (TypeError, binascii.Error) as e:
raise securesystemslib.exceptions.FormatError('Invalid base64'
' encoding: ' + str(e))
|
<Purpose>
Encode 'object' in canonical JSON form, as specified at
http://wiki.laptop.org/go/Canonical_JSON . It's a restricted
dialect of JSON in which keys are always lexically sorted,
there is no whitespace, floats aren't allowed, and only quote
and backslash get escaped. The result is encoded in UTF-8,
and the resulting bits are passed to output_function (if provided),
or joined into a string and returned.
Note: This function should be called prior to computing the hash or
signature of a JSON object in TUF. For example, generating a signature
of a signing role object such as 'ROOT_SCHEMA' is required to ensure
repeatable hashes are generated across different json module versions
and platforms. Code elsewhere is free to dump JSON objects in any format
they wish (e.g., utilizing indentation and single quotes around object
keys). These objects are only required to be in "canonical JSON" format
when their hashes or signatures are needed.
>>> encode_canonical("")
'""'
>>> encode_canonical([1, 2, 3])
'[1,2,3]'
>>> encode_canonical([])
'[]'
>>> encode_canonical({"A": [99]})
'{"A":[99]}'
>>> encode_canonical({"x" : 3, "y" : 2})
'{"x":3,"y":2}'
<Arguments>
object:
The object to be encoded.
output_function:
The result will be passed as arguments to 'output_function'
(e.g., output_function('result')).
<Exceptions>
securesystemslib.exceptions.FormatError, if 'object' cannot be encoded or
'output_function' is not callable.
<Side Effects>
The results are fed to 'output_function()' if 'output_function' is set.
<Returns>
A string representing the 'object' encoded in canonical JSON form.
def encode_canonical(object, output_function=None):
"""
<Purpose>
Encode 'object' in canonical JSON form, as specified at
http://wiki.laptop.org/go/Canonical_JSON . It's a restricted
dialect of JSON in which keys are always lexically sorted,
there is no whitespace, floats aren't allowed, and only quote
and backslash get escaped. The result is encoded in UTF-8,
and the resulting bits are passed to output_function (if provided),
or joined into a string and returned.
Note: This function should be called prior to computing the hash or
signature of a JSON object in TUF. For example, generating a signature
of a signing role object such as 'ROOT_SCHEMA' is required to ensure
repeatable hashes are generated across different json module versions
and platforms. Code elsewhere is free to dump JSON objects in any format
they wish (e.g., utilizing indentation and single quotes around object
keys). These objects are only required to be in "canonical JSON" format
when their hashes or signatures are needed.
>>> encode_canonical("")
'""'
>>> encode_canonical([1, 2, 3])
'[1,2,3]'
>>> encode_canonical([])
'[]'
>>> encode_canonical({"A": [99]})
'{"A":[99]}'
>>> encode_canonical({"x" : 3, "y" : 2})
'{"x":3,"y":2}'
<Arguments>
object:
The object to be encoded.
output_function:
The result will be passed as arguments to 'output_function'
(e.g., output_function('result')).
<Exceptions>
securesystemslib.exceptions.FormatError, if 'object' cannot be encoded or
'output_function' is not callable.
<Side Effects>
The results are fed to 'output_function()' if 'output_function' is set.
<Returns>
A string representing the 'object' encoded in canonical JSON form.
"""
result = None
# If 'output_function' is unset, treat it as
# appending to a list.
if output_function is None:
result = []
output_function = result.append
try:
_encode_canonical(object, output_function)
except (TypeError, securesystemslib.exceptions.FormatError) as e:
message = 'Could not encode ' + repr(object) + ': ' + str(e)
raise securesystemslib.exceptions.FormatError(message)
# Return the encoded 'object' as a string.
# Note: Implies 'output_function' is None,
# otherwise results are sent to 'output_function'.
if result is not None:
return ''.join(result)
|
Process the error labels of a dependent variable 'value' to ensure uniqueness.
def process_error_labels(value):
""" Process the error labels of a dependent variable 'value' to ensure uniqueness. """
observed_error_labels = {}
for error in value.get('errors', []):
label = error.get('label', 'error')
if label not in observed_error_labels:
observed_error_labels[label] = 0
observed_error_labels[label] += 1
if observed_error_labels[label] > 1:
error['label'] = label + '_' + str(observed_error_labels[label])
# append "_1" to first error label that has a duplicate
if observed_error_labels[label] == 2:
for error1 in value.get('errors', []):
error1_label = error1.get('label', 'error')
if error1_label == label:
error1['label'] = label + "_1"
break
|
Returns a raw string representation of text
def raw(text):
"""Returns a raw string representation of text"""
new_string = ''
for char in text:
try:
new_string += escape_dict[char]
except KeyError:
new_string += char
return new_string
|
Retrieve a function from a library/DLL, and set the data types.
def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}):
"""Retrieve a function from a library/DLL, and set the data types."""
if libname not in _libcache:
_libcache[libname] = windll.LoadLibrary(libname)
func = getattr(_libcache[libname], funcname)
func.argtypes = argtypes
func.restype = restype
return func
|
Run the main windows message loop.
def WinMSGLoop():
"""Run the main windows message loop."""
LPMSG = POINTER(MSG)
LRESULT = c_ulong
GetMessage = get_winfunc("user32", "GetMessageW", BOOL, (LPMSG, HWND, UINT, UINT))
TranslateMessage = get_winfunc("user32", "TranslateMessage", BOOL, (LPMSG,))
# restype = LRESULT
DispatchMessage = get_winfunc("user32", "DispatchMessageW", LRESULT, (LPMSG,))
msg = MSG()
lpmsg = byref(msg)
while GetMessage(lpmsg, HWND(), 0, 0) > 0:
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
|
Exceptional error is handled in zdde Init() method, so the exception
must be re-raised
def ConnectTo(self, appName, data=None):
"""Exceptional error is handled in zdde Init() method, so the exception
must be re-raised"""
global number_of_apps_communicating
self.ddeServerName = appName
try:
self.ddec = DDEClient(self.ddeServerName, self.ddeClientName) # establish conversation
except DDEError:
raise
else:
number_of_apps_communicating +=1
|
Request DDE client
timeout in seconds
Note ... handle the exception within this function.
def Request(self, item, timeout=None):
"""Request DDE client
timeout in seconds
Note ... handle the exception within this function.
"""
if not timeout:
timeout = self.ddetimeout
try:
reply = self.ddec.request(item, int(timeout*1000)) # convert timeout into milliseconds
except DDEError:
err_str = str(sys.exc_info()[1])
error = err_str[err_str.find('err=')+4:err_str.find('err=')+10]
if error == hex(DMLERR_DATAACKTIMEOUT):
print("TIMEOUT REACHED. Please use a higher timeout.\n")
if (sys.version_info > (3, 0)): #this is only evaluated in case of an error
reply = b'-998' #Timeout error value
else:
reply = '-998' #Timeout error value
return reply
|
Request updates when DDE data changes.
def advise(self, item, stop=False):
"""Request updates when DDE data changes."""
hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE)
hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_ADVSTOP if stop else XTYP_ADVSTART, TIMEOUT_ASYNC, LPDWORD())
DDE.FreeStringHandle(self._idInst, hszItem)
if not hDdeData:
raise DDEError("Unable to %s advise" % ("stop" if stop else "start"), self._idInst)
DDE.FreeDataHandle(hDdeData)
|
Execute a DDE command.
def execute(self, command):
"""Execute a DDE command."""
pData = c_char_p(command)
cbData = DWORD(len(command) + 1)
hDdeData = DDE.ClientTransaction(pData, cbData, self._hConv, HSZ(), CF_TEXT, XTYP_EXECUTE, TIMEOUT_ASYNC, LPDWORD())
if not hDdeData:
raise DDEError("Unable to send command", self._idInst)
DDE.FreeDataHandle(hDdeData)
|
Request data from DDE service.
def request(self, item, timeout=5000):
"""Request data from DDE service."""
hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE)
#hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_REQUEST, timeout, LPDWORD())
pdwResult = DWORD(0)
hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_REQUEST, timeout, byref(pdwResult))
DDE.FreeStringHandle(self._idInst, hszItem)
if not hDdeData:
raise DDEError("Unable to request item", self._idInst)
if timeout != TIMEOUT_ASYNC:
pdwSize = DWORD(0)
pData = DDE.AccessData(hDdeData, byref(pdwSize))
if not pData:
DDE.FreeDataHandle(hDdeData)
raise DDEError("Unable to access data in request function", self._idInst)
DDE.UnaccessData(hDdeData)
else:
pData = None
DDE.FreeDataHandle(hDdeData)
return pData
|
DdeCallback callback function for processing Dynamic Data Exchange (DDE)
transactions sent by DDEML in response to DDE events
Parameters
----------
wType : transaction type (UINT)
uFmt : clipboard data format (UINT)
hConv : handle to conversation (HCONV)
hsz1 : handle to string (HSZ)
hsz2 : handle to string (HSZ)
hDDedata : handle to global memory object (HDDEDATA)
dwData1 : transaction-specific data (DWORD)
dwData2 : transaction-specific data (DWORD)
Returns
-------
ret : specific to the type of transaction (HDDEDATA)
def _callback(self, wType, uFmt, hConv, hsz1, hsz2, hDdeData, dwData1, dwData2):
"""DdeCallback callback function for processing Dynamic Data Exchange (DDE)
transactions sent by DDEML in response to DDE events
Parameters
----------
wType : transaction type (UINT)
uFmt : clipboard data format (UINT)
hConv : handle to conversation (HCONV)
hsz1 : handle to string (HSZ)
hsz2 : handle to string (HSZ)
hDDedata : handle to global memory object (HDDEDATA)
dwData1 : transaction-specific data (DWORD)
dwData2 : transaction-specific data (DWORD)
Returns
-------
ret : specific to the type of transaction (HDDEDATA)
"""
if wType == XTYP_ADVDATA: # value of the data item has changed [hsz1 = topic; hsz2 = item; hDdeData = data]
dwSize = DWORD(0)
pData = DDE.AccessData(hDdeData, byref(dwSize))
if pData:
item = create_string_buffer('\000' * 128)
DDE.QueryString(self._idInst, hsz2, item, 128, CP_WINANSI)
self.callback(pData, item.value)
DDE.UnaccessData(hDdeData)
return DDE_FACK
else:
print("Error: AccessData returned NULL! (err = %s)"% (hex(DDE.GetLastError(self._idInst))))
if wType == XTYP_DISCONNECT:
print("Disconnect notification received from server")
return 0
|
:param data_in: path to submission.yaml
:param args:
:param kwargs:
:raise ValueError:
def parse(self, data_in, *args, **kwargs):
"""
:param data_in: path to submission.yaml
:param args:
:param kwargs:
:raise ValueError:
"""
if not os.path.exists(data_in):
raise ValueError("File / Directory does not exist: %s" % data_in)
if os.path.isdir(data_in):
submission_filepath = os.path.join(data_in, 'submission.yaml')
if not os.path.exists(submission_filepath):
submission_filepath = os.path.join(data_in, 'submission.yml')
if not os.path.exists(submission_filepath):
raise ValueError("No submission file in %s" % data_in)
data_in = submission_filepath
# first validate submission file:
with open(data_in, 'r') as submission_file:
submission_data = list(yaml.load_all(submission_file, Loader=Loader))
if len(submission_data) == 0:
raise RuntimeError("Submission file (%s) is empty" % data_in)
submission_file_validator = SubmissionFileValidator()
if not submission_file_validator.validate(file_path=data_in,
data=submission_data):
raise RuntimeError(
"Submission file (%s) did not pass validation: %s" %
(data_in, self._pretty_print_errors(
submission_file_validator.get_messages())))
metadata = {}
tables = []
# validator for table data
data_file_validator = DataFileValidator()
index = 0
for i in range(0, len(submission_data)):
if not submission_data[i]: # empty YAML document
continue
if 'data_file' not in submission_data[i]:
metadata = submission_data[i] # information about whole submission
continue
table_filepath = os.path.join(os.path.dirname(data_in),
submission_data[i]['data_file'])
with open(table_filepath, 'r') as table_file:
if not os.path.exists(table_filepath):
raise ValueError(
"table file: %s does not exist" % table.data_file)
table_data = yaml.load(table_file, Loader=Loader)
if not data_file_validator.validate(data=table_data,
file_path=table_filepath):
raise RuntimeError(
"Data file (%s) did not pass validation: %s" %
(table_filepath, self._pretty_print_errors(
data_file_validator.get_messages())))
index = index + 1
table = Table(index=index, metadata=submission_data[i],
data=table_data)
tables.append(table)
return ParsedData(metadata, tables)
|
generate_ai_request
:param predict_rows: list of predict rows to build into the request
:param req_dict: request dictionary to update - for long-running clients
:param req_file: file holding a request dict to update - one-off tests
:param features: features to process in the data
:param ignore_features: features to ignore in the data (non-numerics)
:param sort_values: optional - order rows for scaler normalization
:param ml_type: machine learning type - classification/regression
:param use_model_name: use a pre-trained model by name
:param predict_feature: predict the values of this feature
:param seed: seed for randomness reproducability
:param test_size: split train/test data
:param batch_size: batch size for processing
:param epochs: test epochs
:param num_splits: test splits for cross validation
:param loss: loss function
:param optimizer: optimizer
:param metrics: metrics to apply
:param histories: historical values to test
:param filter_features_dict: dictionary of features to use
:param filter_features: list of features to use
:param convert_to_type: convert predict_row values to scaler-ready values
:param include_failed_conversions: should the predict rows include fails
:param value_for_missing: set this value to any columns that are missing
:param version: version of the API request
:param publish_to_core: want to publish it to the core or the worker
:param debug: log debug messages
def generate_ai_request(
predict_rows,
req_dict=None,
req_file=ANTINEX_PUBLISH_REQUEST_FILE,
features=ANTINEX_FEATURES_TO_PROCESS,
ignore_features=ANTINEX_IGNORE_FEATURES,
sort_values=ANTINEX_SORT_VALUES,
ml_type=ANTINEX_ML_TYPE,
use_model_name=ANTINEX_USE_MODEL_NAME,
predict_feature=ANTINEX_PREDICT_FEATURE,
seed=ANTINEX_SEED,
test_size=ANTINEX_TEST_SIZE,
batch_size=ANTINEX_BATCH_SIZE,
epochs=ANTINEX_EPOCHS,
num_splits=ANTINEX_NUM_SPLITS,
loss=ANTINEX_LOSS,
optimizer=ANTINEX_OPTIMIZER,
metrics=ANTINEX_METRICS,
histories=ANTINEX_HISTORIES,
filter_features_dict=FILTER_FEATURES_DICT,
filter_features=FILTER_FEATURES,
convert_enabled=ANTINEX_CONVERT_DATA,
convert_to_type=ANTINEX_CONVERT_DATA_TYPE,
include_failed_conversions=ANTINEX_INCLUDE_FAILED_CONVERSIONS,
value_for_missing=ANTINEX_MISSING_VALUE,
version=ANTINEX_VERSION,
publish_to_core=ANTINEX_PUBLISH_TO_CORE,
check_missing_predict_feature=ANTINEX_CHECK_MISSING_PREDICT,
debug=ANTINEX_CLIENT_DEBUG):
"""generate_ai_request
:param predict_rows: list of predict rows to build into the request
:param req_dict: request dictionary to update - for long-running clients
:param req_file: file holding a request dict to update - one-off tests
:param features: features to process in the data
:param ignore_features: features to ignore in the data (non-numerics)
:param sort_values: optional - order rows for scaler normalization
:param ml_type: machine learning type - classification/regression
:param use_model_name: use a pre-trained model by name
:param predict_feature: predict the values of this feature
:param seed: seed for randomness reproducability
:param test_size: split train/test data
:param batch_size: batch size for processing
:param epochs: test epochs
:param num_splits: test splits for cross validation
:param loss: loss function
:param optimizer: optimizer
:param metrics: metrics to apply
:param histories: historical values to test
:param filter_features_dict: dictionary of features to use
:param filter_features: list of features to use
:param convert_to_type: convert predict_row values to scaler-ready values
:param include_failed_conversions: should the predict rows include fails
:param value_for_missing: set this value to any columns that are missing
:param version: version of the API request
:param publish_to_core: want to publish it to the core or the worker
:param debug: log debug messages
"""
status = NOT_SET
err = "not-set"
data = None
if not ANTINEX_PUBLISH_ENABLED:
log.info(("publish disabled ANTINEX_PUBLISH_ENABLED={}")
.format(
ANTINEX_PUBLISH_ENABLED))
status = DISABLED
err = "disabled"
return {
"status": status,
"error": err,
"data": None}
# stop if not enabled
try:
err = "checking number of predict rows"
if len(predict_rows) == 0:
err = "please provide a list of predict_rows"
log.error(err)
status = FAILED
res = {
"status": status,
"error": err,
"data": None}
return res
# stop if there's no new rows
body = None
if not req_dict:
if os.path.exists(req_file):
with open(req_file, "r") as f:
body = json.loads(f.read())
else:
body = copy.deepcopy(
req_dict)
# end of loading body from requested
if not body:
err = ("failed to load request body "
"req_dict={} req_file={}").format(
req_dict,
req_file)
log.error(err)
status = FAILED
res = {
"status": status,
"error": err,
"data": None}
return res
# if body is empty
err = ("setting values rows={} body={} features={}").format(
len(predict_rows),
body,
filter_features)
if debug:
log.info(err)
use_predict_rows = []
for r in predict_rows:
new_row = {}
for col in r:
cur_value = r[col]
if col in filter_features_dict:
if not cur_value:
cur_value = value_for_missing
if ANTINEX_CONVERT_DATA:
try:
if convert_to_type == "float":
new_row[col] = float(cur_value)
elif convert_to_type == "int":
new_row[col] = int(cur_value)
except Exception as e:
if include_failed_conversions:
new_row[col] = cur_value
else:
log.error(("failed converting {}={} type={}")
.format(
col,
cur_value,
convert_to_type))
# if conversion failed
else:
new_row[col] = cur_value
# if not converting data
# if the column is in the filtered features
# for all columns in the row dictionary
for col in filter_features:
if col not in new_row:
new_row[col] = value_for_missing
# make sure to fill in missing columns with a default
if check_missing_predict_feature:
if predict_feature not in new_row:
new_row[predict_feature] = value_for_missing
use_predict_rows.append(new_row)
# for all predict rows to convert and fileter
err = ("converted rows={} to use_rows={}").format(
len(predict_rows),
len(use_predict_rows))
log.info(err)
body["label"] = use_model_name
body["predict_feature"] = predict_feature
body["predict_rows"] = use_predict_rows
body["publish_to_core"] = publish_to_core
body["seed"] = seed
body["test_size"] = test_size
body["batch_size"] = batch_size
body["epochs"] = epochs
body["num_splits"] = num_splits
body["loss"] = loss
body["optimizer"] = optimizer
body["metrics"] = metrics
body["histories"] = histories
body["ml_type"] = ml_type
if sort_values:
body["sort_values"] = sort_values
if filter_features:
body["features_to_process"] = filter_features
if ignore_features:
body["ignore_features"] = ignore_features
data = body
if debug:
log.info(("req={}")
.format(
ppj(data)))
status = SUCCESS
err = ""
except Exception as e:
log.error(("failed last_step='{}' with ex={}")
.format(
err,
e))
status = ERROR
# end of try/ex
res = {
"status": status,
"error": err,
"data": data}
return res
|
get_ml_job
Get an ``MLJob`` by database id.
def get_ml_job():
"""get_ml_job
Get an ``MLJob`` by database id.
"""
parser = argparse.ArgumentParser(
description=("Python client get AI Job by ID"))
parser.add_argument(
"-u",
help="username",
required=False,
dest="user")
parser.add_argument(
"-p",
help="user password",
required=False,
dest="password")
parser.add_argument(
"-e",
help="user email",
required=False,
dest="email")
parser.add_argument(
"-a",
help="url endpoint with default http://localhost:8010",
required=False,
dest="url")
parser.add_argument(
"-i",
help="User's MLJob.id to look up",
required=False,
dest="job_id")
parser.add_argument(
"-b",
help=(
"optional - path to CA bundle directory for "
"client encryption over HTTP"),
required=False,
dest="ca_dir")
parser.add_argument(
"-c",
help=(
"optional - path to x509 certificate for "
"client encryption over HTTP"),
required=False,
dest="cert_file")
parser.add_argument(
"-k",
help=(
"optional - path to x509 key file for "
"client encryption over HTTP"),
required=False,
dest="key_file")
parser.add_argument(
"-s",
help="silent",
required=False,
dest="silent",
action="store_true")
parser.add_argument(
"-d",
help="debug",
required=False,
dest="debug",
action="store_true")
args = parser.parse_args()
user = ev(
"API_USER",
"user-not-set")
password = ev(
"API_PASSWORD",
"password-not-set")
email = ev(
"API_EMAIL",
"email-not-set")
url = ev(
"API_URL",
"http://localhost:8010")
job_id = ev(
"JOB_ID",
"job_id-not-set")
ca_dir = os.getenv(
"API_CA_BUNDLE_DIR",
None)
cert_file = os.getenv(
"API_CERT_FILE",
None)
key_file = os.getenv(
"API_KEY_FILE",
None)
verbose = bool(str(ev(
"API_VERBOSE",
"true")).lower() == "true")
debug = bool(str(ev(
"API_DEBUG",
"false")).lower() == "true")
if args.user:
user = args.user
if args.password:
password = args.password
if args.email:
email = args.email
if args.url:
url = args.url
if args.job_id:
job_id = args.job_id
if args.ca_dir:
ca_dir = args.ca_dir
if args.cert_file:
cert_file = args.cert_file
if args.key_file:
key_file = args.key_file
if args.silent:
verbose = False
if args.debug:
debug = True
usage = (
"Please run with "
"-u <username> "
"-p <password> "
"-a <AntiNex URL http://localhost:8010> "
"-i <job_id> "
"-b <optional - path to CA bundle directory> "
"-c <optional - path to x509 ssl certificate file> "
"-k <optional - path to x509 ssl key file>")
valid = True
if not user or user == "user-not-set":
log.error("missing user")
valid = False
if not password or password == "password-not-set":
log.error("missing password")
valid = False
if not job_id or job_id == "job_id-not-set":
log.error("missing job_id")
valid = False
else:
try:
job_id = int(job_id)
except Exception as e:
log.error("please use -i <job_id with an integer>")
valid = False
if not valid:
log.error(usage)
sys.exit(1)
if verbose:
log.info((
"creating client user={} url={} job_id={} "
"ca_dir={} cert_file={} key_file={}").format(
user,
url,
job_id,
ca_dir,
cert_file,
key_file))
client = AIClient(
user=user,
email=email,
password=password,
url=url,
ca_dir=ca_dir,
cert_file=cert_file,
key_file=key_file,
verbose=verbose,
debug=debug)
if verbose:
log.info(("loading request in job_id={}")
.format(
job_id))
response = client.get_job_by_id(
job_id=job_id)
if response["status"] == SUCCESS:
if debug:
log.info(("got a job response={}")
.format(
response["data"]))
elif response["status"] == FAILED:
log.error(("job failed with error='{}' with response={}")
.format(
response["error"],
response["data"]))
sys.exit(1)
elif response["status"] == ERROR:
if "missing " in response["error"]:
log.error(("Did not find a job with id={} for user={}")
.format(
job_id,
user))
else:
log.error(("job had an error='{}' with response={}")
.format(
response["error"],
response["data"]))
sys.exit(1)
elif response["status"] == LOGIN_FAILED:
log.error(("job reported user was not able to log in "
"with an error='{}' with response={}")
.format(
response["error"],
response["data"]))
sys.exit(1)
job_data = response["data"]
if len(job_data) == 0:
log.error(("Did not find a job with id={} for user={}")
.format(
job_id,
user))
sys.exit(1)
job_id = job_data.get("id", None)
job_status = job_data.get("status", None)
log.info(("job={}")
.format(
ppj(job_data)))
log.info(("done getting job.id={} status={}")
.format(
job_id,
job_status))
|
Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
Set the amount of comments to
usage:
{% get_molo_comments for object as variable_name %}
{% get_molo_comments for object as variable_name limit amount %}
{% get_molo_comments for object as variable_name limit amount child_limit amount %} # noqa
def get_molo_comments(parser, token):
"""
Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
Set the amount of comments to
usage:
{% get_molo_comments for object as variable_name %}
{% get_molo_comments for object as variable_name limit amount %}
{% get_molo_comments for object as variable_name limit amount child_limit amount %} # noqa
"""
keywords = token.contents.split()
if len(keywords) != 5 and len(keywords) != 7 and len(keywords) != 9:
raise template.TemplateSyntaxError(
"'%s' tag takes exactly 2,4 or 6 arguments" % (keywords[0],))
if keywords[1] != 'for':
raise template.TemplateSyntaxError(
"first argument to '%s' tag must be 'for'" % (keywords[0],))
if keywords[3] != 'as':
raise template.TemplateSyntaxError(
"first argument to '%s' tag must be 'as'" % (keywords[0],))
if len(keywords) > 5 and keywords[5] != 'limit':
raise template.TemplateSyntaxError(
"third argument to '%s' tag must be 'limit'" % (keywords[0],))
if len(keywords) == 7:
return GetMoloCommentsNode(keywords[2], keywords[4], keywords[6])
if len(keywords) > 7 and keywords[7] != 'child_limit':
raise template.TemplateSyntaxError(
"third argument to '%s' tag must be 'child_limit'"
% (keywords[0],))
if len(keywords) > 7:
return GetMoloCommentsNode(keywords[2], keywords[4],
keywords[6], keywords[8])
return GetMoloCommentsNode(keywords[2], keywords[4])
|
Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
usage:
{% get_comments_content_object for form_object as variable_name %}
def get_comments_content_object(parser, token):
"""
Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
usage:
{% get_comments_content_object for form_object as variable_name %}
"""
keywords = token.contents.split()
if len(keywords) != 5:
raise template.TemplateSyntaxError(
"'%s' tag takes exactly 2 arguments" % (keywords[0],))
if keywords[1] != 'for':
raise template.TemplateSyntaxError(
"first argument to '%s' tag must be 'for'" % (keywords[0],))
if keywords[3] != 'as':
raise template.TemplateSyntaxError(
"first argument to '%s' tag must be 'as'" % (keywords[0],))
return GetCommentsContentObject(keywords[2], keywords[4])
|
Flags a comment on GET.
Redirects to whatever is provided in request.REQUEST['next'].
def report(request, comment_id):
"""
Flags a comment on GET.
Redirects to whatever is provided in request.REQUEST['next'].
"""
comment = get_object_or_404(
django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)
if comment.parent is not None:
messages.info(request, _('Reporting comment replies is not allowed.'))
else:
perform_flag(request, comment)
messages.info(request, _('The comment has been reported.'))
next = request.GET.get('next') or comment.get_absolute_url()
return HttpResponseRedirect(next)
|
Allows for posting of a Molo Comment, this allows comments to
be set with the "user_name" as "Anonymous"
def post_molo_comment(request, next=None, using=None):
"""
Allows for posting of a Molo Comment, this allows comments to
be set with the "user_name" as "Anonymous"
"""
data = request.POST.copy()
if 'submit_anonymously' in data:
data['name'] = 'Anonymous'
# replace with our changed POST data
# ensure we always set an email
data['email'] = request.user.email or 'blank@email.com'
request.POST = data
return post_comment(request, next=next, using=next)
|
build_ai_client_from_env
Use environment variables to build a client
:param verbose: verbose logging
:param debug: debug internal client calls
:param ca_dir: optional path to CA bundle dir
:param cert_file: optional path to x509 ssl cert file
:param key_file: optional path to x509 ssl key file
def build_ai_client_from_env(
verbose=ANTINEX_CLIENT_VERBOSE,
debug=ANTINEX_CLIENT_DEBUG,
ca_dir=None,
cert_file=None,
key_file=None):
"""build_ai_client_from_env
Use environment variables to build a client
:param verbose: verbose logging
:param debug: debug internal client calls
:param ca_dir: optional path to CA bundle dir
:param cert_file: optional path to x509 ssl cert file
:param key_file: optional path to x509 ssl key file
"""
if not ANTINEX_PUBLISH_ENABLED:
log.info((
"publish disabled ANTINEX_PUBLISH_ENABLED={}").format(
ANTINEX_PUBLISH_ENABLED))
return None
use_ca_dir = ca_dir
use_cert_file = cert_file
use_key_file = key_file
if ANTINEX_CA_FILE or ANTINEX_KEY_FILE or ANTINEX_CERT_FILE:
use_ca_dir = ANTINEX_CA_FILE
use_cert_file = ANTINEX_CERT_FILE
use_key_file = ANTINEX_KEY_FILE
log.info((
"creating env client user={} url={} "
"ca={} cert={} key={}").format(
ANTINEX_USER,
ANTINEX_URL,
ANTINEX_CA_FILE,
ANTINEX_CERT_FILE,
ANTINEX_KEY_FILE))
else:
log.info((
"creating client user={} url={} "
"ca={} cert={} key={}").format(
ANTINEX_USER,
ANTINEX_URL,
use_ca_dir,
use_cert_file,
use_key_file))
# if secure or dev
return AIClient(
user=ANTINEX_USER,
email=ANTINEX_EMAIL,
password=ANTINEX_PASSWORD,
url=ANTINEX_URL,
ca_dir=use_ca_dir,
cert_file=use_cert_file,
key_file=use_key_file,
verbose=verbose,
debug=debug)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.