Exemplo n.º 1
0
def show_server_info(servers, options):
    """Show server information for a list of servers

    This method will gather information about a running server. If the
    show_defaults option is specified, the method will also read the
    configuration file and return a list of the server default settings.

    If the format option is set, the output will be in the format specified.

    If the no_headers option is set, the output will not have a header row (no
    column names) except for format = vertical.

    If the basedir and start options are set, the method will attempt to start
    the server in read only mode to get the information. Specifying only
    basedir will not start the server. The extra start option is designed to
    make sure the user wants to start the offline server. The user may not wish
    to do this if there are certain error conditions and/or logs in place that
    may be overwritten.

    servers[in]       list of server connections in the form
                      <user>:<password>@<host>:<port>:<socket>
    options[in]       dictionary of options (no_headers, format, basedir,
                      start, show_defaults)

    Returns tuple ((server information), defaults)
    """
    no_headers = options.get("no_headers", False)
    fmt = options.get("format", "grid")
    show_defaults = options.get("show_defaults", False)
    basedir = options.get("basedir", None)
    datadir = options.get("datadir", None)
    start = options.get("start", False)
    show_servers = options.get("show_servers", 0)

    if show_servers:
        if os.name == 'nt':
            ports = options.get("ports", "3306:3333")
            start_p, end_p = ports.split(":")
            _show_running_servers(start_p, end_p)
        else:
            _show_running_servers()

    row_dict_lst = []
    warnings = []
    server_val = {}
    for server in servers:
        new_server = None
        try:
            test_connect(server, True)
        except UtilError as util_error:
            conn_dict = get_connection_dictionary(server)
            server1 = Server(options={'conn_info': conn_dict})
            server_is_off = False
            # If we got errno 2002 it means can not connect through the
            # given socket, but if path to socket not empty, server could be
            # turned off.
            if util_error.errno == CR_CONNECTION_ERROR:
                socket = conn_dict.get("unix_socket", "")
                if socket:
                    mydir = os.path.split(socket)[0]
                    if os.path.isdir(mydir) and len(os.listdir(mydir)) != 0:
                        server_is_off = True
            # If we got errno 2003 and this is a windows, we do not have
            # socket, instead we check if server is localhost.
            elif (util_error.errno == CR_CONN_HOST_ERROR and
                  os.name == 'nt' and server1.is_alias("localhost")):
                server_is_off = True
            # If we got errno 1045 it means Access denied,
            # notify the user if a password was used or not.
            elif util_error.errno == ER_ACCESS_DENIED_ERROR:
                use_pass = '******' if conn_dict['passwd'] else 'NO'
                er = ("Access denied for user '{0}'@'{1}' using password: {2}"
                      ).format(conn_dict['user'], conn_dict['host'], use_pass)
            # Use the error message from the connection attempt.
            else:
                er = [util_error.errmsg]
            # To propose to start a cloned server for extract the info,
            # can not predict if the server is really off, but we can do it
            # in case of socket error, or if one of the related
            # parameter was given.
            if (server_is_off or basedir or datadir or start):
                er = ["Server is offline. To connect, "
                      "you must also provide "]

                opts = ["basedir", "datadir", "start"]
                for opt in tuple(opts):
                    try:
                        if locals()[opt] is not None:
                            opts.remove(opt)
                    except KeyError:
                        pass
                if opts:
                    er.append(", ".join(opts[0:-1]))
                    if len(opts) > 1:
                        er.append(" and the ")
                    er.append(opts[-1])
                    er.append(" option")
                    raise UtilError("".join(er))

            if not start:
                raise UtilError("".join(er))
            else:
                try:
                    server_val = parse_connection(server, None, options)
                except:
                    raise UtilError("Source connection values invalid"
                                    " or cannot be parsed.")
                new_server = _start_server(server_val, basedir,
                                           datadir, options)
        info_dict, defaults = _server_info(server, show_defaults, options)
        warnings.extend(info_dict['warnings'])
        if info_dict:
            row_dict_lst.append(info_dict)
        if new_server:
            # Need to stop the server!
            new_server.disconnect()
            _stop_server(server_val, basedir, options)

    # Get the row values stored in the dictionaries
    rows = [[row_dict[key] for key in _COLUMNS] for row_dict in row_dict_lst]

    print_list(sys.stdout, fmt, _COLUMNS, rows, no_headers)
    if warnings:
        print("\n# List of Warnings: \n")
        for warning in warnings:
            print("WARNING: {0}\n".format(warning))

    # Print the default configurations.
    if show_defaults and len(defaults) > 0:
        for row in defaults:
            print("  {0}".format(row))
