当前位置: 首页>>代码示例>>Python>>正文


Python Server.connect方法代码示例

本文整理汇总了Python中mysql.utilities.common.server.Server.connect方法的典型用法代码示例。如果您正苦于以下问题:Python Server.connect方法的具体用法?Python Server.connect怎么用?Python Server.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mysql.utilities.common.server.Server的用法示例。


在下文中一共展示了Server.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: check_connect

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
    def check_connect(self, port, full_datadir, name="cloned_server"):

        new_server = None
        # Create a new instance
        conn = {
            "user"   : "root",
            "passwd" : "root",
            "host"   : "localhost",
            "port"   : port,
            "unix_socket" : full_datadir + "/mysql.sock"
        }
        if os.name != "posix":
            conn["unix_socket"] = None
        
        server_options = {
            'conn_info' : conn,
            'role'      : name,
        }
        new_server = Server(server_options)
        if new_server is None:
            return None
        
        # Connect to the new instance
        try:
            new_server.connect()
        except UtilError, e:
            raise MUTLibError("Cannot connect to spawned server.")
开发者ID:LinhDart,项目名称:mysql-utilities,代码行数:29,代码来源:clone_server.py

示例2: check_connect

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
    def check_connect(port, name="cloned_server", conn_dict=None):
        """Check connection.

        port[in]    Server port.
        name[in]    Server name.
        """
        conn = {"user": "root", "passwd": "root", "host": "localhost",
                "port": port}

        if conn_dict is not None:
            conn.update(conn_dict)

        server_options = {'conn_info': conn, 'role': name, }
        new_server = Server(server_options)
        if new_server is None:
            return None

        # Connect to the new instance
        try:
            new_server.connect()
        except UtilError as err:
            raise MUTLibError("Cannot connect to spawned server: {0}".format(
                err.errmsg))

        return new_server
开发者ID:abooitt,项目名称:mysql-utilities,代码行数:27,代码来源:clone_server.py

示例3: test

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
class test(mutlib.System_test):
    """clone server parameters
    This test exercises the parameters for mysqlserverclone
    """

    def check_prerequisites(self):
        return self.check_num_servers(1)

    def setup(self):
        # No setup needed
        self.new_server = None
        return True

    def _test_server_clone(self, cmd_str, comment, kill=True, capture_all=False):
        self.results.append(comment+"\n")
        port1 = int(self.servers.get_next_port())
        cmd_str += " --new-port=%d " % port1
        full_datadir = os.path.join(os.getcwd(), "temp_%s" % port1)
        cmd_str += " --new-data=%s --delete " % full_datadir
        res = self.exec_util(cmd_str, "start.txt")
        for line in open("start.txt").readlines():
            # Don't save lines that have [Warning] or don't start with #
            index = line.find("[Warning]")
            if capture_all or (index <= 0 and line[0] == '#'):
                self.results.append(line)
        if res:
            raise MUTLibError("%s: failed" % comment)
       
        # Create a new instance
        conn = {
            "user"   : "root",
            "passwd" : "root",
            "host"   : "localhost",
            "port"   : port1,
            "unix_socket" : full_datadir + "/mysql.sock"
        }
        if os.name != "posix":
            conn["unix_socket"] = None
        
        server_options = {
            'conn_info' : conn,
            'role'      : "cloned_server_2",
        }
        self.new_server = Server(server_options)
        if self.new_server is None:
            return False
        
        if kill:
            # Connect to the new instance
            try:
                self.new_server.connect()
            except UtilError, e:
                self.new_server = None
                raise MUTLibError("Cannot connect to spawned server.")
            self.servers.stop_server(self.new_server)

        self.servers.clear_last_port()

        return True
开发者ID:LinhDart,项目名称:mysql-utilities,代码行数:61,代码来源:clone_server_parameters.py

