int test_conc21(MYSQL *mysql)
{
  int rc;
  MYSQL_RES *res= NULL;
  MYSQL_ROW row;
  char tmp[256];
  int check_server_version= 0;
  int major=0, minor= 0, patch=0;

  rc= mysql_query(mysql, "SELECT @@version");
  check_mysql_rc(rc, mysql);

  res= mysql_store_result(mysql);
  FAIL_IF(res == NULL, "invalid result set");

  row= mysql_fetch_row(res);
  strcpy(tmp, row[0]);
  mysql_free_result(res);
  
  sscanf(tmp, "%d.%d.%d", &major, &minor, &patch);

  check_server_version= major * 10000 + minor * 100 + patch;

  FAIL_IF(mysql_get_server_version(mysql) != check_server_version, "Numeric server version mismatch");
  FAIL_IF(strcmp(mysql_get_server_info(mysql), tmp) != 0, "String server version mismatch");
  return OK;
}
Exemple #2
0
int test_sql()
{
	if (!m_use_sql)
		return 0;
	try
	{
		mysql_get_server_version(m_database);
		if (m_config.m_log_announce)
			Csql_query(m_database, "select id, ipa, port, event, info_hash, peer_id, downloaded, left0, uploaded, uid, mtime from @announce_log where 0").execute();
		Csql_query(m_database, "select name, value from @config where 0").execute();
		Csql_query(m_database, "select @fid, info_hash, @leechers, @seeders, flags, mtime, ctime from @files where 0").execute();
		Csql_query(m_database, "select fid, uid, active, announced, completed, downloaded, `left`, uploaded from @files_users where 0").execute();
		if (m_config.m_log_scrape)
			Csql_query(m_database, "select id, ipa, uid, mtime from @scrape_log where 0").execute();
		Csql_query(m_database, "select @uid, torrent_pass_version, downloaded, uploaded from @users where 0").execute();
		Csql_query(m_database, "update @files set @leechers = 0, @seeders = 0").execute();
		// Csql_query(m_database, "update @files_users set active = 0").execute();
		m_read_users_can_leech = Csql_query(m_database, "show columns from @users like 'can_leech'").execute();
		m_read_users_peers_limit = Csql_query(m_database, "show columns from @users like 'peers_limit'").execute();
		m_read_users_torrent_pass = Csql_query(m_database, "show columns from @users like 'torrent_pass'").execute();
		m_read_users_wait_time = Csql_query(m_database, "show columns from @users like 'wait_time'").execute();
		return 0;
	}
	catch (bad_query&)
	{
	}
	return 1;
}
Exemple #3
0
static package bf_mysql_status(Var arglist, Byte next, void *vdata, Objid progr)
{
	Var r;
	Objid oid = arglist.v.list[1].v.obj;
	free_var(arglist);
	if (!is_wizard(progr))
	  return make_error_pack(E_PERM);
	MYSQL_CONN *wrapper;
	wrapper = resolve_mysql_connection(oid);
	if (wrapper == NULL || wrapper->active == 0)
	  return make_error_pack(E_INVARG);
	r = new_list(7);
	r.v.list[1].type = TYPE_STR;
	r.v.list[1].v.str = str_dup(wrapper->server);
	r.v.list[2].type = TYPE_INT;
	r.v.list[2].v.num = wrapper->port;
	r.v.list[3].type = TYPE_STR;
	r.v.list[3].v.str = str_dup(wrapper->username);
	r.v.list[4].type = TYPE_STR;
	r.v.list[4].v.str = str_dup(wrapper->database);
	r.v.list[5].type = TYPE_INT;
	r.v.list[5].v.num = wrapper->connect_time;
	r.v.list[6].type = TYPE_INT;
	r.v.list[6].v.num = wrapper->last_query_time;
	r.v.list[7].type = TYPE_INT;
	r.v.list[7].v.num = mysql_get_server_version(wrapper->conn);
	return make_var_pack(r);
}
Exemple #4
0
static VALUE rb_connect(VALUE self, VALUE user, VALUE pass, VALUE host, VALUE port, VALUE database, VALUE socket, VALUE flags) {
  struct nogvl_connect_args args;
  VALUE rv;
  GET_CLIENT(self);

  args.host = NIL_P(host) ? NULL : StringValuePtr(host);
  args.unix_socket = NIL_P(socket) ? NULL : StringValuePtr(socket);
  args.port = NIL_P(port) ? 0 : NUM2INT(port);
  args.user = NIL_P(user) ? NULL : StringValuePtr(user);
  args.passwd = NIL_P(pass) ? NULL : StringValuePtr(pass);
  args.db = NIL_P(database) ? NULL : StringValuePtr(database);
  args.mysql = wrapper->client;
  args.client_flag = NUM2ULONG(flags);

  rv = (VALUE) rb_thread_call_without_gvl(nogvl_connect, &args, RUBY_UBF_IO, 0);
  if (rv == Qfalse) {
    while (rv == Qfalse && errno == EINTR && !mysql_errno(wrapper->client)) {
      errno = 0;
      rv = (VALUE) rb_thread_call_without_gvl(nogvl_connect, &args, RUBY_UBF_IO, 0);
    }
    if (rv == Qfalse)
      return rb_raise_mysql2_error(wrapper);
  }

  wrapper->server_version = mysql_get_server_version(wrapper->client);
  wrapper->connected = 1;
  return self;
}
Exemple #5
0
static VALUE rb_mysql_client_server_info(VALUE self) {
  VALUE version, server_info;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *default_internal_enc;
  rb_encoding *conn_enc;
#endif
  GET_CLIENT(self);

  REQUIRE_OPEN_DB(wrapper);
#ifdef HAVE_RUBY_ENCODING_H
  default_internal_enc = rb_default_internal_encoding();
  conn_enc = rb_to_encoding(wrapper->encoding);
#endif

  version = rb_hash_new();
  rb_hash_aset(version, sym_id, LONG2FIX(mysql_get_server_version(wrapper->client)));
  server_info = rb_str_new2(mysql_get_server_info(wrapper->client));
#ifdef HAVE_RUBY_ENCODING_H
  rb_enc_associate(server_info, conn_enc);
  if (default_internal_enc) {
    server_info = rb_str_export_to_enc(server_info, default_internal_enc);
  }
#endif
  rb_hash_aset(version, sym_version, server_info);
  return version;
}
wyBool
IsMySQL502(Tunnel * tunnel, PMYSQL mysql)
{
	long me = mysql_get_server_version(*mysql);
	
	if(me >= 50002)
		return wyTrue;
	else
		return wyFalse;
}
wyBool 
IsMySQL516(Tunnel * tunnel, PMYSQL mysql)
{
	wyUInt32 me = mysql_get_server_version(*mysql);/* Only available from MySQLv4.1*/

	if(me >= 50106)
		return wyTrue;
	else
		return wyFalse;
}
//MySQL 5.5.10
wyBool
IsMySQL5510(Tunnel * tunnel, PMYSQL mysql)
{
	long me = mysql_get_server_version(*mysql);/* Only available from MySQLv4.1*/

	if(me >= 50510)
		return wyTrue;
	else
		return wyFalse;
}
Exemple #9
0
Logger::Level Logger::databaseLevel( Logger::Level databaseLevel )
{
    if ( databaseLevel > NOOPT )
    {
        databaseLevel = limit(databaseLevel);
        if ( mDatabaseLevel != databaseLevel )
        {
            if ( databaseLevel > NOLOG && mDatabaseLevel <= NOLOG )
            {
                if ( !mDbConnected )
                {
                    if ( !mysql_init( &mDbConnection ) )
                    {
                        Fatal( "Can't initialise database connection: %s", mysql_error( &mDbConnection ) );
                        exit( mysql_errno( &mDbConnection ) );
                    }
                    my_bool reconnect = 1;
                    if ( mysql_options( &mDbConnection, MYSQL_OPT_RECONNECT, &reconnect ) )
                        Fatal( "Can't set database auto reconnect option: %s", mysql_error( &mDbConnection ) );
                    std::string::size_type colonIndex = staticConfig.DB_HOST.find( ":/" );
                    if ( colonIndex != std::string::npos )
                    {
                        std::string dbHost = staticConfig.DB_HOST.substr( 0, colonIndex );
                        std::string dbPort = staticConfig.DB_HOST.substr( colonIndex+1 );
                        if ( !mysql_real_connect( &mDbConnection, dbHost.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), 0, atoi(dbPort.c_str()), 0, 0 ) )
                        {
                            Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
                            exit( mysql_errno( &mDbConnection ) );
                        }
                    }
                    else
                    {
                        if ( !mysql_real_connect( &mDbConnection, staticConfig.DB_HOST.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), 0, 0, 0, 0 ) )
                        {
                            Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
                            exit( mysql_errno( &mDbConnection ) );
                        }
                    }
                    unsigned long mysqlVersion = mysql_get_server_version( &mDbConnection );
                    if ( mysqlVersion < 50019 )
                        if ( mysql_options( &mDbConnection, MYSQL_OPT_RECONNECT, &reconnect ) )
                            Fatal( "Can't set database auto reconnect option: %s", mysql_error( &mDbConnection ) );
                    if ( mysql_select_db( &mDbConnection, staticConfig.DB_NAME.c_str() ) )
                    {
                        Fatal( "Can't select database: %s", mysql_error( &mDbConnection ) );
                        exit( mysql_errno( &mDbConnection ) );
                    }
                    mDbConnected = true;
                }
            }
            mDatabaseLevel = databaseLevel;
        }
    }
    return( mDatabaseLevel );
}
//DEFAULT, ON UPDATE clause for DATETIME 
wyBool
IsMySQL565MariaDB1001(Tunnel *tunnel, PMYSQL mysql)
{
    long me = mysql_get_server_version(*mysql);/* Only available from MySQLv4.1*/
    const char *dbString = mysql_get_server_info(*mysql);

	if((me >= 50605 && !strstr(dbString, "MariaDB")) || (me >= 100001 && strstr(dbString, "MariaDB")))
		return wyTrue;
	else
		return wyFalse;
}
Exemple #11
0
Logger::Level Logger::databaseLevel( Logger::Level databaseLevel ) {
  if ( databaseLevel > NOOPT ) {
    databaseLevel = limit(databaseLevel);
    if ( mDatabaseLevel != databaseLevel ) {
      if ( databaseLevel > NOLOG && mDatabaseLevel <= NOLOG ) {
        if ( !mDbConnected ) {
          if ( !mysql_init( &mDbConnection ) ) {
            Fatal( "Can't initialise database connection: %s", mysql_error( &mDbConnection ) );
            exit( mysql_errno( &mDbConnection ) );
          }
          my_bool reconnect = 1;
          if ( mysql_options( &mDbConnection, MYSQL_OPT_RECONNECT, &reconnect ) )
            Fatal( "Can't set database auto reconnect option: %s", mysql_error( &mDbConnection ) );
          if ( !staticConfig.DB_SSL_CA_CERT.empty() )
            mysql_ssl_set( &mDbConnection, staticConfig.DB_SSL_CLIENT_KEY.c_str(), staticConfig.DB_SSL_CLIENT_CERT.c_str(), staticConfig.DB_SSL_CA_CERT.c_str(), NULL, NULL );
          std::string::size_type colonIndex = staticConfig.DB_HOST.find( ":" );
          if ( colonIndex == std::string::npos ) {
            if ( !mysql_real_connect( &mDbConnection, staticConfig.DB_HOST.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, 0, NULL, 0 ) ) {
              Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
              exit( mysql_errno( &mDbConnection ) );
            }
          } else {
            std::string dbHost = staticConfig.DB_HOST.substr( 0, colonIndex );
            std::string dbPortOrSocket = staticConfig.DB_HOST.substr( colonIndex+1 );
            if ( dbPortOrSocket[0] == '/' ) {
              if ( !mysql_real_connect( &mDbConnection, NULL, staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, 0, dbPortOrSocket.c_str(), 0 ) ) {
                Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
                exit( mysql_errno( &mDbConnection ) );
              }  
            } else {
              if ( !mysql_real_connect( &mDbConnection, dbHost.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, atoi(dbPortOrSocket.c_str()), NULL, 0 ) ) {
                Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
                exit( mysql_errno( &mDbConnection ) );
              }
            }
          } // end if has colon
          unsigned long mysqlVersion = mysql_get_server_version( &mDbConnection );
          if ( mysqlVersion < 50019 )
            if ( mysql_options( &mDbConnection, MYSQL_OPT_RECONNECT, &reconnect ) )
              Fatal( "Can't set database auto reconnect option: %s", mysql_error( &mDbConnection ) );
          if ( mysql_select_db( &mDbConnection, staticConfig.DB_NAME.c_str() ) ) {
            Fatal( "Can't select database: %s", mysql_error( &mDbConnection ) );
            exit( mysql_errno( &mDbConnection ) );
          }
          mDbConnected = true;
        } // end if ! mDbConnected
      } // end if ( databaseLevel > NOLOG && mDatabaseLevel <= NOLOG )
      mDatabaseLevel = databaseLevel;
    } // end if ( mDatabaseLevel != databaseLevel )
  } // end if ( databaseLevel > NOOPT )

  return( mDatabaseLevel );
}
wyBool IsMariaDB52(Tunnel * tunnel, PMYSQL mysql)
{
	long me = mysql_get_server_version(*mysql);
	const char *dbString = mysql_get_server_info(*mysql);
	
	if(me >= 50002 && strstr(dbString, "MariaDB"))
		return wyTrue;
	else
		return wyFalse;


}
Exemple #13
0
void CDataBase::Connect()
{
	ADDTOCALLSTACK("CDataBase::Connect");
	SimpleThreadLock lock(m_connectionMutex);
	if ( m_connected )
		return;

	if ( mysql_get_client_version() < LIBMYSQL_VERSION_ID )
	{
#ifdef _WIN32
		g_Log.EventWarn("Your MySQL client library %s is outdated. For better compatibility, update your 'libmysql.dll' file to version %s\n", mysql_get_client_info(), LIBMYSQL_VERSION);
#else
		g_Log.EventWarn("Your MySQL client library %s is outdated. For better compatibility, update your 'libmysqlclient' package to version %s\n", mysql_get_client_info(), LIBMYSQL_VERSION);
#endif
	}

	m_socket = mysql_init(NULL);
	if ( !m_socket )
	{
		g_Log.EventError("Insufficient memory to initialize MySQL client socket\n");
		return;
	}

	const char *user = g_Cfg.m_sMySqlUser;
	const char *password = g_Cfg.m_sMySqlPass;
	const char *db = g_Cfg.m_sMySqlDB;
	const char *host = g_Cfg.m_sMySqlHost;
	unsigned int port = MYSQL_PORT;

	// If user define server port using hostname:port format, split values into different variables
	const char *pszArgs = strchr(host, ':');
	if ( pszArgs != NULL )
	{
		char *pszTemp = Str_GetTemp();
		strcpy(pszTemp, host);
		*(strchr(pszTemp, ':')) = 0;
		port = ATOI(pszArgs + 1);
		host = pszTemp;
	}

	if ( mysql_real_connect(m_socket, host, user, password, db, port, NULL, CLIENT_MULTI_STATEMENTS) )
	{
		m_connected = true;
		if ( mysql_get_server_version(m_socket) < MYSQL_VERSION_ID )
			g_Log.EventWarn("Your MySQL server %s is outdated. For better compatibility, update your MySQL server to version %s\n", mysql_get_server_info(m_socket), MYSQL_SERVER_VERSION);
	}
	else
	{
		g_Log.EventError("MySQL error #%u: %s\n", mysql_errno(m_socket), mysql_error(m_socket));
		mysql_close(m_socket);
		m_socket = NULL;
	}
}
Exemple #14
0
static int test_wl4284_1(MYSQL *mysql)
{
  int rc;
  MYSQL_ROW row;
  MYSQL_RES *result;

  if (mysql_get_server_version(mysql) < 60000) {
    diag("Test requires MySQL Server version 6.0 or above");
    return SKIP;
  }

  /* set AUTOCOMMIT to OFF */
  rc= mysql_autocommit(mysql, FALSE);
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "DROP TABLE IF EXISTS trans");
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "CREATE TABLE trans (a INT) ENGINE= InnoDB");
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "INSERT INTO trans VALUES(1)");
  check_mysql_rc(rc, mysql);

  rc= mysql_refresh(mysql, REFRESH_GRANT | REFRESH_TABLES);
  check_mysql_rc(rc, mysql);

  rc= mysql_rollback(mysql);
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "SELECT * FROM trans");
  check_mysql_rc(rc, mysql);

  result= mysql_use_result(mysql);
  FAIL_IF(!result, "Invalid result set");

  row= mysql_fetch_row(result);
  FAIL_IF(!row, "Can't fetch row");

  mysql_free_result(result);

  /* set AUTOCOMMIT to OFF */
  rc= mysql_autocommit(mysql, FALSE);
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "DROP TABLE trans");
  check_mysql_rc(rc, mysql);

  return OK;
}
Exemple #15
0
static VALUE rb_connect(VALUE self, VALUE user, VALUE pass, VALUE host, VALUE port, VALUE database, VALUE socket, VALUE flags) {
  struct nogvl_connect_args args;
  time_t start_time, end_time;
  unsigned int elapsed_time, connect_timeout;
  VALUE rv;
  GET_CLIENT(self);

  args.host        = NIL_P(host)     ? NULL : StringValueCStr(host);
  args.unix_socket = NIL_P(socket)   ? NULL : StringValueCStr(socket);
  args.port        = NIL_P(port)     ? 0    : NUM2INT(port);
  args.user        = NIL_P(user)     ? NULL : StringValueCStr(user);
  args.passwd      = NIL_P(pass)     ? NULL : StringValueCStr(pass);
  args.db          = NIL_P(database) ? NULL : StringValueCStr(database);
  args.mysql       = wrapper->client;
  args.client_flag = NUM2ULONG(flags);

  if (wrapper->connect_timeout)
    time(&start_time);
  rv = (VALUE) rb_thread_call_without_gvl(nogvl_connect, &args, RUBY_UBF_IO, 0);
  if (rv == Qfalse) {
    while (rv == Qfalse && errno == EINTR) {
      if (wrapper->connect_timeout) {
        time(&end_time);
        /* avoid long connect timeout from system time changes */
        if (end_time < start_time)
          start_time = end_time;
        elapsed_time = end_time - start_time;
        /* avoid an early timeout due to time truncating milliseconds off the start time */
        if (elapsed_time > 0)
          elapsed_time--;
        if (elapsed_time >= wrapper->connect_timeout)
          break;
        connect_timeout = wrapper->connect_timeout - elapsed_time;
        mysql_options(wrapper->client, MYSQL_OPT_CONNECT_TIMEOUT, &connect_timeout);
      }
      errno = 0;
      rv = (VALUE) rb_thread_call_without_gvl(nogvl_connect, &args, RUBY_UBF_IO, 0);
    }
    /* restore the connect timeout for reconnecting */
    if (wrapper->connect_timeout)
      mysql_options(wrapper->client, MYSQL_OPT_CONNECT_TIMEOUT, &wrapper->connect_timeout);
    if (rv == Qfalse)
      return rb_raise_mysql2_error(wrapper);
  }

  wrapper->server_version = mysql_get_server_version(wrapper->client);
  wrapper->connected = 1;
  return self;
}
int Database::serverVersion()
{
  if (!m_connectionThread ||
       m_connectionThread->isRunning() ||
       !m_connectionThread->wasSuccessful() )
  {
    m_luaInterface->PushNil();
    return 1;
  }

  m_sqlMutex.lock();
  m_luaInterface->PushLong( mysql_get_server_version(m_sql) );
  m_sqlMutex.unLock();
  return 1;
}
Exemple #17
0
/* Thread that connects to the database, on success it continues to handle queries in the run method.
 */
