From fcd3c33ed84718659845275105f083145531ac98 Mon Sep 17 00:00:00 2001 From: Michael Hierweck Date: Fri, 25 Mar 2016 20:03:38 +0100 Subject: [PATCH] Initial release. --- .gitignore | 11 ++ CHANGES.txt | 8 ++ CONTRIBUTORS.txt | 1 + README.txt | 20 +++ docs/LICENSE.LGPL | 165 +++++++++++++++++++++++ docs/LICENSE.txt | 15 +++ setup.py | 44 ++++++ src/hs/__init__.py | 4 + src/hs/admin/__init__.py | 4 + src/hs/admin/play/__init__.py | 4 + src/hs/admin/play/exceptions.py | 28 ++++ src/hs/admin/play/module.py | 229 ++++++++++++++++++++++++++++++++ 12 files changed, 533 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGES.txt create mode 100644 CONTRIBUTORS.txt create mode 100644 README.txt create mode 100644 docs/LICENSE.LGPL create mode 100644 docs/LICENSE.txt create mode 100644 setup.py create mode 100644 src/hs/__init__.py create mode 100644 src/hs/admin/__init__.py create mode 100644 src/hs/admin/play/__init__.py create mode 100644 src/hs/admin/play/exceptions.py create mode 100644 src/hs/admin/play/module.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..878619b --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*.py[co] + +# Packages +*.egg +*.egg-info +*.tar.gz +dist +build +sdist +bdist +deb_dist diff --git a/CHANGES.txt b/CHANGES.txt new file mode 100644 index 0000000..0bd24f5 --- /dev/null +++ b/CHANGES.txt @@ -0,0 +1,8 @@ +Changelog +========= + +0.1 +--- + +- Initial release. + [Michael Hierweck , Hostsharing eG] diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt new file mode 100644 index 0000000..d56decd --- /dev/null +++ b/CONTRIBUTORS.txt @@ -0,0 +1 @@ +Michael Hierweck , Hostsharing eG. diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..5dda790 --- /dev/null +++ b/README.txt @@ -0,0 +1,20 @@ +Introduction +============ + +This package provides a generic interface between Ansible and the Hostsharing HSAdmin API package. + +Example +------- + +Please note that the ids argument will be removed from the Module class constructor +as soon as this information is provided by the backends theirselves. + +In real world uses the argsfile will be populated by Ansible. + +>>> from hs.admin.play import Module +>>> +>>> module = Module(module='emailaddress', +... ids=['localpart', 'subdomain', 'domain'], +... argsfile='/tmp/argsfile') +>>> +>>> module() diff --git a/docs/LICENSE.LGPL b/docs/LICENSE.LGPL new file mode 100644 index 0000000..65c5ca8 --- /dev/null +++ b/docs/LICENSE.LGPL @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/docs/LICENSE.txt b/docs/LICENSE.txt new file mode 100644 index 0000000..ce0e938 --- /dev/null +++ b/docs/LICENSE.txt @@ -0,0 +1,15 @@ +hs.admin.play Copyright 2015, Hostsharing eG + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA. diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..c0c446d --- /dev/null +++ b/setup.py @@ -0,0 +1,44 @@ +from setuptools import setup, find_packages +import os + +version = '0.1' + +long_description = ( + open('README.txt').read() + + '\n' + + 'Contributors\n' + '============\n' + + '\n' + + open('CONTRIBUTORS.txt').read() + + '\n' + + open('CHANGES.txt').read() + + '\n') + +setup(name='hs.admin.play', + version=version, + description="Hostsharing HSAdmin Play", + long_description=long_description, + # Get more strings from + # http://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + "Programming Language :: Python", + ], + keywords='Hostsharing HSAdmin Play', + author='Hostsharing eG', + author_email='info@hostsharing.net', + url='https://www.hostsharing.net', + license='lgpl', + packages=find_packages('src'), + package_dir = {'': 'src'}, + namespace_packages=['hs', 'hs.admin'], + include_package_data=True, + zip_safe=False, + install_requires=[ + 'setuptools', + 'hs.admin.api', + # -*- Extra requirements: -*- + ], + entry_points=""" + # -*- Entry points: -*- + """, + ) diff --git a/src/hs/__init__.py b/src/hs/__init__.py new file mode 100644 index 0000000..45871cd --- /dev/null +++ b/src/hs/__init__.py @@ -0,0 +1,4 @@ +""" hs namespace package +""" + +__import__('pkg_resources').declare_namespace(__name__) diff --git a/src/hs/admin/__init__.py b/src/hs/admin/__init__.py new file mode 100644 index 0000000..1b67390 --- /dev/null +++ b/src/hs/admin/__init__.py @@ -0,0 +1,4 @@ +""" hs.admin namespace package +""" + +__import__('pkg_resources').declare_namespace(__name__) diff --git a/src/hs/admin/play/__init__.py b/src/hs/admin/play/__init__.py new file mode 100644 index 0000000..896577c --- /dev/null +++ b/src/hs/admin/play/__init__.py @@ -0,0 +1,4 @@ +""" hs.admin.play namespace package +""" + +from .module import Module diff --git a/src/hs/admin/play/exceptions.py b/src/hs/admin/play/exceptions.py new file mode 100644 index 0000000..f417b2d --- /dev/null +++ b/src/hs/admin/play/exceptions.py @@ -0,0 +1,28 @@ +""" This module provides exception classes. +""" + + + +class MissingArgumentError(Exception): + """ Raised when a mandatory argument is missing. + """ + + +class InvalidArgumentError(Exception): + """ Raised when an argument has an invalid type or structure. + """ + + +class APIInitializationError(Exception): + """ Raised when the HSAdmin API initialization failed. + """ + + +class APIInvokationError(Exception): + """ Raised when an HSAdmin API invokation failed. + """ + + +class AmbiguousResultsError(Exception): + """ Raised when ambiguous results were retrieved. + """ diff --git a/src/hs/admin/play/module.py b/src/hs/admin/play/module.py new file mode 100644 index 0000000..493ab2a --- /dev/null +++ b/src/hs/admin/play/module.py @@ -0,0 +1,229 @@ +""" This module provides a class that implements a generic Ansible module againt the HSAdmin API. +""" + +from shlex import split +from ast import literal_eval +from json import dumps + +from hs.admin.api import API + +from .exceptions import MissingArgumentError, InvalidArgumentError +from .exceptions import APIInitializationError, APIInvokationError +from .exceptions import AmbiguousResultsError + + + +class Module(object): + """ This class implements a generic Ansible module againt the HSAdmin API. + """ + + def __init__(self, module, ids, argsfile): + + def parse_argsfile(argsfile): + """ Returns parsed params provided by argsfile """ + + args = split(file(argsfile).read()) + params = dict() + for arg in args: + + if '=' in arg: + key, value = arg.split('=', 1) + try: + params[key] = literal_eval(value) + except (SyntaxError, TypeError, ValueError,): + params[key] = value + else: + params[arg] = None + return params + + + def check_hsadmin_param(hsadmin): + """ Checks whether the hsadmin parameter has a valid structure """ + + if not isinstance(hsadmin, dict): + return False + + if not (hsadmin.has_key('cas') and + isinstance(hsadmin['cas'], dict)): + return False + else: + cas = hsadmin['cas'] + if not (isinstance(cas, dict) and + cas.has_key('uri') and + isinstance(cas['uri'], basestring) and + cas.has_key('service') and + isinstance(cas['service'], basestring)): + return False + + if not hsadmin.has_key('credentials'): + return False + else: + credentials = hsadmin['credentials'] + if not (isinstance(credentials, dict) and + credentials.has_key('username') and + isinstance(credentials['username'], basestring) and + credentials.has_key('password') and + isinstance(credentials['password'], basestring)): + return False + + if not hsadmin.has_key('backends'): + return False + else: + backends = hsadmin['backends'] + if not isinstance(backends, list) or (len(backends) == 0): + return False + for backend in backends: + if not isinstance(backend, basestring): + return False + + return True + + + params = parse_argsfile(argsfile) + + if not params.has_key('hsadmin'): + raise MissingArgumentError('Module argument "hsadmin" is missing.') + + hsadmin = params['hsadmin'] + del params['hsadmin'] + + if not check_hsadmin_param(hsadmin): + raise InvalidArgumentError('Module argument "hsadmin" is invalid.') + + try: + api = API(**hsadmin) + except Exception as exception: + raise APIInitializationError('HSAdmin API initialization failed: ' + exception.message) + + if not api.modules.has_key(module): + raise NotImplementedError('HSAdmin API does not implement the module: ' + module) + + if params.has_key('state'): + state = params['state'] + del params['state'] + if not state in ('present', 'absent'): + raise InvalidArgumentError('Module argument "state" is invalid.') + else: + state = 'present' + + # Patch module properties to provide information + # about the property being part of the unique identifier + # until that information is provided by the backends theirselves + for key, value in api.modules[module].properties.iteritems(): + value['id'] = (key in ids) + + self.module = api.modules[module] + self.params = params + self.state = state + + + def __call__(self): + + def build_where_params(module, params): + """ Returns where data structure """ + + ids = list() + for key, value in module.properties.iteritems(): + if value.has_key('id') and value['id']: + ids.append(key) + + where_params = dict() + for key in ids: + if not params.has_key(key): + raise MissingArgumentError('Module argument "%s" is missing.' % key) + where_params[key] = self.params[key] + + return where_params + + + def build_set_params(module, current, params): + """ Returns where data structure """ + + set_params = dict() + for key, value in params.iteritems(): + if not module.properties.has_key(key): + raise InvalidArgumentError('Module argument "%s" is invalid.' % key) + if not current.has_key(key) or (current[key] != value): + set_params[key] = value + + return set_params + + + def retrieve(module, params): + """ Returns record if found """ + + where = build_where_params(module, params) + + try: + results = module.search(where=where) + except Exception as exception: + raise APIInvokationError('HSAdmin API invokation failed: ' + exception.message) + + if len(results) > 1: + raise AmbiguousResultsError('Retrieved ambiguous results.') + + if len(results) == 1: + return results[0] + else: + return None + + + def add(module, params): + """ Adds record """ + + set_params = build_set_params(module, dict(), params) + + try: + module.add(set=set_params) + except Exception as exception: + raise APIInvokationError('HSAdmin API invokation failed: ' + exception.message) + + return True + + + def update(module, current, params): + """ Updates record if modified """ + + set_params = build_set_params(module, current, params) + if len(set_params) > 0: + where_params = build_where_params(module, params) + + try: + module.update(where=where_params, set=set_params) + except Exception as exception: + raise APIInvokationError('HSAdmin API invokation failed: ' + exception.message) + + return True + else: + return False + + + def delete(module, params): + """ Deletes record """ + + where_params = build_where_params(module, params) + + try: + module.delete(where=where_params) + except Exception as exception: + raise APIInvokationError('HSAdmin API invokation failed: ' + exception.message) + + return True + + + module = self.module + params = self.params + state = self.state + + changed = False + + retrieved = retrieve(module, params) + + if (state == 'present') and not retrieved: + changed = add(module, params) + if (state == 'present') and retrieved: + changed = update(module, retrieved, params) + if (state == 'absent') and retrieved: + changed = delete(module, params) + + print dumps({'changed': changed})