示例4: _bulk_insert

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
    def _bulk_insert(self, rows, new_db, destination=None):
        """Import data using bulk insert

        Reads data from a table and builds group INSERT statements for writing
        to the destination server specified (new_db.name).

        This method is designed to be used in a thread for parallel inserts.
        As such, it requires its own connection to the destination server.

        Note: This method does not print any information to stdout.

        rows[in]           a list of rows to process
        new_db[in]         new database name
        destination[in]    the destination server
        """

        from mysql.utilities.common.lock import Lock
        from mysql.utilities.common.server import Server

        if self.dest_vals is None:
            self.dest_vals = self.get_dest_values(destination)

        # Spawn a new connection
        server_options = {
            'conn_info' : self.dest_vals,
            'role'      : "thread",
        }
        dest = Server(server_options)
        dest.connect()

        # Issue the write lock
        lock_list = [("`%s`.`%s`" % (new_db, self.tbl_name), 'WRITE')]
        my_lock = Lock(dest, lock_list, {'locking':'lock-all',})
                    
        # First, turn off foreign keys if turned on
        dest.disable_foreign_key_checks(True)

        if self.column_format is None:
            self.get_column_metadata()

        data_lists = self.make_bulk_insert(rows, new_db)
        insert_data = data_lists[0]
        blob_data = data_lists[1]

        # Insert the data first
        for data_insert in insert_data:
            try:
                res = dest.exec_query(data_insert, self.query_options)
            except UtilError, e:
                raise UtilError("Problem inserting data. "
                                     "Error = %s" % e.errmsg)
开发者ID:dannykopping,项目名称:deploi,代码行数:53,代码来源:table.py

示例5: show_options

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
 def show_options(self):
     """ Show all audit log variables.
     """
     server = Server({'conn_info': self.options.get("server_vals", None)})
     server.connect()
     rows = server.show_server_variable("audit%")
     server.disconnect()
     if rows:
         print "#\n# Audit Log Variables and Options\n#"
         print_list(sys.stdout, "GRID", ['Variable_name', 'Value'],
                    rows)
         print
     else:
         raise UtilError("No audit log variables found.")
开发者ID:abooitt,项目名称:mysql-utilities,代码行数:16,代码来源:audit_log.py

示例6: check_audit_log

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
    def check_audit_log(self):
        """Verify if the audit log plugin is installed on the server.
        Return the message error if not, or None.
        """
        error = None
        server = Server({'conn_info': self.options.get("server_vals", None)})
        server.connect()
        # Check to see if the plug-in is installed
        if not server.supports_plugin("audit"):
            error = "The audit log plug-in is not installed on this " + \
                    "server or is not enabled."
        server.disconnect()

        return error
开发者ID:abooitt,项目名称:mysql-utilities,代码行数:16,代码来源:audit_log.py

示例7: do_command

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
    def do_command(self):
        """ Check and execute the audit log command (previously set by the the
        options of the object constructor).
        """
        # Check for valid command
        command = self.options.get("command", None)
        if not command in VALID_COMMANDS:
            raise UtilError("Invalid command.")

        command_value = self.options.get("value", None)
        # Check for valid value if needed
        if (command_requires_value(command)
           and not check_command_value(command, command_value)):
            raise UtilError("Please provide the correct value for the %s "
                            "command." % command)

        # Copy command does not need the server
        if command == "COPY":
            self._copy_log()
            return True

        # Connect to server
        server = Server({'conn_info': self.options.get("server_vals", None)})
        server.connect()

        # Now execute the command
        print "#\n# Executing %s command.\n#\n" % command
        try:
            if command == "POLICY":
                server.exec_query("SET @@GLOBAL.audit_log_policy = %s" %
                                  command_value)
            elif command == "ROTATE":
                self._rotate_log(server)
            else:  # "ROTATE_ON_SIZE":
                server.exec_query("SET @@GLOBAL.audit_log_rotate_on_size = %s"
                                  % command_value)
        finally:
            server.disconnect()

        return True
开发者ID:akhan786,项目名称:LaunchDevelopment,代码行数:42,代码来源:audit_log.py