void Database::connectRun()
{
	LOG_CURRENT_FUNCTIONCALL
	mysql_thread_init();
	auto threadEnd = finally([&] { mysql_thread_end(); });
	{
		auto connectionSignaliser = finally([&] { m_connectWakeupVariable.notify_one(); });
		std::lock_guard<std::mutex>(this->m_connectMutex);
		this->m_sql = mysql_init(nullptr);
		if (this->m_sql == nullptr)
		{
			m_success = false;
			m_connection_err = "Out of memory";
			m_connectionDone = true;
			m_status = DATABASE_CONNECTION_FAILED;
			return;
		}
		if (this->shouldAutoReconnect)
		{
			my_bool reconnect = 1;
			mysql_options(this->m_sql, MYSQL_OPT_RECONNECT, &reconnect);
		}
		const char* socket = (this->socket.length() == 0) ? nullptr : this->socket.c_str();
		unsigned long clientFlag = (this->useMultiStatements) ? CLIENT_MULTI_STATEMENTS : 0;
		if (mysql_real_connect(this->m_sql, this->host.c_str(), this->username.c_str(), this->pw.c_str(), 
			this->database.c_str(), this->port, socket, clientFlag) != this->m_sql)
		{
			m_success = false;
			m_connection_err = mysql_error(this->m_sql);
			m_connectionDone = true;
			m_status = DATABASE_CONNECTION_FAILED;
			return;
		}
		m_success = true;
		m_connection_err = "";
		m_connectionDone = true;
		m_status = DATABASE_CONNECTED;
		m_serverVersion = mysql_get_server_version(this->m_sql);
		m_serverInfo = mysql_get_server_info(this->m_sql);
		m_hostInfo = mysql_get_host_info(this->m_sql);
	}
	auto closeConnection = finally([&] { mysql_close(this->m_sql); this->m_sql = nullptr;  });
	if (m_success)
	{
		run();
	}
}
Exemple #18
0
bool
DbUtil::databaseLogin(const char* system, const char* usr,
                           const char* password, unsigned int portIn,
                           const char* sockIn, bool transactional)
{
  if (!(m_mysql = mysql_init(NULL)))
  {
    myerror("DB Login-> mysql_init() failed");
    return false;
  }
  setUser(usr);
  setHost(system);
  setPassword(password);
  setPort(portIn);
  setSocket(sockIn);
  m_dbname.assign("test");

  if (!(mysql_real_connect(m_mysql, 
                           m_host.c_str(), 
                           m_user.c_str(), 
                           m_pass.c_str(), 
                           m_dbname.c_str(),
                           m_port, 
                           m_socket.c_str(), 0)))
  {
    myerror("connection failed");
    disconnect();
    return false;
  }

  m_mysql->reconnect = TRUE;

  /* set AUTOCOMMIT */
  if(!transactional)
    mysql_autocommit(m_mysql, TRUE);
  else
    mysql_autocommit(m_mysql, FALSE);

  #ifdef DEBUG
    printf("\n\tConnected to MySQL server version: %s (%lu)\n\n", 
           mysql_get_server_info(m_mysql),
           (unsigned long) mysql_get_server_version(m_mysql));
  #endif
  selectDb();
  m_connected= true;
  return true;
}
Exemple #19
0
BOOL CMySQL::Connect(const char *server, const char *user, const char *pass, const char *db, unsigned int port, const char *unix_socket, const char *charset)
{
    // initialize the mysql structure
    if (mysql_init(&mysql) == NULL) {
        return false;
    }
    // try to connect to the mysql server
    connection = mysql_real_connect(&mysql, server, user, pass, db, port, unix_socket, 0);
    if (connection == NULL) {
        mysql_close(&mysql);
        return false;
    }
    version = mysql_get_server_version(&mysql);
    if (charset) SetCharacterSet(charset);

    return true;
}
Exemple #20
0
/**
* Sets the client character set
*/
static int Lmysql_set_charset (lua_State *L) {
    lua_mysql_conn *my_conn = Mget_conn (L);
    const char *ncharset = luaL_checkstring (L, 2);
    char charset[1024];

    /* major_version*10000 + minor_version *100 + sub_version
      For example, 5.1.5 is returned as 50105. 
    */
    unsigned long version = mysql_get_server_version(my_conn->conn);

    int i, j=0;
    for (i = 0; i < strlen(ncharset); i++) {
        if (ncharset[i] != '-') {
            charset[j] = ncharset[i];
            j++;
        }
    }
    charset[j] = 0;

    /* set charset */
    if ( version > 41000) {
        const char *statement1 = lua_pushfstring(L, "SET character_set_connection=%s, character_set_results=%s, character_set_client=binary", charset, charset);
        unsigned long st_len1 = strlen(statement1);
        if (mysql_real_query(my_conn->conn, statement1, st_len1)) {
            return luaM_msg (L, 0, mysql_error(my_conn->conn));
        }
    }
    else {
        if (mysql_set_character_set(my_conn->conn, charset)) {
            return luaM_msg (L, 0, mysql_error(my_conn->conn));
        }
    }

    if ( version > 50001) {
        const char *statement2 = "SET sql_mode=''";
        unsigned long st_len2 = strlen(statement2);
        if (mysql_real_query(my_conn->conn, statement2, st_len2)) {
            return luaM_msg (L, 0, mysql_error(my_conn->conn));
        }
    }

	lua_pushboolean(L, 1);
	return 1;
}
Exemple #21
0
/*
  Altough mysql_create_db(), mysql_rm_db() are deprecated since 4.0 they
  should not crash server and should not hang in case of errors.

  Since those functions can't be seen in modern API (unless client library
  was compiled with USE_OLD_FUNCTIONS define) we use simple_command() macro.
*/
static int test_bug6081(MYSQL *mysql)
{
  int rc;

  if (mysql_get_server_version(mysql) < 50100) {
    diag("Test requires MySQL Server version 5.1 or above");
    return SKIP;
  }

  rc= simple_command(mysql, MYSQL_COM_DROP_DB, (char*) schema,
                     (ulong)strlen(schema), 0U);
  FAIL_IF(!rc, "Error expected");

  rc= simple_command(mysql, MYSQL_COM_CREATE_DB, (char*) schema,
                     (ulong)strlen(schema), 0U);
  FAIL_IF(!rc, "Error expected");
  
  rc= mysql_select_db(mysql, schema);
  check_mysql_rc(rc, mysql);
  return OK;
}
Exemple #22
0
static VALUE rb_mysql_client_server_info(VALUE self) {
  MYSQL * client;
  VALUE version, server_info;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *default_internal_enc = rb_default_internal_encoding();
  rb_encoding *conn_enc = rb_to_encoding(rb_iv_get(self, "@encoding"));
#endif

  Data_Get_Struct(self, MYSQL, client);
  REQUIRE_OPEN_DB(client);

  version = rb_hash_new();
  rb_hash_aset(version, sym_id, LONG2FIX(mysql_get_server_version(client)));
  server_info = rb_str_new2(mysql_get_server_info(client));
#ifdef HAVE_RUBY_ENCODING_H
  rb_enc_associate(server_info, conn_enc);
  if (default_internal_enc) {
    server_info = rb_str_export_to_enc(server_info, default_internal_enc);
  }
#endif
  rb_hash_aset(version, sym_version, server_info);
  return version;
}
Exemple #23
0
static PyObject* wsql_connection_set_sql_mode(wsql_connection *self, PyObject *args)
{
    int error = 0;
    char* sql_mode;

    if (!PyArg_ParseTuple(args, "s:set_sql_mode", &sql_mode))
        return NULL;

    CHECK_CONNECTION(self, NULL);

    Py_BEGIN_ALLOW_THREADS
    if (mysql_get_server_version(&(self->connection)) > 40100)
    {
        char query[256];
        snprintf(query, 256, "SET SESSION sql_mode='%s'", sql_mode);
        error = mysql_query(&(self->connection), query);
    }
    Py_END_ALLOW_THREADS
    if (error)
        return wsql_raise_error(self);

    Py_RETURN_NONE;
}
uint32 DatabaseWorkerPool<T>::OpenConnections(InternalIndex type, uint8 numConnections)
{
	for (uint8 i = 0; i < numConnections; ++i)
	{
		// Create the connection
		auto connection = [&] {
			switch (type)
			{
			case IDX_ASYNC:
				return Trinity::make_unique<T>(_queue.get(), *_connectionInfo);
			case IDX_SYNCH:
				return Trinity::make_unique<T>(*_connectionInfo);
			default:
				ABORT();
			}
		}();

		if (uint32 error = connection->Open())
		{
			// Failed to open a connection or invalid version, abort and cleanup
			_connections[type].clear();
			return error;
		}
		else if (mysql_get_server_version(connection->GetHandle()) < MIN_MYSQL_SERVER_VERSION)
		{
			TC_LOG_ERROR("sql.driver", "TrinityCore does not support MySQL versions below 5.1");
			return 1;
		}
		else
		{
			_connections[type].push_back(std::move(connection));
		}
	}

	// Everything is fine
	return 0;
}
Exemple #25
0
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  //const char ** colnames;         /* column names */
  const char ** values;           /* values */