Exemplo n.º 2
0
def show_server_info(servers, options):
    """Show server information for a list of servers
    
    This method will gather information about a running server. If the
    show_defaults option is specified, the method will also read the
    configuration file and return a list of the server default settings.
    
    If the format option is set, the output will be in the format specified.
    
    If the no_headers option is set, the output will not have a header row (no
    column names) except for format = vertical.
    
    If the basedir and start options are set, the method will attempt to start
    the server in read only mode to get the information. Specifying only
    basedir will not start the server. The extra start option is designed to
    make sure the user wants to start the offline server. The user may not wish
    to do this if there are certain error conditions and/or logs in place that
    may be overwritten.
    
    servers[in]       list of server connections in the form
                      <user>:<password>@<host>:<port>:<socket>
    options[in]       dictionary of options (no_headers, format, basedir,
                      start, show_defaults)
    
    Returns tuple ((server information), defaults) 
    """
    from mysql.utilities.common.server import test_connect
    from mysql.utilities.common.format import print_list
    
    no_headers = options.get("no_headers", False)
    format = options.get("format", "grid")
    show_defaults = options.get("show_defaults", False)
    basedir = options.get("basedir", None)
    datadir = options.get("datadir", None)
    start = options.get("start", False)
    verbosity = options.get("verbosity", 0)
    show_servers = options.get("show_servers", 0)
    
    if show_servers:
        if os.name == 'nt':
            ports = options.get("ports", "3306:3333")
            start, end = ports.split(":")
            _show_running_servers(start, end)
        else:
            _show_running_servers()

    defaults_rows = []
    rows = []
    server_val = {}
    get_defaults = True
    for server in servers:
        server_alive = True
        server_started = False
        if not test_connect(server):
            if basedir is None or datadir is None:
                raise UtilError("Server is offline. To connection, "
                                     "you must provide basedir, datadir, "
                                     "and the start option")
            else:
                if start:
                    try:
                        server_val = parse_connection(server)
                    except:
                        raise UtilError("Source connection values in"
                                             "valid or cannot be parsed.")
                    res = _start_server(server_val, basedir, datadir, options)
                    server_started = True                    
                else:
                    server_alive = False
        if server_alive:
            info, defaults = _server_info(server, get_defaults, options)
            if info is not None:
                rows.append(info)
            if defaults is not None and len(defaults_rows) == 0:
                defaults_rows = defaults
                get_defaults = False
        if server_started:
            # Need to stop the server!
            res = _stop_server(server_val, basedir, options)

    print_list(sys.stdout, format, _COLUMNS, rows, no_headers)

    if show_defaults and len(defaults_rows) > 0:
        for row in defaults_rows:
            print "  %s" % row