示例8: load_test_data

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
def load_test_data(server, db_num=1):
    """Load/insert data into the test databases.

    A considerable amount of data should be considered in order to take some
    time to load, allowing mysqlrplsync to be executed at the same time the
    data is still being inserted.

    server[in]      Target server to load the test data.
    db_num[in]      Number of databases to load the data (by default: 1).
                    It is assumed that a matching number of test databases
                    have been previously created.

    Note: method prepared to be invoked by a different thread.
    """
    # Create a new server instance with a new connection (for multithreading).
    srv = Server({'conn_info': server})
    srv.connect()

    for db_index in xrange(db_num):
        db_name = '`test_rplsync_db{0}`'.format(
            '' if db_num == 1 else db_index
        )
        # Insert random data on all tables.
        random_values = string.letters + string.digits
        for _ in xrange(TEST_DB_NUM_ROWS):
            columns = []
            values = []
            for table_index in xrange(TEST_DB_NUM_TABLES):
                columns.append('rnd_txt{0}'.format(table_index))
                rnd_text = "".join(
                    [random.choice(random_values) for _ in xrange(20)]
                )
                values.append("'{0}'".format(rnd_text))
                insert = ("INSERT INTO {0}.`t{1}` ({2}) VALUES ({3})"
                          "").format(db_name, table_index, ', '.join(columns),
                                     ', '.join(values))
                srv.exec_query(insert)
                srv.commit()
开发者ID:abooitt,项目名称:mysql-utilities,代码行数:40,代码来源:rpl_sync.py

示例9: int

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
                         (conn_val["host"], conn_val["user"],
                          conn_val["port"]))
        sys.stdout.flush()

        if conn_val["port"] is not None:
            conn_val["port"] = int(conn_val["port"])
        else:
            conn_val["port"] = 0

        server_options = {
            'conn_info' : conn_val,
            'role'      : "server%d" % i,
        }
        conn = Server(server_options)
        try:
            conn.connect()
            server_list.add_new_server(conn)
            print("CONNECTED")
            res = conn.show_server_variable("basedir")
            #print res
            basedir = res[0][1]
        # Here we capture any exception and print the error message.
        # Since all util errors (exceptions) derive from Exception, this is
        # safe.
        except Exception:
            _, err, _ = sys.exc_info()
            print("%sFAILED%s" % (BOLD_ON, BOLD_OFF))
            if conn.connect_error is not None:
                print(conn.connect_error)
            print("ERROR: %s" % str(err))
    if server_list.num_servers() == 0:
开发者ID:LinhDart,项目名称:mysql-utilities,代码行数:33,代码来源:mut.py

示例10: _spawn_server

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
def _spawn_server(options):
    """Spawn a server to use for reading .frm files

    This method spawns a new server instance on the port specified by the
    user in the options dictionary.

    options[in]         Options from user

    Returns tuple - (Server instance, new datdir) or raises exception on error
    """
    verbosity = int(options.get("verbosity", 0))
    quiet = options.get("quiet", False)
    new_port = options.get("port", 3310)
    user = options.get("user", None)
    start_timeout = int(options.get("start_timeout", 10))

    # 1) create a directory to use for new datadir

    # If the user is not the same as the user running the script...
    if user_change_as_root(options):
        # Since Python libraries correctly restrict temporary folders to
        # the user who runs the script and /tmp is protected on some
        # platforms, we must create the folder in the current folder
        temp_datadir = os.path.join(os.getcwd(), str(uuid.uuid4()))
        os.mkdir(temp_datadir)
    else:
        temp_datadir = tempfile.mkdtemp()

    if verbosity > 1 and not quiet:
        print "# Creating a temporary datadir =", temp_datadir

    # 2) spawn a server pointed to temp
    if not quiet:
        if user:
            print("# Spawning server with --user={0}.".format(user))
        print "# Starting the spawned server on port %s ..." % new_port,
        sys.stdout.flush()

    bootstrap_options = {
        'new_data': temp_datadir,
        'new_port': new_port,
        'new_id': 101,
        'root_pass': "root",
        'mysqld_options': None,
        'verbosity': verbosity if verbosity > 1 else 0,
        'basedir': options.get("basedir"),
        'delete': True,
        'quiet': True if verbosity <= 1 else False,
        'user': user,
        'start_timeout': start_timeout,
    }
    if verbosity > 1 and not quiet:
        print

    try:
        serverclone.clone_server(None, bootstrap_options)
    except UtilError as error:
        if error.errmsg.startswith("Unable to communicate"):
            err = ". Clone server error: {0}".format(error.errmsg)
            proc_id = int(error.errmsg.split("=")[1].strip('.'))
            print("ERROR Attempting to stop failed spawned server. "
                  " Process id = {0}.".format(proc_id))
            if os.name == "posix":
                try:
                    os.kill(proc_id, subprocess.signal.SIGTERM)
                except OSError:
                    pass
            else:
                try:
                    subprocess.Popen("taskkill /F /T /PID %i" %
                                     proc_id, shell=True)
                except:
                    pass
            raise UtilError(_SPAWN_SERVER_ERROR.format(err))
        else:
            raise

    if verbosity > 1 and not quiet:
        print "# Connecting to spawned server"
    conn = {
        "user": "root",
        "passwd": "root",
        "host": "127.0.0.1",
        "port": options.get("port"),
    }
    server_options = {
        'conn_info': conn,
        'role': "frm_reader_bootstrap",
    }
    server = Server(server_options)
    try:
        server.connect()
    except UtilError:
        raise UtilError(_SPAWN_SERVER_ERROR.format(""))

    if not quiet:
        print "done."

    return (server, temp_datadir)