#endif
  char sqlquery_str[1024]  ="";   /* SQL query string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  int top_count            =0;    /* how many top ip to display */
  char start_date[11]      ="";   /* selected start date */
  char start_time[6]       ="";   /* selected start time */
  char end_date[11]        ="";   /* selected end date */
  char end_time[6]         ="";   /* selected end time */
  char order_by[13]        ="";   /* sort list by column */
  char sort_order[5]       ="";   /* ascending or descending */
  char **form_data;               /* string array for query data */
  char title[256]          = "";  /* cgi title string */
  struct tm *tm_ptr;              /* containing time structure */
  time_t now, old;                /* containing timestamp */
  char err_str[2048]       = "";  /* use for combined error string */
  int period               = 0;   /* the period to display */
  char dataunit[255] = "0 Bytes"; /* holds the calculated KB/MB */

  _abort_flag     = 0;
#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);
#endif

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  if(form_data[0] == NULL) {
    /* ------------------------------------------------------------------- * 
     * Start the HTML output to display the query selection                *
     * ------------------------------------------------------------------- */
    /* define the CGI title */
    snprintf(title, sizeof(title), "Top IP Address Session Activity");
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");

    fprintf(cgiOut, "<form action=\"ip-toplast.cgi\" method=\"get\">\n");
    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    /* 1st row, display headers */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">Number of IP</th>");
    fprintf(cgiOut, "<th class=\"inner\">Time Frame</th>");
    fprintf(cgiOut, "<th class=\"inner\">Top by</th>");
    fprintf(cgiOut, "<th class=\"inner\">Sort Order</th>");
    fprintf(cgiOut, "</tr>\n");
    /* 2nd row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"24\" checked name=\"start\">Last Day</td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 3rd row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"168\" name=\"start\">Last Week</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"desc\" checked name=\"sort_order\">");
    fprintf(cgiOut, "Top</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 4th row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><select name=\"top_count\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"5\">Top 5 IP</option>");
    fprintf(cgiOut, "<option selected value=\"10\">Top 10 IP</option>");
    fprintf(cgiOut, "<option value=\"20\">Top 20 IP</option>");
    fprintf(cgiOut, "<option value=\"50\">Top 50 IP</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"720\" name=\"start\">Last Month</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><select name=\"order_by\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"elapsed_mins\">Elapsed Time</option>");
    fprintf(cgiOut, "<option value=\"bytes_in\">Bytes In</option>");
    fprintf(cgiOut, "<option selected value=\"bytes_out\">Bytes Out</option>");
    fprintf(cgiOut, "<option value=\"packets_in\">Packets In</option>");
    fprintf(cgiOut, "<option value=\"packets_out\">Packets Out</option>");
    fprintf(cgiOut, "<option value=\"sessions\">Session Count</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio name=\"sort_order\" value=\"asc\">Bottom</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 5th row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"2160\" name=\"start\">Last 3 Months</td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 6th and last row, close the frame */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=4><input type=submit value=\"Run Query\"></td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");

    fprintf(cgiOut, "<h3>Additional Information</h3>\n");
    fprintf(cgiOut, "<hr>\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "This query returns a list of top IP addresses of the \"Order By\" selection for the last time period choosen.");
    fprintf(cgiOut, " It will give you a quick view who is possibly missusing the service, i.e. transferring large amounts of data in or out.");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>Select the number of top IP to display (5, 10, 20, 50) from the drop down list.");
    fprintf(cgiOut, "<li>The time frame can be selected from the radio menu, time is counting back from now.");
    fprintf(cgiOut, "<li>The results list is grouped by the \"Order By\" list, and sorted \"Top\" down or \"Bottom\" up.");
    fprintf(cgiOut, "</ul>");
    fprintf(cgiOut, "</p>\n");
  } /* end if for displaying the query request */
  else {
  /* ------------------------------------------------------------------- *
   * check if we got all information to make the SQL query               *
   * --------------------------------------------------------------------*/
    if ( cgiFormIntegerBounded("top_count", &top_count, 1, 50, 10) 
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving IP top count.");
  
    if ( cgiFormIntegerBounded("start", &period, 1, 2160, 24) 
                                                     != cgiFormSuccess ) 
      cgi_error("Error retrieving start period information.");
  
    if ( cgiFormString("order_by", order_by, sizeof(order_by))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving order_by information.");
  
    if ( cgiFormString("sort_order", sort_order, sizeof(sort_order))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving sort_order information.");
  
    /* ------------------------------------------------------------------- * 
     * The calculate query start and end time from given period in hours   *
     * ------------------------------------------------------------------- */
    now = time(NULL);
    tm_ptr = localtime(&now);
    strftime(end_date, sizeof(end_date), "%d.%m.%Y", (tm_ptr));
    strftime(end_time, sizeof(end_time), "%H:%M", tm_ptr);
    old = time(NULL) - (period * 3600);
    tm_ptr = localtime(&old);
    strftime(start_date, sizeof(start_date), "%d.%m.%Y", tm_ptr);
    strftime(start_time, sizeof(start_time), "%H:%M", tm_ptr);
  
    /* ------------------------------------------------------------------- *
     * check we got all parts and can start doing the SQL query below      *
     * --------------------------------------------------------------------*/
#ifdef ORACLE_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT IP_ADDR, TO_CHAR(SUM(BYTES_IN), '999,999,999,999') BYTES_IN, TO_CHAR(SUM(BYTES_OUT), '999,999,999,999') BYTES_OUT, TO_CHAR(SUM(PACKETS_IN), '999,999,999,999') PACKETS_IN, TO_CHAR(SUM(PACKETS_OUT), '999,999,999,999') PACKETS_OUT, TO_CHAR(SUM(ELAPSED_MINS), '99,999.99') ELAPSED_MINS, COUNT (IP_ADDR) AS SESSIONS FROM %s.V_EDACS WHERE BYTES_IN IS NOT NULL AND START_DATE BETWEEN TO_DATE('%s %s', 'dd.mm.yyyy hh24:mi') and TO_DATE ('%s %s', 'dd.mm.yyyy hh24:mi') GROUP BY IP_ADDR ORDER BY %s %s",
           EDACSADMIN, start_date, start_time, end_date,
           end_time, order_by, sort_order);

    /* initialize the statement handle */
    sth1 = SQLO_STH_INIT;
  
    /* opens a cursor for the query statement */
    if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL))) {
      if(DEBUG == 0) cgi_error(sqlo_geterror(dbh));
      else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
               sqlo_geterror(dbh), sqlquery_str);
      cgi_error(err_str);
    }
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
  
    /* get the output column names */
    //if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
    //  cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
    // RETURN_ON_ABORT; /* finish if SIGINT was catched */
  #endif