Exemplo n.º 3
0
def show_server_info(servers, options):
    """Show server information for a list of servers

    This method will gather information about a running server. If the
    show_defaults option is specified, the method will also read the
    configuration file and return a list of the server default settings.

    If the format option is set, the output will be in the format specified.

    If the no_headers option is set, the output will not have a header row (no
    column names) except for format = vertical.

    If the basedir and start options are set, the method will attempt to start
    the server in read only mode to get the information. Specifying only
    basedir will not start the server. The extra start option is designed to
    make sure the user wants to start the offline server. The user may not wish
    to do this if there are certain error conditions and/or logs in place that
    may be overwritten.

    servers[in]       list of server connections in the form
                      <user>:<password>@<host>:<port>:<socket>
    options[in]       dictionary of options (no_headers, format, basedir,
                      start, show_defaults)

    Returns tuple ((server information), defaults)
    """
    no_headers = options.get("no_headers", False)
    fmt = options.get("format", "grid")
    show_defaults = options.get("show_defaults", False)
    basedir = options.get("basedir", None)
    datadir = options.get("datadir", None)
    start = options.get("start", False)
    show_servers = options.get("show_servers", 0)

    if show_servers:
        if os.name == 'nt':
            ports = options.get("ports", "3306:3333")
            start_p, end_p = ports.split(":")
            _show_running_servers(start_p, end_p)
        else:
            _show_running_servers()

    ssl_dict = {}
    ssl_dict['ssl_cert'] = options.get("ssl_cert", None)
    ssl_dict['ssl_ca'] = options.get("ssl_ca", None)
    ssl_dict['ssl_key'] = options.get("ssl_key", None)
    ssl_dict['ssl'] = options.get("ssl", None)

    row_dict_lst = []
    warnings = []
    server_val = {}
    for server in servers:
        new_server = None
        try:
            test_connect(server, throw_errors=True, ssl_dict=ssl_dict)
        except UtilError as util_error:
            conn_dict = get_connection_dictionary(server, ssl_dict=ssl_dict)
            server1 = Server(options={'conn_info': conn_dict})
            server_is_off = False
            # If we got errno 2002 it means can not connect through the
            # given socket.
            if util_error.errno == CR_CONNECTION_ERROR:
                socket = conn_dict.get("unix_socket", "")
                if socket:
                    msg = ("Unable to connect to server using socket "
                           "'{0}'.".format(socket))
                    if os.path.isfile(socket):
                        err_msg = ["{0} Socket file is not valid.".format(msg)]
                    else:
                        err_msg = [
                            "{0} Socket file does not "
                            "exist.".format(msg)
                        ]
            # If we got errno 2003 and we do not have
            # socket, instead we check if server is localhost.
            elif (util_error.errno == CR_CONN_HOST_ERROR
                  and server1.is_alias("localhost")):
                server_is_off = True
            # If we got errno 1045 it means Access denied,
            # notify the user if a password was used or not.
            elif util_error.errno == ER_ACCESS_DENIED_ERROR:
                use_pass = '******' if conn_dict['passwd'] else 'NO'
                err_msg = ("Access denied for user '{0}'@'{1}' using "
                           "password: {2}".format(conn_dict['user'],
                                                  conn_dict['host'], use_pass))
            # Use the error message from the connection attempt.
            else:
                err_msg = [util_error.errmsg]
            # To propose to start a cloned server for extract the info,
            # can not predict if the server is really off, but we can do it
            # in case of socket error, or if one of the related
            # parameter was given.
            if server_is_off or basedir or datadir or start:
                err_msg = [
                    "Server is offline. To connect, "
                    "you must also provide "
                ]

                opts = ["basedir", "datadir", "start"]
                for opt in tuple(opts):
                    try:
                        if locals()[opt] is not None:
                            opts.remove(opt)
                    except KeyError:
                        pass
                if opts:
                    err_msg.append(", ".join(opts[0:-1]))
                    if len(opts) > 1:
                        err_msg.append(" and the ")
                    err_msg.append(opts[-1])
                    err_msg.append(" option")
                    raise UtilError("".join(err_msg))

            if not start:
                raise UtilError("".join(err_msg))
            else:
                try:
                    server_val = parse_connection(server, None, options)
                except:
                    raise UtilError("Source connection values invalid"
                                    " or cannot be parsed.")
                new_server = _start_server(server_val, basedir, datadir,
                                           options)
        info_dict, defaults = _server_info(server, show_defaults, options)
        warnings.extend(info_dict['warnings'])
        if info_dict:
            row_dict_lst.append(info_dict)
        if new_server:
            # Need to stop the server!
            new_server.disconnect()
            _stop_server(server_val, basedir, options)

    # Get the row values stored in the dictionaries
    rows = [[row_dict[key] for key in _COLUMNS] for row_dict in row_dict_lst]

    print_list(sys.stdout, fmt, _COLUMNS, rows, no_headers)
    if warnings:
        print("\n# List of Warnings: \n")
        for warning in warnings:
            print("WARNING: {0}\n".format(warning))

    # Print the default configurations.
    if show_defaults and len(defaults) > 0:
        for row in defaults:
            print("  {0}".format(row))