开发者ID:abooitt,项目名称:mysql-utilities,代码行数:101,代码来源:read_frm.py

示例11: clone_server

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
def clone_server(conn_val, options):
    """Clone an existing server

    This method creates a new instance of a running server using a datadir
    set to the new_data parametr, with a port set to new_port, server_id
    set to new_id and a root password of root_pass. You can also specify
    additional parameters for the mysqld command line as well as turn on
    verbosity mode to display more diagnostic information during the clone
    process.

    The method will build a new base database installation from the .sql
    files used to construct a new installation. Once the database is
    created, the server will be started.

    dest_val[in]        a dictionary containing connection information
                        including:
                        (user, password, host, port, socket)
    options[in]         dictionary of options:
      new_data[in]        An existing path to create the new database and use
                          as datadir for new instance
                          (default = None)
      new_port[in]        Port number for new instance
                          (default = 3307)
      new_id[in]          Server_id for new instance
                          (default = 2)
      root_pass[in]       Password for root user on new instance (optional)
      mysqld_options[in]  Additional command line options for mysqld
      verbosity[in]       Print additional information during operation
                          (default is 0)
      quiet[in]           If True, do not print messages.
                          (default is False)
      cmd_file[in]        file name to write startup command
      start_timeout[in]   Number of seconds to wait for server to start
    """
    new_data = os.path.abspath(options.get('new_data', None))
    new_port = options.get('new_port', '3307')
    root_pass = options.get('root_pass', None)
    verbosity = options.get('verbosity', 0)
    user = options.get('user', 'root')
    quiet = options.get('quiet', False)
    cmd_file = options.get('cmd_file', None)
    start_timeout = int(options.get('start_timeout', 10))
    mysqld_options = options.get('mysqld_options', '')

    if not check_port_in_use('localhost', int(new_port)):
        raise UtilError("Port {0} in use. Please choose an "
                        "available port.".format(new_port))

    # Clone running server
    if conn_val is not None:
        # Try to connect to the MySQL database server.
        server1_options = {
            'conn_info': conn_val,
            'role': "source",
        }
        server1 = Server(server1_options)
        server1.connect()
        if not quiet:
            print "# Cloning the MySQL server running on %s." % \
                conn_val["host"]

        basedir = ""
        # Get basedir
        rows = server1.exec_query("SHOW VARIABLES LIKE 'basedir'")
        if not rows:
            raise UtilError("Unable to determine basedir of running server.")
        basedir = os.path.normpath(rows[0][1])

    # Cloning downed or offline server
    else:
        basedir = os.path.abspath(options.get("basedir", None))
        if not quiet:
            print "# Cloning the MySQL server located at %s." % basedir

    # If datadir exists, has data, and user said it was Ok, delete it
    if os.path.exists(new_data) and options.get("delete", False) and \
       os.listdir(new_data):
        shutil.rmtree(new_data, True)

    # Create new data directory if it does not exist
    if not os.path.exists(new_data):
        if not quiet:
            print "# Creating new data directory..."
        try:
            os.mkdir(new_data)
        except:
            raise UtilError("Unable to create directory '%s'" % new_data)

    if not quiet:
        print "# Configuring new instance..."
        print "# Locating mysql tools..."

    mysqld_path = get_tool_path(basedir, "mysqld")
    mysqladmin_path = get_tool_path(basedir, "mysqladmin")
    mysql_basedir = get_tool_path(basedir, "share/english/errgmsg.sys",
                                  False, False)
    mysql_basedir = basedir
    if os.path.exists(os.path.join(basedir, "local/mysql/share/")):
        mysql_basedir = os.path.join(mysql_basedir, "local/mysql/")
    # for source trees