#ifdef MYSQL_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT ip_addr, SUM(bytes_in) bytes_in, SUM(BYTES_OUT) bytes_out, TRUNCATE((bytes_in+bytes_out)/SUM(TIME_TO_SEC(elapsed_mins)),2) throughput, FORMAT(SUM(packets_in), 0) packets_in, FORMAT(SUM(packets_out), 0) packet_out, SEC_TO_TIME(SUM(TIME_TO_SEC(elapsed_mins))) elapsed_mins, COUNT(ip_addr) AS SESSIONS FROM v_edacs WHERE bytes_in IS NOT NULL AND start_date BETWEEN STR_TO_DATE('%s %s', '%s') and STR_TO_DATE('%s %s', '%s') GROUP BY ip_addr ORDER BY %s %s",
           start_date, start_time, "%d.%m.%Y %H:%i",
           end_date, end_time, "%d.%m.%Y %H:%i",
           order_by, sort_order);

  /* Prepare and execute the SQL statement */
  if(mysql_query(dbh, sqlquery_str) != 0) {
    if(DEBUG == 0) cgi_error(mysql_error(dbh));
    else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
    cgi_error(err_str);
  }
 /* get query results set */
  result = mysql_store_result(dbh);
  if (result == NULL) {
    snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
    cgi_error( err_str);
  }

  allrows = mysql_num_rows(result);
  colcount = mysql_num_fields(result);