Exemplo n.º 4
0
def show_server_info(servers, options):
    """Show server information for a list of servers
    
    This method will gather information about a running server. If the
    show_defaults option is specified, the method will also read the
    configuration file and return a list of the server default settings.
    
    If the format option is set, the output will be in the format specified.
    
    If the no_headers option is set, the output will not have a header row (no
    column names) except for format = vertical.
    
    If the basedir and start options are set, the method will attempt to start
    the server in read only mode to get the information. Specifying only
    basedir will not start the server. The extra start option is designed to
    make sure the user wants to start the offline server. The user may not wish
    to do this if there are certain error conditions and/or logs in place that
    may be overwritten.
    
    servers[in]       list of server connections in the form
                      <user>:<password>@<host>:<port>:<socket>
    options[in]       dictionary of options (no_headers, format, basedir,
                      start, show_defaults)
    
    Returns tuple ((server information), defaults) 
    """
    from mysql.utilities.common.server import test_connect
    from mysql.utilities.common.format import print_list
    
    no_headers = options.get("no_headers", False)
    format = options.get("format", "grid")
    show_defaults = options.get("show_defaults", False)
    basedir = options.get("basedir", None)
    datadir = options.get("datadir", None)
    start = options.get("start", False)
    verbosity = options.get("verbosity", 0)
    show_servers = options.get("show_servers", 0)
    
    if show_servers:
        if os.name == 'nt':
            ports = options.get("ports", "3306:3333")
            start, end = ports.split(":")
            _show_running_servers(start, end)
        else:
            _show_running_servers()

    defaults_rows = []
    rows = []
    server_val = {}
    get_defaults = True
    for server in servers:
        new_server = None
        try:
            test_connect(server, True)
        except UtilError as util_error:
            if util_error.errmsg.startswith("Server connection values invalid:"):
                raise util_error
            # If we got an exception it may means that the server is offline
            # in that case we will try to turn a clone to extract the info
            # if the user passed the necessary parameters.
            pattern = ".*?: (.*?)\((.*)\)"
            res = re.match(pattern, util_error.errmsg, re.S)
            if not res:
                er = ["error: <%s>" % util_error.errmsg]
            else:
                er = res.groups()

            if (re.search("refused", "".join(er)) or 
                re.search("Can't connect to local MySQL server through socket",
                           "".join(er))):
                er = ["Server is offline. To connect, "
                      "you must also provide "]
            
                opts = ["basedir", "datadir", "start"]
                for opt in tuple(opts):
                    try:
                        if locals()[opt] is not None:
                            opts.remove(opt)
                    except KeyError:
                        pass
                if opts:
                    er.append(", ".join(opts[0:-1]))
                    if len(opts) > 1:
                        er.append(" and the ")
                    er.append(opts[-1])
                    er.append(" option")
                    raise UtilError("".join(er))

            if not start:
                raise UtilError("".join(er))
            else:    
                try:
                    server_val = parse_connection(server, None, options)
                except:
                    raise UtilError("Source connection values invalid"
                                    " or cannot be parsed.")
                new_server = _start_server(server_val, basedir,
                                           datadir, options)

        info, defaults = _server_info(server, get_defaults, options)
        if info:
            rows.append(info)
        if defaults and len(defaults_rows) == 0:
            defaults_rows = defaults
            get_defaults = False
        if new_server:
            # Need to stop the server!
            new_server.disconnect()
            res = _stop_server(server_val, basedir, options)

    print_list(sys.stdout, format, _COLUMNS, rows, no_headers)

    if show_defaults and len(defaults_rows) > 0:
        for row in defaults_rows:
            print "  %s" % row