Beispiel #1
0
    def currentConn(self) -> mysql_connect:
        mConfigInfo = ConfigInfo()
        if self.__db_type == JPDbType.MySQL:
            if self.__currentConn is None:
                try:
                    conn = mysql_connect(host=mConfigInfo.host,
                                         user=mConfigInfo.user,
                                         password=mConfigInfo.password,
                                         database=mConfigInfo.database,
                                         port=mConfigInfo.port)
                except Exception as e:
                    linkErr = '连接数据库错误,请检查"config.ini"文件\n'
                    linkErr = linkErr + 'Connecting the database incorrectly, '
                    linkErr = linkErr + 'please check the "config.ini" file'
                    s = Exception.__repr__(e) + '\n' + linkErr
                    QMessageBox.warning(None, '错误', s, QMessageBox.Yes,
                                        QMessageBox.Yes)
                    exit()
                self.__currentConn = conn
            return self.__currentConn
        if self.__db_type == JPDbType.SqlServer:
            pass

        if self.__db_type == JPDbType.SqlServer:
            pass
Beispiel #2
0
    def currentConn(self) -> mysql_connect:
        cfg = ConfigInfo()
        if self.__db_type == JPDbType.MySQL:
            if self.__currentConn is None:
                try:
                    conn = mysql_connect(host=cfg.database.host,
                                         user=cfg.database.user,
                                         password=cfg.database.password,
                                         database=cfg.database.database,
                                         port=int(cfg.database.port))
                except Exception as e:
                    linkErr = '连接数据库错误,请检查"config.ini"文件\n'
                    linkErr = linkErr + 'Connecting the database incorrectly, '
                    linkErr = linkErr + 'please check the "config.ini" file'
                    s = Exception.__repr__(e) + '\n' + linkErr
                    raise RuntimeError(s)
                self.__currentConn = conn
            return self.__currentConn
        if self.__db_type == JPDbType.SqlServer:
            pass

        if self.__db_type == JPDbType.SqlServer:
            pass
Beispiel #3
0
        settings['version'] = DatabaseVersion.CURRENT
        database_manager.execute(
            'setting insert',
            arguments=('version', str(DatabaseVersion.CURRENT.value)))


# ============================================================================
# >> INITIALIZATION
# ============================================================================
# TODO: Get MySQL working
if _driver == 'mysql':
    _queue.put(
        _Node(NodeType.CONNECT,
              query=lambda: mysql_connect(host=_database['host'],
                                          port=_database['port'],
                                          user=_database['user'],
                                          passwd=_database['password'],
                                          connect_timeout=_database['timeout'],
                                          charset='utf8mb4')))

    database_manager.execute('toggle warnings', format_args=(0, ))
    database_manager.execute('create database',
                             format_args=(_database['database'], ))

    _queue.put(
        _Node(NodeType.USE,
              query=statements['use database'].format(_database['database'])))
else:
    _queue.put(
        _Node(NodeType.CONNECT,
              query=lambda: sqlite_connect(DATA_PATH.joinpath('players.sqlite')
                                           )))
Beispiel #4
0
        if version < DatabaseVersion.UPDATE3:
            for statement in [x for x in statements if x.startswith(f'database upgrade {DatabaseVersion.UPDATE3.value}.')]:
                database_manager.execute(statement)

        database_manager.execute('setting update', arguments=(str(DatabaseVersion.CURRENT.value), ), format_args=('version', ))
        settings['version'] = DatabaseVersion.CURRENT

    OnSettingsLoaded.manager.notify(settings)


# ============================================================================
# >> INITIALIZATION
# ============================================================================
# TODO: Get MySQL working
if _driver == 'mysql':
    _queue.put(_Node(NodeType.CONNECT, query=lambda: mysql_connect(host=_database['host'], port=_database['port'], user=_database['user'], passwd=_database['password'], connect_timeout=_database['timeout'], charset='utf8mb4')))

    database_manager.execute('toggle warnings', format_args=(0, ))
    database_manager.execute('create database', format_args=(_database['database'], ))

    _queue.put(_Node(NodeType.USE, query=statements['use database'].format(_database['database'])))