#endif

  /* ------------------------------------------------------------------------ *
   * start the html output                                                    *
   * -------------------------------------------------------------------------*/
    snprintf(title, sizeof(title), "Top %d IP Address Activity by %s", top_count, order_by);
  
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "<b>Top:</b> %d <b>Selection:</b> %s <b>Timeperiod:</b> %s %s - %s %s <b>Data Records:</b> %d",
               top_count, order_by, start_date, start_time, end_date, end_time, allrows);
    fprintf(cgiOut, "</p>\n");

    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">#</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">IP Address</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data In</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data Out</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Throughput</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Packets In</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Packets Out</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Elapsed Time</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Sessions</th>\n");
    fprintf(cgiOut, "</tr>\n");
  
    /* fetch the data */
#ifdef ORACLE_DB
    while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
       /* get one record */
       values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
     while((values = mysql_fetch_row(result)) != NULL) {
#endif
     rowcount++;

     /* check for even/odd rows */
     oddline_calc = div(rowcount, 2);
     if(oddline_calc.rem) fprintf(cgiOut, "<tr class=\"odd\">\n");
     else fprintf(cgiOut, "<tr class=\"even\">\n");

     fprintf(cgiOut, "<td>%d</td>\n", rowcount);
     fprintf(cgiOut, "<td>");
     fprintf(cgiOut, "<a href=ip-actlast.cgi?start=%d&sort_order=%s&ipaddr=%s&order_by=start_date>",
                         period, sort_order, values[0]);
     fprintf(cgiOut, "%s</a></td>", values[0]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", calc_units(values[1], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s</td>", calc_units(values[2], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s/s</td>", calc_units(values[3], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[4]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[5]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[6]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[7]);
     fprintf(cgiOut, "</tr>\n");

       if ( rowcount == top_count) break;
     } /* end while row */
#ifdef ORACLE_DB
    if (SQLO_SUCCESS != sqlo_close(sth1))
      cgi_error("Error Closing the SQL statment handle.");
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
   mysql_close(dbh);
#endif

     /* ----------------------------------------------------------------- *
      * IF there was no data for the selection, display a notification    *
      * ----------------------------------------------------------------- */
    if(rowcount == 0) {
      fprintf(cgiOut, "<tr>\n");
      fprintf(cgiOut, "<td colspan=9>");
      fprintf(cgiOut, "No data found for top %d IP by %s between %s %s and %s %s.",
              top_count, order_by, start_date, start_time, end_date, end_time);
      fprintf(cgiOut, "</td>\n");
      fprintf(cgiOut, "</tr>\n");
    } /* end if rowcount is zero */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=9>");
    fprintf(cgiOut, "&nbsp;");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
  } /* end else we were called with form data */

  pageside();
  pagefoot();
  return(0);
}
Exemple #26
0
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  const char ** values;           /* values */
#endif

  char sqlquery_str[1024]  ="";   /* SQL query string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  char router[41]          ="";   /* selected router IP */
  char start_date[11]      ="";   /* selected start date */
  char start_time[6]       ="";   /* selected start time */
  char end_date[11]        ="";   /* selected end date */
  char end_time[6]         ="";   /* selected end time */
  char select_by[11]       ="";   /* select by start_date (def) | stop_date */
  char order_by[13]        ="";   /* sort list by column */
  char sort_order[5]       ="";   /* ascending or descending */
  char **form_data;               /* string array for query data */
  char title[256]          = "";  /* cgi title string */
  struct tm *tm_ptr;              /* containing time structure */
  time_t now, old;                /* containing timestamp */
  char err_str[2048]       = "";  /* use for combined error string */
  char dataunit[255] = "0 Bytes"; /* holds the calculated KB/MB */
  unsigned long long sum_bin = 0;
  unsigned long long sum_bout = 0;
  unsigned long long sum_ball = 0;
  char sum_buf[255]  = "0";

  _abort_flag     = 0;
