Esempio n. 1
0
def check_connector():
    """Check if the connector is properly configured and
    has the required version.
    """
    from mysql.fabric.errors import (
        ConfigurationError
    )

    try:
        import mysql.connector as cpy
        cpy_ver = distutils.version.LooseVersion(cpy.__version__)
        cpy_req = distutils.version.LooseVersion(__cpy_version__)
        if  cpy_ver < cpy_req:
            path = os.path.dirname(cpy.__file__)
            raise ConfigurationError(
                "Connector has version {cpy_ver} but {cpy_req} "
                "(or later) required (looked in {path}).".format(
                    path=path, cpy_ver=cpy_ver, cpy_req=cpy_req
                )
            )
    except ImportError as error:
        import mysql
        path = os.path.dirname(mysql.__file__)
        raise ConfigurationError(
            "Tried to look for mysql.connector at ({path}). Connector not "
            "installed. Error ({error}).".format(path=path, error=error)
        )
Esempio n. 2
0
def search(provider_id, generic_filters, meta_filters, skip_store):
    """Return information on existing machine(s).
    """
    provider = _retrieve_provider(provider_id)

    if not skip_store:
        if generic_filters or meta_filters:
            raise ConfigurationError(
                "Filters are only supported when the 'skip_store' option "
                "is set.")
        machines = Machine.machines(provider.provider_id)
    else:
        generic_filters, meta_filters = \
           _preprocess_filters(generic_filters, meta_filters)
        manager = provider.get_provider_machine()

        if issubclass(manager, AbstractDatabaseManager):
            meta_filters = {}
            manager = _retrieve_database_manager(provider_id)
        elif issubclass(manager, AbstractMachineManager):
            manager = _retrieve_machine_manager(provider_id)

        machines = manager.search(generic_filters, meta_filters)

    rset = ResultSet(names=('uuid', 'provider_id', 'av_zone', 'addresses'),
                     types=(str, str, str, str))

    for machine in machines:
        row = (str(machine.uuid), machine.provider_id, machine.av_zone,
               machine.addresses)
        rset.append_row(row)
    return CommandResult(None, results=rset)
Esempio n. 3
0
def kv_to_dict(meta):
    """Transform a list with key/value strings into a dictionary.
    """
    try:
        return dict(m.split("=", 1) for m in meta)
    except ValueError:
        from mysql.fabric.errors import (ConfigurationError)
        raise ConfigurationError("Invalid parameter (%s)." % (meta, ))
Esempio n. 4
0
def _retrieve_database_manager(provider_id):
    """Retrive machine manager for a provider.
    """
    provider = _retrieve_provider(provider_id)
    DatabaseManager = provider.get_provider_machine()
    if not issubclass(DatabaseManager, AbstractDatabaseManager):
        raise ConfigurationError(
            "Provider (%s) does not allow to manage machine databases "
            "directly." % (provider_id, ))
    return DatabaseManager(provider)
Esempio n. 5
0
def _retrieve_snapshot_manager(provider_id):
    """Retrive snapshot manager for a provider.
    """
    provider = _retrieve_provider(provider_id)
    SnapshotManager = provider.get_provider_snapshot()
    if not issubclass(SnapshotManager, AbstractSnapshotManager):
        raise ConfigurationError(
            "Provider (%s) does not allow to manage machine snapshots "
            "directly." % (provider_id, ))
    return SnapshotManager(provider)
Esempio n. 6
0
def check_connector():
    """Check if the connector is properly configured and
    has the required version.
    """
    from mysql.fabric.errors import (
        ConfigurationError
    )

    try:
        import mysql.connector as cpy
        path = os.path.dirname(cpy.__file__)

        # Whether the connector has support to C-Extensions can be identified
        # by the minor release number. For that reason, we need at least two
        # fields for the version:  [0] - major version and [1] minor version.
        cpy_ver = distutils.version.LooseVersion(cpy.__version__)
        if len(cpy_ver.version) < 2:
            raise ConfigurationError(
                "Connector has version {cpy_ver} that only has a major "
                "number and a minor number is expected as well (looked "
                "in {path}).".format(path=path, cpy_ver=cpy_ver)
            )
        # [1] Minor version 1 means connector with C-Extensions.
        if cpy_ver.version[1] == 1:
            cpy_req = distutils.version.LooseVersion(__cpy_with_c_version__)
        else:
            cpy_req = distutils.version.LooseVersion(__cpy_version__)

        if  cpy_ver < cpy_req:
            raise ConfigurationError(
                "Connector has version {cpy_ver} but {cpy_req} "
                "(or later) required (looked in {path}).".format(
                    path=path, cpy_ver=cpy_ver, cpy_req=cpy_req
                )
            )
    except ImportError as error:
        import mysql
        path = os.path.dirname(mysql.__file__)
        raise ConfigurationError(
            "Tried to look for mysql.connector at ({path}). Connector not "
            "installed. Error ({error}).".format(path=path, error=error)
        )