#.........这里部分代码省略.........
开发者ID:akhan786,项目名称:LaunchDevelopment,代码行数:103,代码来源:serverclone.py

示例12: clone_server

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
def clone_server(conn_val, options):
    """Clone an existing server

    This method creates a new instance of a running server using a datadir
    set to the new_data parametr, with a port set to new_port, server_id
    set to new_id and a root password of root_pass. You can also specify
    additional parameters for the mysqld command line as well as turn on
    verbosity mode to display more diagnostic information during the clone
    process.

    The method will build a new base database installation from the .sql
    files used to construct a new installation. Once the database is
    created, the server will be started.

    dest_val[in]        a dictionary containing connection information
                        including:
                        (user, password, host, port, socket)
    options[in]         dictionary of options:
      new_data[in]        An existing path to create the new database and use
                          as datadir for new instance
                          (default = None)
      new_port[in]        Port number for new instance
                          (default = 3307)
      new_id[in]          Server_id for new instance
                          (default = 2)
      root_pass[in]       Password for root user on new instance (optional)
      mysqld_options[in]  Additional command line options for mysqld
      verbosity[in]       Print additional information during operation
                          (default is 0)
      quiet[in]           If True, do not print messages.
                          (default is False)
      cmd_file[in]        file name to write startup command
      start_timeout[in]   Number of seconds to wait for server to start
    """
    new_data = os.path.abspath(options.get('new_data', None))
    new_port = options.get('new_port', '3307')
    root_pass = options.get('root_pass', None)
    verbosity = options.get('verbosity', 0)
    user = options.get('user', 'root')
    quiet = options.get('quiet', False)
    cmd_file = options.get('cmd_file', None)
    start_timeout = int(options.get('start_timeout', 10))
    mysqld_options = options.get('mysqld_options', '')
    force = options.get('force', False)
    quote_char = "'" if os.name == "posix" else '"'

    if not check_port_in_use('localhost', int(new_port)):
        raise UtilError("Port {0} in use. Please choose an "
                        "available port.".format(new_port))

    # Check if path to database files is greater than MAX_DIR_SIZE char,
    if len(new_data) > MAX_DATADIR_SIZE and not force:
        raise UtilError("The --new-data path '{0}' is too long "
                        "(> {1} characters). Please use a smaller one. "
                        "You can use the --force option to skip this "
                        "check".format(new_data, MAX_DATADIR_SIZE))

    # Clone running server
    if conn_val is not None:
        # Try to connect to the MySQL database server.
        server1_options = {
            'conn_info': conn_val,
            'role': "source",
        }
        server1 = Server(server1_options)
        server1.connect()
        if not quiet:
            print "# Cloning the MySQL server running on %s." % \
                conn_val["host"]

        # Get basedir
        rows = server1.exec_query("SHOW VARIABLES LIKE 'basedir'")
        if not rows:
            raise UtilError("Unable to determine basedir of running server.")
        basedir = os.path.normpath(rows[0][1])

    # Cloning downed or offline server
    else:
        basedir = os.path.abspath(options.get("basedir", None))
        if not quiet:
            print "# Cloning the MySQL server located at %s." % basedir

    new_data_deleted = False
    # If datadir exists, has data, and user said it was Ok, delete it
    if os.path.exists(new_data) and options.get("delete", False) and \
       os.listdir(new_data):
        new_data_deleted = True
        shutil.rmtree(new_data, True)

    # Create new data directory if it does not exist
    if not os.path.exists(new_data):
        if not quiet:
            print "# Creating new data directory..."
        try:
            os.mkdir(new_data)
        except OSError as err:
            raise UtilError("Unable to create directory '{0}', reason: {1}"
                            "".format(new_data, err.strerror))

    # After create the new data directory, check for free space, so the errors