#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);


  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  /* ------------------------------------------------------------------- * 
   * If we are not called with arguments, we display the query selector  *
   * with a query to list the available routers from edacs_router.       *
   * ------------------------------------------------------------------- */
  if(form_data[0] == NULL) {

    /* define the SQL query */
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT ROUTER FROM %s.EDACS_ROUTER", EDACSADMIN);

    /* initialize the statement handle */
    sth1 = SQLO_STH_INIT;

    /* opens a cursor for the query statement */
    if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL)))
      cgi_error(sqlo_geterror(dbh));
    RETURN_ON_ABORT; /* finish if SIGINT was catched */

    /* get the output column names */
    //if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
    //  cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
    //RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  /* ------------------------------------------------------------------- * 
   * If we are not called with arguments, we display the query selector  *
   * with a query to list the available routers from edacs_router.       *
   * ------------------------------------------------------------------- */
  if(form_data[0] == NULL) {

    /* create the SQL query string */
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT router FROM edacs_router");

    /* Prepare and execute the SQL statement */
    if(mysql_query(dbh, sqlquery_str) != 0) {
      if(DEBUG == 0) cgi_error(mysql_error(dbh));
      else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
      cgi_error(err_str);
    }
   /* get query results set */
    result = mysql_store_result(dbh);
    if (result == NULL) {
      snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
      cgi_error( err_str);
    }

    colcount = mysql_num_fields(result);
#endif

    /* ------------------------------------------------------------------- * 
     * The timestamps are used for range pre-selection or show query time  *
     * ------------------------------------------------------------------- */
    now = time(NULL);
    tm_ptr = localtime(&now);
    strftime(end_date, sizeof(end_date), "%d.%m.%Y", (tm_ptr));
    strftime(end_time, sizeof(end_time), "%H:%M", tm_ptr);
    old = time(NULL) - 7200;
    tm_ptr = localtime(&old);
    strftime(start_date, sizeof(start_date), "%d.%m.%Y", tm_ptr);
    strftime(start_time, sizeof(start_time), "%H:%M", tm_ptr);

    /* ------------------------------------------------------------------- * 
     * Start the HTML output                                               *
     * ------------------------------------------------------------------- */
    /* define the CGI title */
    snprintf(title, sizeof(title), "Router Session Activity by Time");
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");

    fprintf(cgiOut, "<form action=\"router-acttime.cgi\" method=\"get\">\n");
    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    /* 1st row, display headers */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">Router</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Time Frame</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Order By</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Sort Order</th>\n");
    /* 2nd row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">From:</td>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 3rd row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<input type=text size=10 name=start_date value=\"%s\">",start_date);
    fprintf(cgiOut, "<input type=text size=5 name=start_time value=\"%s\">",start_time);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"asc\" checked name=\"sort_order\">");
    fprintf(cgiOut, "Ascending</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 4th row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<select name=\"router\" size=\"1\">");
    /* fetch the data */