Esempio n. 7
0
def check_connector():
    """Check if the connector is properly configured and
    has the required version.
    """
    from mysql.fabric.errors import (ConfigurationError)

    try:
        import mysql.connector as cpy
        if cpy.version.VERSION < __cpy_version_info__:
            path = os.path.dirname(cpy.__file__)
            raise ConfigurationError(
                "Looked for mysql.connector at ({path}). Connector has "
                "({cpy_ver}) version but ({required_ver}) or later version "
                "is required.".format(path=path,
                                      cpy_ver=cpy.version.VERSION,
                                      required_ver=__cpy_version_info__))
    except ImportError as error:
        import mysql
        path = os.path.dirname(mysql.__file__)
        raise ConfigurationError(
            "Tried to look for mysql.connector at ({path}). Connector not "
            "installed. Error ({error}).".format(path=path, error=error))
Esempio n. 8
0
def _preprocess_filters(generic_filters, meta_filters):
    """Process filters.
    """
    if generic_filters:
        generic_filters = kv_to_dict(generic_filters)
    else:
        generic_filters = {}

    if meta_filters:
        meta_filters = kv_to_dict(meta_filters)
    else:
        meta_filters = {}

    meta_filters['mysql-fabric'] = 'True'

    if any(key in reserved_meta for key in generic_filters.iterkeys()):
        raise ConfigurationError(
            "Generic filters option cannot have keyords in the following "
            "list: %s." % (str(reserved_meta), ))

    return generic_filters, meta_filters
Esempio n. 9
0
def _preprocess_parameters(parameters, machine_group_uuid, provider):
    """Process paramaters.
    """
    # Check whether all parameters are expected.
    for key, value in parameters.items():
        if key not in VALID_PARAMETERS and (value is not None and value):
            raise MachineError(
                "Parameter (%s) is not in the set of possible parameters: %s.",
                key, VALID_PARAMETERS)
        elif key not in VALID_PARAMETERS:
            del parameters[key]

    # 1. Put image parameter in the appropriate format.
    if parameters['image']:
        parameters['image'] = kv_to_dict(parameters['image'])
    elif provider.default_image:
        parameters['image'] = {'name': provider.default_image}
    if not parameters['image']:
        raise MachineError("No valid image hasn't been found.")

    # 2. Put flavor parameter in the appropriate format.
    if parameters['flavor']:
        parameters['flavor'] = kv_to_dict(parameters['flavor'])
    elif provider.default_flavor:
        parameters['flavor'] = {'name': provider.default_flavor}
    if not parameters['flavor']:
        raise MachineError("No valid flavor hasn't been found.")

    # 3. Check the parameter number_machines.
    number_machines = parameters['number_machines']
    try:
        number_machines = int(number_machines)
        parameters['number_machines'] = number_machines
    except TypeError:
        number_machines = 1
        parameters['number_machines'] = number_machines
    if number_machines <= 0:
        raise MachineError(
            "Number of machines must be greater than zero (%s)." %
            (number_machines, ))

    # 4. We don't need to check the availability_zone parameter

    # 5. We don't need to check the parameter key_name parameter.

    # 6. Put the security_groups parameter in the appropriate format.
    if parameters['security_groups']:
        security_groups = parameters['security_groups'].split(',')
        parameters['security_groups'] = security_groups

    # 7. Check the private_newtwork parameter.
    private_nics = parameters['private_nics']
    private_network = parameters['private_network']
    if private_network and private_nics:
        raise ConfigurationError(
            "Can't define both private_network (%s) and private_nics "
            "parameters (%s)." % (private_network, private_nics))

    # 8. Check the public_newtwork parameter.
    public_nics = parameters['public_nics']
    public_network = parameters['public_network']
    if public_network and public_nics:
        raise ConfigurationError(
            "Can't define both public_network (%s) and public_nics "
            "parameters (%s)." % (public_network, public_nics))

    # 9. Read userdata parameter which must be a path to a file.
    if parameters['userdata']:
        try:
            src = parameters['userdata']
            userdata = open(src)
        except IOError as error:
            raise ConfigurationError("Can't open '%(src)s': %(exc)s" % {
                'src': src,
                'exc': error
            })
        parameters['userdata'] = userdata

    # 10. We don't need to check the swap parameter

    # 11. Put the block_device parameter in the appropriate format.
    if parameters['block_device']:
        raise ConfigurationError(
            "Parameter block_device is not supported yet.")

    # 12. Put the scheduler_hints parameter in the appropriate format.
    if parameters['scheduler_hints']:
        parameters['scheduler_hints'] = \
            kv_to_dict(parameters['scheduler_hints'])

    # 13. Put the private_nics parameter in the appropriate format.
    if parameters['private_nics']:
        raise ConfigurationError(
            "Parameter private_nics is not supported yet.")

    # 14. Put the public_nics parameter in the appropriate format.
    if parameters['public_nics']:
        raise ConfigurationError("Parameter public_nics is not supported yet.")

    # 15. Put meta parameter in the appropriate format.
    reserved_value = ('True',
                      str(FabricNode().version), str(FabricNode().uuid),
                      str(FabricNode().group_uuid), machine_group_uuid)
    assert len(reserved_meta) == len(reserved_value)
    if parameters['meta']:
        parameters['meta'] = kv_to_dict(parameters['meta'])
        if any(key in reserved_meta for key in parameters['meta'].iterkeys()):
            raise ConfigurationError(
                "The meta parameter cannot have keywords in the following "
                "list: %s. They are reserved for internal use." %
                (str(reserved_meta), ))
    else:
        parameters['meta'] = {}

    meta = dict(zip(reserved_meta, reserved_value))
    parameters['meta'].update(meta)