#.........这里部分代码省略.........
开发者ID:fengshao0907,项目名称:mysql-utilities,代码行数:103,代码来源:serverclone.py

示例13: parse_connection

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
# Parse source connection values
try:
    conn = parse_connection(opt.server)
except:
    parser.error("Server connection values invalid or cannot be parsed.")

# Get a server class instance
print "# Connecting to server..."
server_options = {
    'conn_info' : conn,
    'role'      : "source",
}
server1 = Server(server_options)
try:
    server1.connect()
except UtilError, e:
    print "ERROR:", e.errmsg

# Get list of databases from the server if not specified in options
print "# Getting databases..."
db_list = []
if opt.dbs_to_copy is None:
    for db in server1.get_all_databases():
        db_list.append((db[0], None))
else:
    for db in opt.dbs_to_copy.split(","):
        db_list.append((db, None))

# Get list of all users from the server
print "# Getting users..."
开发者ID:LinhDart,项目名称:mysql-utilities,代码行数:32,代码来源:copy_server.py

示例14: _shutdown_running_servers

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
def _shutdown_running_servers(server_list, processes, basedir):
    """Shutdown any running servers.

    processes[in]       The list of processes to shutdown with the form:
                        (process_id, [datadir|port])
    basedir[in]         The starting path to search for mysqladmin tool

    Returns bool - True - servers shutdown attempted
                   False - no servers to shutdown
    """
    if len(processes) < 1:
        return False
    for process in processes:
        datadir = os.getcwd()
        connection = {
            "user": "root",
            "passwd": "root",
            "host": "localhost",
            "port": None,
        }
        if os.name == "posix":
            try:
                connection["port"] = get_port(process[0])
            except MUTLibError:
                connection["port"] = -1  # try to kill it forcefully later
        elif os.name == "nt":
            connection["port"] = process[1]

        if os.name == "posix":
            print("  Process id: {0:>6}, Data path: {1}".format(process[0],
                                                                process[1]))
        elif os.name == "nt":
            print("  Process id: {0:>6}, Port: {1}".format(process[0],
                                                           process[1]))

        # 1) connect to the server.
        server_options = {
            'conn_info': connection,
        }
        svr = Server(server_options)
        ok_to_shutdown = True
        try:
            svr.connect()
        except UtilError:  # if we cannot connect, don't try to shut it down.
            ok_to_shutdown = False
            print("    WARNING: shutdown failed - cannot connect.")
        if not ok_to_shutdown:
            if os.name == "posix":
                # Attempt kill
                ret_code = subprocess.call(["kill", "-9",
                                            " {0}".format(process[0])])
                # wait until connection is closed
                for _ in range(CONNECTION_CLOSE_WAIT_TIMEOUT):
                    try:
                        sock = socket.create_connection((svr.host, svr.port))
                        sock.close()
                        time.sleep(1)
                    except socket.error:
                        # could not connect, connection is closed
                        break
                else:
                    print("    WARNING: timeout waiting for connection to "
                          "process {0} to close".format(process[0]))
                if ret_code:
                    print("    WARNING: shutdown failed: Killing process {0}"
                          "returned error code {1}".format(process[0],
                                                           ret_code))
            else:
                ret_code = subprocess.call("taskkill /F /T /PID {0}".format(
                    process[0]))
                if ret_code not in (0, 128):
                    print("    WARNING: shutdown failed: Killing process {0} "
                          "returned error code {1}".format(process[0],
                                                           ret_code))
        # 2) if nt, verify datadirectory
        if os.name == "nt" and ok_to_shutdown:
            res = svr.show_server_variable("datadir")
            server_datadir = res[0][1]
            ok_to_shutdown = (server_datadir.find(datadir) >= 0)

        # 3) call shutdown method from mutlib Server_list class
        if ok_to_shutdown and svr:
            try:
                server_list.stop_server(svr)
            except MUTLibError:
                _, e, _ = sys.exc_info()
                print("    WARNING: shutdown failed: " + e.errmsg)
    return True