#ifdef ORACLE_DB
    while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
      /* get one record */
      values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
   while((values = mysql_fetch_row(result)) != NULL) {
#endif
      fprintf(cgiOut, "<option value=\"%s\">%s</option>",values[0],values[0]);
    }
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">To:</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<select name=\"order_by\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"username\">User Name</option>");
    fprintf(cgiOut, "<option value=\"service\">Service</option>");
    fprintf(cgiOut, "<option value=\"ip_or_phone\">IP or Phone</option>");
    fprintf(cgiOut, "<option selected value=\"start_date\">Start Date</option>");
    fprintf(cgiOut, "<option value=\"stop_date\">Stop Date</option>");
    fprintf(cgiOut, "<option value=\"elapsed_mins\">Elapsed Time</option>");
    fprintf(cgiOut, "<option value=\"tty\">TTY</option>");
    fprintf(cgiOut, "<option value=\"bytes_in\">Bytes In</option>");
    fprintf(cgiOut, "<option value=\"bytes_out\">Bytes Out</option>");
    fprintf(cgiOut, "<option value=\"packets_in\">Packets In</option>");
    fprintf(cgiOut, "<option value=\"packets_out\">Packets Out</option>");
    fprintf(cgiOut, "<option value=\"throughput\">Throughput</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio name=\"sort_order\" value=\"desc\">Descending</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 5th row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<input type=text size=10 name=\"end_date\" value=\"%s\">", end_date);
    fprintf(cgiOut, "<input type=text size=5 name=\"end_time\" value=\"%s\"><br>&nbsp;</td>", end_time);
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 6th and last row, close the frame */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=4><input type=submit value=\"Run Query\"></th>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
    fprintf(cgiOut, "</form>\n");

    fprintf(cgiOut, "<h3>Additional Information</h3>\n");
    fprintf(cgiOut, "<hr>\n");
    fprintf(cgiOut, "<p>");
    fprintf(cgiOut, "This query returns the list of user sessions on the selected router for a given time period.");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>Select the router from the drop down list. If unsure, see <a href=\"router-list.cgi\">List of Routers</a> for more information.");
    fprintf(cgiOut, "<li>The time frame can be adjusted by typing directly into it, using the DD.MM.YYYY HH:MM format.");
    fprintf(cgiOut, "<li>Choosing a large time frame can result in a long query and a very large result set (thousands of rows).");
    fprintf(cgiOut, "<li>The results list can be ordered using criteria from the \"Order By\" drop down list.");
    fprintf(cgiOut, "</ul>\n");
    fprintf(cgiOut, "</p>\n");

    pageside();
  } /* end if for displaying the query request */
  else {
    /* ------------------------------------------------------------------- *
     * check if we got all information to make the SQL query               *
     * --------------------------------------------------------------------*/
    if ( cgiFormString("router", router, sizeof(router)) != cgiFormSuccess )
Exemple #27
0
static int mysql_read (user_data_t *ud)
{
	mysql_database_t *db;
	MYSQL     *con;
	MYSQL_RES *res;
	MYSQL_ROW  row;
	char      *query;

	derive_t qcache_hits          = 0;
	derive_t qcache_inserts       = 0;
	derive_t qcache_not_cached    = 0;
	derive_t qcache_lowmem_prunes = 0;
	gauge_t qcache_queries_in_cache = NAN;

	gauge_t threads_running   = NAN;
	gauge_t threads_connected = NAN;
	gauge_t threads_cached    = NAN;
	derive_t threads_created = 0;

	unsigned long long traffic_incoming = 0ULL;
	unsigned long long traffic_outgoing = 0ULL;

	if ((ud == NULL) || (ud->data == NULL))
	{
		ERROR ("mysql plugin: mysql_database_read: Invalid user data.");
		return (-1);
	}

	db = (mysql_database_t *) ud->data;

	/* An error message will have been printed in this case */
	if ((con = getconnection (db)) == NULL)
		return (-1);

	query = "SHOW STATUS";
	if (mysql_get_server_version (con) >= 50002)
		query = "SHOW GLOBAL STATUS";

	res = exec_query (con, query);
	if (res == NULL)
		return (-1);

	while ((row = mysql_fetch_row (res)))
	{
		char *key;
		unsigned long long val;

		key = row[0];
		val = atoll (row[1]);

		if (strncmp (key, "Com_", 
			          strlen ("Com_")) == 0)
		{
			if (val == 0ULL)
				continue;

			/* Ignore `prepared statements' */
			if (strncmp (key, "Com_stmt_", strlen ("Com_stmt_")) != 0)
				counter_submit ("mysql_commands", 
						key + strlen ("Com_"), 
						val, db);
		}
		else if (strncmp (key, "Handler_", 
				        strlen ("Handler_")) == 0)
		{
			if (val == 0ULL)
				continue;

			counter_submit ("mysql_handler", 
					key + strlen ("Handler_"), 
					val, db);
		}
		else if (strncmp (key, "Qcache_",
       				        strlen ("Qcache_")) == 0)
		{
			if (strcmp (key, "Qcache_hits") == 0)
				qcache_hits = (derive_t) val;
			else if (strcmp (key, "Qcache_inserts") == 0)
				qcache_inserts = (derive_t) val;
			else if (strcmp (key, "Qcache_not_cached") == 0)
				qcache_not_cached = (derive_t) val;
			else if (strcmp (key, "Qcache_lowmem_prunes") == 0)
				qcache_lowmem_prunes = (derive_t) val;
			else if (strcmp (key, "Qcache_queries_in_cache") == 0)
				qcache_queries_in_cache = (gauge_t) val;
		}
		else if (strncmp (key, "Bytes_", 
				        strlen ("Bytes_")) == 0)
		{
			if (strcmp (key, "Bytes_received") == 0)
				traffic_incoming += val;
			else if (strcmp (key, "Bytes_sent") == 0)
				traffic_outgoing += val;
		}
		else if (strncmp (key, "Threads_", 
       				        strlen ("Threads_")) == 0)
		{
			if (strcmp (key, "Threads_running") == 0)
				threads_running = (gauge_t) val;
			else if (strcmp (key, "Threads_connected") == 0)
				threads_connected = (gauge_t) val;
			else if (strcmp (key, "Threads_cached") == 0)
				threads_cached = (gauge_t) val;
			else if (strcmp (key, "Threads_created") == 0)
				threads_created = (derive_t) val;
		}
		else if (strncmp (key, "Table_locks_",
					strlen ("Table_locks_")) == 0)
		{
			counter_submit ("mysql_locks",
					key + strlen ("Table_locks_"),
					val, db);
		}
	}
	mysql_free_result (res); res = NULL;

	if ((qcache_hits != 0)
			|| (qcache_inserts != 0)
			|| (qcache_not_cached != 0)
			|| (qcache_lowmem_prunes != 0))
	{
		derive_submit ("cache_result", "qcache-hits",
				qcache_hits, db);
		derive_submit ("cache_result", "qcache-inserts",
				qcache_inserts, db);
		derive_submit ("cache_result", "qcache-not_cached",
				qcache_not_cached, db);
		derive_submit ("cache_result", "qcache-prunes",
				qcache_lowmem_prunes, db);

		gauge_submit ("cache_size", "qcache",
				qcache_queries_in_cache, db);
	}

	if (threads_created != 0)
	{
		gauge_submit ("threads", "running",
				threads_running, db);
		gauge_submit ("threads", "connected",
				threads_connected, db);
		gauge_submit ("threads", "cached",
				threads_cached, db);

		derive_submit ("total_threads", "created",
				threads_created, db);
	}

	traffic_submit  (traffic_incoming, traffic_outgoing, db);

	if (db->master_stats)
		mysql_read_master_stats (db, con);

	if ((db->slave_stats) || (db->slave_notif))
		mysql_read_slave_stats (db, con);

	return (0);
} /* int mysql_read */
Exemple #28
0
/**
Connect to the server with options given by arguments to this application,
stored in global variables opt_host, opt_user, opt_password, opt_db, 
opt_port and opt_unix_socket.

@param flag[in]           client_flag passed on to mysql_real_connect
@param protocol[in]       MYSQL_PROTOCOL_* to use for this connection
@param auto_reconnect[in] set to 1 for auto reconnect
   
@return pointer to initialized and connected MYSQL object
*/
static MYSQL* client_connect(ulong flag, uint protocol, my_bool auto_reconnect)
{
 MYSQL* mysql;
 int  rc;
 static char query[MAX_TEST_QUERY_LENGTH];
 myheader_r("client_connect");

 if (!opt_silent)
 fprintf(stdout, "\n Establishing a connection to '%s' ...",
 opt_host ? opt_host : "");

 if (!(mysql= mysql_client_init(NULL)))
 {
   opt_silent= 0;
   myerror("mysql_client_init() failed");
   exit(1);
 }
 /* enable local infile, in non-binary builds often disabled by default */
 mysql_options(mysql, MYSQL_OPT_LOCAL_INFILE, 0);
 mysql_options(mysql, MYSQL_OPT_PROTOCOL, &protocol);
 if (opt_plugin_dir && *opt_plugin_dir)
 mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);

 if (opt_default_auth && *opt_default_auth)
 mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);

 if (!(mysql_real_connect(mysql, opt_host, opt_user,
 opt_password, opt_db ? opt_db:"test", opt_port,
 opt_unix_socket, flag)))
 {
   opt_silent= 0;
   myerror("connection failed");
   mysql_close(mysql);
   fprintf(stdout, "\n Check the connection options using --help or -?\n");
   exit(1);
 }
 mysql->reconnect= auto_reconnect;

 if (!opt_silent)
 fprintf(stdout, "OK");

 /* set AUTOCOMMIT to ON*/
 mysql_autocommit(mysql, TRUE);

 if (!opt_silent)
 {
   fprintf(stdout, "\nConnected to MySQL server version: %s (%lu)\n",
   mysql_get_server_info(mysql),
   (ulong) mysql_get_server_version(mysql));
   fprintf(stdout, "\n Creating a test database '%s' ...", current_db);
 }
 strxmov(query, "CREATE DATABASE IF NOT EXISTS ", current_db, NullS);

 rc= mysql_query(mysql, query);
 myquery(rc);

 strxmov(query, "USE ", current_db, NullS);
 rc= mysql_query(mysql, query);
 myquery(rc);
 have_innodb= check_have_innodb(mysql);

 if (!opt_silent)
 fprintf(stdout, "OK");

 return mysql;
}
Exemple #29
0
bool MySQLConnection::Open()
{
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog->outError("Could not initialize Mysql connection to database `%s`", m_connectionInfo.database.c_str());
        return false;
    }

    int port;
    char const* unix_socket;

    mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
    #ifdef _WIN32
    if (m_connectionInfo.host == ".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(m_connectionInfo.port_or_socket.c_str());
        unix_socket = 0;
    }
    #else
    if (m_connectionInfo.host == ".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        m_connectionInfo.host = "localhost";
        port = 0;
        unix_socket = m_connectionInfo.port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(m_connectionInfo.port_or_socket.c_str());
        unix_socket = 0;
    }
    #endif

    m_Mysql = mysql_real_connect(mysqlInit, m_connectionInfo.host.c_str(), m_connectionInfo.user.c_str(),
        m_connectionInfo.password.c_str(), m_connectionInfo.database.c_str(), port, unix_socket, 0);

    if (m_Mysql)
    {
        if (!m_reconnecting)
        {
            sLog->outSQLDriver("MySQL client library: %s", mysql_get_client_info());
            sLog->outSQLDriver("MySQL server ver: %s ", mysql_get_server_info(m_Mysql));
            if (mysql_get_server_version(m_Mysql) != mysql_get_client_version())
                sLog->outSQLDriver("[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements.");
        }

        sLog->outDetail("Connected to MySQL database at %s", m_connectionInfo.host.c_str());
        mysql_autocommit(m_Mysql, 1);

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        mysql_set_character_set(m_Mysql, "utf8");
        return true;
    }
    else
    {
        sLog->outError("Could not connect to MySQL database at %s: %s\n", m_connectionInfo.host.c_str(), mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemple #30
0
static int mysql_read (user_data_t *ud)
{
    mysql_database_t *db;
    MYSQL      *con;
    MYSQL_RES  *res;
    MYSQL_ROW   row;
    const char *query;

    derive_t qcache_hits          = 0;
    derive_t qcache_inserts       = 0;
    derive_t qcache_not_cached    = 0;
    derive_t qcache_lowmem_prunes = 0;
    gauge_t qcache_queries_in_cache = NAN;

    gauge_t threads_running   = NAN;
    gauge_t threads_connected = NAN;
    gauge_t threads_cached    = NAN;
    derive_t threads_created = 0;

    unsigned long long traffic_incoming = 0ULL;
    unsigned long long traffic_outgoing = 0ULL;
    unsigned long mysql_version = 0ULL;

    if ((ud == NULL) || (ud->data == NULL))
    {
        ERROR ("mysql plugin: mysql_database_read: Invalid user data.");
        return (-1);
    }

    db = (mysql_database_t *) ud->data;

    /* An error message will have been printed in this case */
    if ((con = getconnection (db)) == NULL)
        return (-1);

    mysql_version = mysql_get_server_version(con);

    query = "SHOW STATUS";
    if (mysql_version >= 50002)
        query = "SHOW GLOBAL STATUS";

    res = exec_query (con, query);
    if (res == NULL)
        return (-1);

    while ((row = mysql_fetch_row (res)))
    {
        char *key;
        unsigned long long val;

        key = row[0];
        val = atoll (row[1]);

        if (strncmp (key, "Com_",
                     strlen ("Com_")) == 0)
        {
            if (val == 0ULL)
                continue;

            /* Ignore `prepared statements' */
            if (strncmp (key, "Com_stmt_", strlen ("Com_stmt_")) != 0)
                counter_submit ("mysql_commands",
                                key + strlen ("Com_"),
                                val, db);
        }
        else if (strncmp (key, "Handler_",
                          strlen ("Handler_")) == 0)
        {
            if (val == 0ULL)
                continue;

            counter_submit ("mysql_handler",
                            key + strlen ("Handler_"),
                            val, db);
        }
        else if (strncmp (key, "Qcache_",
                          strlen ("Qcache_")) == 0)
        {
            if (strcmp (key, "Qcache_hits") == 0)
                qcache_hits = (derive_t) val;
            else if (strcmp (key, "Qcache_inserts") == 0)
                qcache_inserts = (derive_t) val;
            else if (strcmp (key, "Qcache_not_cached") == 0)
                qcache_not_cached = (derive_t) val;
            else if (strcmp (key, "Qcache_lowmem_prunes") == 0)
                qcache_lowmem_prunes = (derive_t) val;
            else if (strcmp (key, "Qcache_queries_in_cache") == 0)
                qcache_queries_in_cache = (gauge_t) val;
        }
        else if (strncmp (key, "Bytes_",
                          strlen ("Bytes_")) == 0)
        {
            if (strcmp (key, "Bytes_received") == 0)
                traffic_incoming += val;
            else if (strcmp (key, "Bytes_sent") == 0)
                traffic_outgoing += val;
        }
        else if (strncmp (key, "Threads_",
                          strlen ("Threads_")) == 0)
        {
            if (strcmp (key, "Threads_running") == 0)
                threads_running = (gauge_t) val;
            else if (strcmp (key, "Threads_connected") == 0)
                threads_connected = (gauge_t) val;
            else if (strcmp (key, "Threads_cached") == 0)
                threads_cached = (gauge_t) val;
            else if (strcmp (key, "Threads_created") == 0)
                threads_created = (derive_t) val;
        }
        else if (strncmp (key, "Table_locks_",
                          strlen ("Table_locks_")) == 0)
        {
            counter_submit ("mysql_locks",
                            key + strlen ("Table_locks_"),
                            val, db);
        }
        else if (db->innodb_stats && strncmp (key, "Innodb_", strlen ("Innodb_")) == 0)
        {
            /* buffer pool */
            if (strcmp (key, "Innodb_buffer_pool_pages_data") == 0)
                gauge_submit ("mysql_bpool_pages", "data", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_pages_dirty") == 0)
                gauge_submit ("mysql_bpool_pages", "dirty", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_pages_flushed") == 0)
                counter_submit ("mysql_bpool_counters", "pages_flushed", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_pages_free") == 0)
                gauge_submit ("mysql_bpool_pages", "free", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_pages_misc") == 0)
                gauge_submit ("mysql_bpool_pages", "misc", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_pages_total") == 0)
                gauge_submit ("mysql_bpool_pages", "total", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_read_ahead_rnd") == 0)
                counter_submit ("mysql_bpool_counters", "read_ahead_rnd", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_read_ahead") == 0)
                counter_submit ("mysql_bpool_counters", "read_ahead", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_read_ahead_evicted") == 0)
                counter_submit ("mysql_bpool_counters", "read_ahead_evicted", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_read_requests") == 0)
                counter_submit ("mysql_bpool_counters", "read_requests", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_reads") == 0)
                counter_submit ("mysql_bpool_counters", "reads", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_write_requests") == 0)
                counter_submit ("mysql_bpool_counters", "write_requests", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_bytes_data") == 0)
                gauge_submit ("mysql_bpool_bytes", "data", val, db);
            else if (strcmp (key, "Innodb_buffer_pool_bytes_dirty") == 0)
                gauge_submit ("mysql_bpool_bytes", "dirty", val, db);

            /* data */
            if (strcmp (key, "Innodb_data_fsyncs") == 0)
                counter_submit ("mysql_innodb_data", "fsyncs", val, db);
            else if (strcmp (key, "Innodb_data_read") == 0)
                counter_submit ("mysql_innodb_data", "read", val, db);
            else if (strcmp (key, "Innodb_data_reads") == 0)
                counter_submit ("mysql_innodb_data", "reads", val, db);
            else if (strcmp (key, "Innodb_data_writes") == 0)
                counter_submit ("mysql_innodb_data", "writes", val, db);
            else if (strcmp (key, "Innodb_data_written") == 0)
                counter_submit ("mysql_innodb_data", "written", val, db);

            /* double write */
            else if (strcmp (key, "Innodb_dblwr_writes") == 0)
                counter_submit ("mysql_innodb_dblwr", "writes", val, db);
            else if (strcmp (key, "Innodb_dblwr_pages_written") == 0)
                counter_submit ("mysql_innodb_dblwr", "written", val, db);

            /* log */
            else if (strcmp (key, "Innodb_log_waits") == 0)
                counter_submit ("mysql_innodb_log", "waits", val, db);
            else if (strcmp (key, "Innodb_log_write_requests") == 0)
                counter_submit ("mysql_innodb_log", "write_requests", val, db);
            else if (strcmp (key, "Innodb_log_writes") == 0)
                counter_submit ("mysql_innodb_log", "writes", val, db);
            else if (strcmp (key, "Innodb_os_log_fsyncs") == 0)
                counter_submit ("mysql_innodb_log", "fsyncs", val, db);
            else if (strcmp (key, "Innodb_os_log_written") == 0)
                counter_submit ("mysql_innodb_log", "written", val, db);

            /* pages */
            else if (strcmp (key, "Innodb_pages_created") == 0)
                counter_submit ("mysql_innodb_pages", "created", val, db);
            else if (strcmp (key, "Innodb_pages_read") == 0)
                counter_submit ("mysql_innodb_pages", "read", val, db);
            else if (strcmp (key, "Innodb_pages_written") == 0)
                counter_submit ("mysql_innodb_pages", "written", val, db);

            /* row lock */
            else if (strcmp (key, "Innodb_row_lock_time") == 0)
                counter_submit ("mysql_innodb_row_lock", "time", val, db);
            else if (strcmp (key, "Innodb_row_lock_waits") == 0)
                counter_submit ("mysql_innodb_row_lock", "waits", val, db);

            /* rows */
            else if (strcmp (key, "Innodb_rows_deleted") == 0)
                counter_submit ("mysql_innodb_rows", "deleted", val, db);
            else if (strcmp (key, "Innodb_rows_inserted") == 0)
                counter_submit ("mysql_innodb_rows", "inserted", val, db);
            else if (strcmp (key, "Innodb_rows_read") == 0)
                counter_submit ("mysql_innodb_rows", "read", val, db);
            else if (strcmp (key, "Innodb_rows_updated") == 0)
                counter_submit ("mysql_innodb_rows", "updated", val, db);
        }
        else if (strncmp (key, "Select_", strlen ("Select_")) == 0)
        {
            counter_submit ("mysql_select", key + strlen ("Select_"),
                            val, db);
        }
        else if (strncmp (key, "Sort_", strlen ("Sort_")) == 0)
        {
            if (strcmp (key, "Sort_merge_passes") == 0)
                counter_submit ("mysql_sort_merge_passes", NULL, val, db);
            else if (strcmp (key, "Sort_rows") == 0)
                counter_submit ("mysql_sort_rows", NULL, val, db);
            else if (strcmp (key, "Sort_range") == 0)
                counter_submit ("mysql_sort", "range", val, db);
            else if (strcmp (key, "Sort_scan") == 0)
                counter_submit ("mysql_sort", "scan", val, db);

        }
        else if (strncmp (key, "Slow_queries", strlen ("Slow_queries")) == 0)
        {
            counter_submit ("mysql_slow_queries", NULL , val, db);
        }
    }
    mysql_free_result (res);
    res = NULL;

    if ((qcache_hits != 0)
            || (qcache_inserts != 0)
            || (qcache_not_cached != 0)
            || (qcache_lowmem_prunes != 0))
    {
        derive_submit ("cache_result", "qcache-hits",
                       qcache_hits, db);
        derive_submit ("cache_result", "qcache-inserts",
                       qcache_inserts, db);
        derive_submit ("cache_result", "qcache-not_cached",
                       qcache_not_cached, db);
        derive_submit ("cache_result", "qcache-prunes",
                       qcache_lowmem_prunes, db);

        gauge_submit ("cache_size", "qcache",
                      qcache_queries_in_cache, db);
    }

    if (threads_created != 0)
    {
        gauge_submit ("threads", "running",
                      threads_running, db);
        gauge_submit ("threads", "connected",
                      threads_connected, db);
        gauge_submit ("threads", "cached",
                      threads_cached, db);

        derive_submit ("total_threads", "created",
                       threads_created, db);
    }

    traffic_submit  (traffic_incoming, traffic_outgoing, db);

    if (mysql_version >= 50600 && db->innodb_stats)
        mysql_read_innodb_stats (db, con);

    if (db->master_stats)
        mysql_read_master_stats (db, con);

    if ((db->slave_stats) || (db->slave_notif))
        mysql_read_slave_stats (db, con);

    if (db->wsrep_stats)
        mysql_read_wsrep_stats (db, con);

    return (0);
} /* int mysql_read */