else:
    _queue.put(_Node(NodeType.CONNECT, query=lambda: sqlite_connect(DATA_PATH.joinpath('players.sqlite'))))

for statement in ('create players', 'create races', 'create skills', 'create stats', 'create stats races', 'create stats items', 'create settings'):
    database_manager.execute(statement)

if _driver == 'mysql':
    database_manager.execute('toggle warnings', format_args=(1, ))

database_manager.execute('setting get', callback=_query_settings)
Beispiel #5
0
 def connection(self):
     return mysql_connect(**self._params)
Beispiel #6
0
def resurrect_instances(dead_hv, spare_hv, update_db=True):
    assert dead_hv != spare_hv

    os_conn = OpenStack(session=os.session,
                        cloud=CLOUD,
                        region_name=os.get_region())

    if update_db:
        _logger.info('updating redis database')
        refresh_redis_inventory(True)

    spare_hv_r = redis.get('hypervisors', json.loads)[spare_hv]
    assert spare_hv_r['running_vms'] == 0
    dead_service = spare_service = None
    for svc in os_conn.compute.services():
        if svc.host == dead_hv:
            dead_service = svc
        elif svc.host == spare_hv:
            spare_service = svc
            assert svc.status == 'disabled'

    assert dead_service is not None
    assert spare_service is not None
    assert spare_service.state == 'up'
    assert spare_service.zone == dead_service.zone
    assert 'spare' in spare_service.disables_reason.lower()

    _logger.info(f'verifying that {dead_hv} is dead')
    if not nmap_scan([dead_hv], [22, 111, 16509]):
        raise Exception(f'hypervisor {dead_hv} does not seem to be dead!')

    instance_list = []
    servers = json.loads(redis.get('servers'))
    for _, server in servers.items():
        if server['hypervisor_hostname'] == spare_hv:
            raise Exception(f'spare hypervisor {spare_hv} has vms assigned!')
        if server['hypervisor_hostname'] == dead_hv:
            instance_list.append(server['id'])
            server['hypervisor_hostname'] = spare_hv

    if not instance_list:
        _logger.warning(f'{dead_hv} does not run any instances')
        return

    _logger.info('updating database records in nova')
    db_conn = mysql_connect(host=MYSQL_HOST,
                            user=MYSQL_USER,
                            passwd=MYSQL_PASS,
                            db='nova')
    try:
        spare_hv = escape_string(spare_hv)
        with db_conn.cursor() as cursor:
            for uuid in instance_list:
                uuid = escape_string(uuid)
                query = \
                    f'''update instances set
                    host = "{spare_hv}", node = "{spare_hv}"
                    where uuid="{uuid}"'''
                _logger.debug(query)
                cursor.execute(query)
        db_conn.commit()
    finally:
        db_conn.close()

    _logger.info('updating servers inventory db')
    redis.set('servers', json.dumps(servers))

    exceptions = []
    for uuid in instance_list:
        try:
            if servers[uuid]['vm_state'] == 'stopped':
                _logger.info(f'instance {uuid} is stoppped, not rebooting')
                continue

            _logger.info(f'hard rebooting instance {uuid}')
            os_conn.compute.reboot_server(uuid, 'HARD')
            for ifce in os_conn.compute.server_interfaces(uuid):
                _logger.info(f'updating port binding on {ifce.port_id}')
                port = os_conn.get_port(ifce.port_id)
                if port:
                    os_conn.network.update_port(
                        port, **{'binding:host_id': spare_hv})
        except Exception as e:
            exceptions.append(str(e))

    if exceptions:
        raise Exception('\n'.join(exceptions))

    _logger.info(f'disabling nova on {dead_hv}, enabling nova on {spare_hv}')
    os_conn.compute.disable_service(dead_service, dead_hv, 'nova-compute',
                                    f'sonny resurrection on {spare_hv}')
    os_conn.compute.enable_service(spare_service, spare_hv, 'nova-compute')
def mysql_connection(mysql_username, mysql_password, local_port):
    """This performs the connection and returns a connection object
    that we can use to execute our SQL commands."""
    return mysql_connect(user=mysql_username, passwd=mysql_password, port=local_port)