开发者ID:fengshao0907,项目名称:mysql-utilities,代码行数:90,代码来源:mut.py

示例15: BinaryLogRotate

# 需要导入模块: from mysql.utilities.common.server import Server [as 别名]
# 或者: from mysql.utilities.common.server.Server import connect [as 别名]
class BinaryLogRotate(object):
    """The BinaryLogRotate Class, it represents a binary log rotation task.
    The rotate method performs the following tasks:
        - Retrieves the active binary log and file size.
        - If the minimum size is given, evaluate active binlog file size, and
          if this is greater than the minimum size rotation will occur.
          rotation occurs.
    """

    def __init__(self, server_cnx_val, options):
        """Initiator.

        server_cnx_val[in] Dictionary with the connection values for the
                           server.
        options[in]        options for controlling behavior:
            logging        If logging is active or not.
            verbose        print extra data during operations (optional)
                           default value = False
            min_size       minimum size that the active binlog must have prior
                           to rotate it.
            dry_run        Don't actually rotate the active binlog, instead
                           it will print information about file name and size.
        """

        # Connect to server
        self.server = Server({'conn_info': server_cnx_val})
        self.server.connect()
        self.options = options
        self.verbosity = self.options.get("verbosity", 0)
        self.quiet = self.options.get("quiet", False)
        self.logging = self.options.get("logging", False)
        self.dry_run = self.options.get("dry_run", 0)
        self.binlog_min_size = self.options.get("min_size", False)

    def _report(self, message, level=logging.INFO, print_msg=True):
        """Log message if logging is on.

        This method will log the message presented if the log is turned on.
        Specifically, if options['log_file'] is not None. It will also
        print the message to stdout.

        message[in]      Message to be printed.
        level[in]        Level of message to log. Default = INFO.
        print_msg[in]    If True, print the message to stdout. Default = True.
        """
        # First, print the message.
        if print_msg and not self.quiet:
            print(message)
        # Now log message if logging turned on
        if self.logging:
            msg = message.strip("#").strip(" ")
            logging.log(int(level), msg)

    def rotate(self):
        """This Method runs the rotation.

        This method will use the methods from the common library to rotate the
        binary log.
        """

        # Check required privileges
        check_privileges(self.server, BINLOG_OP_ROTATE,
                         ["RELOAD", "REPLICATION CLIENT"],
                         BINLOG_OP_ROTATE_DESC, self.verbosity, self._report)

        active_binlog, binlog_size = get_active_binlog_and_size(self.server)
        if self.verbosity:
            self._report("# Active binlog file: '{0}' (size: {1} bytes)'"
                         "".format(active_binlog, binlog_size))

        if self.binlog_min_size:
            rotated = rotate(self.server, self.binlog_min_size,
                             reporter=self._report)
        else:
            rotated = rotate(self.server, reporter=self._report)

        if rotated:
            new_active_binlog, _ = get_active_binlog_and_size(self.server)
            if active_binlog == new_active_binlog:
                raise UtilError("Unable to rotate binlog file.")
            else:
                self._report("# The binlog file has been rotated.")
                if self.verbosity:
                    self._report("# New active binlog file: '{0}'"
                                 "".format(new_active_binlog))
开发者ID:abooitt,项目名称:mysql-utilities,代码行数:87,代码来源:binlog_admin.py


注:本文中的mysql.utilities.common.server.Server.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。