示例#1
0
static int
cmyth_db_check_connection(cmyth_database_t db)
{
    int new_conn = 0;
    if(db->mysql != NULL)
    {
	/* Fetch the mysql stats (uptime and stuff) to check the connection is
	 * still good
	 */
	if(mysql_stat(db->mysql) == NULL)
	{
	    cmyth_database_close(db);
	}
    }
    if(db->mysql == NULL)
    {
	db->mysql = mysql_init(NULL);
	new_conn = 1;
	if(db->mysql == NULL)
	{
	    fprintf(stderr,"%s: mysql_init() failed, insufficient memory?",
		    __FUNCTION__);
	    return -1;
	}
	if(NULL == mysql_real_connect(db->mysql,
		    db->db_host,db->db_user,db->db_pass,db->db_name,0,NULL,0))
	{
	    fprintf(stderr,"%s: mysql_connect() failed: %s", __FUNCTION__,
		    mysql_error(db->mysql));
	    cmyth_database_close(db);
	    return -1;
	}
    }
    return 0;
}
示例#2
0
/* {{{ property link_stat_read */
static zval *link_stat_read(mysqli_object *obj, zval *retval)
{
	MY_MYSQL *mysql;

	ZVAL_NULL(retval);

#if defined(MYSQLI_USE_MYSQLND)
	CHECK_STATUS(MYSQLI_STATUS_INITIALIZED);
#else
	CHECK_STATUS(MYSQLI_STATUS_VALID);
#endif

 	mysql = (MY_MYSQL *)((MYSQLI_RESOURCE *)(obj->ptr))->ptr;

	if (mysql) {
#if defined(MYSQLI_USE_MYSQLND)
		zend_string * stat_msg;
		if (mysqlnd_stat(mysql->mysql, &stat_msg) == PASS) {
			ZVAL_STR(retval, stat_msg);
		}
#else
		char * stat_msg;
		if ((stat_msg = (char *)mysql_stat(mysql->mysql))) {
			ZVAL_STRING(retval, stat_msg);
		}
#endif
	}
	return retval;
}
示例#3
0
int
cmyth_mysql_testdb_connection(cmyth_database_t db,char **message) {
	char buf[1000];
	int new_conn = 0;
	if (db->mysql != NULL) {
		if (mysql_stat(db->mysql) == NULL) {
			cmyth_database_close(db);
			return -1;
			}
	}
	if (db->mysql == NULL) {
		db->mysql = mysql_init(NULL);
		new_conn = 1;
		if(db->mysql == NULL) {
			fprintf(stderr,"%s: mysql_init() failed, insufficient memory?", __FUNCTION__);
			snprintf(buf, sizeof(buf), "mysql_init() failed, insufficient memory?");
			*message=buf;
			return -1;
		}
		if (NULL == mysql_real_connect(db->mysql, db->db_host,db->db_user,db->db_pass,db->db_name,0,NULL,0)) {
			fprintf(stderr,"%s: mysql_connect() failed: %s\n", __FUNCTION__,
			mysql_error(db->mysql));
			snprintf(buf, sizeof(buf), "%s",mysql_error(db->mysql));
			fprintf (stderr,"buf = %s\n",buf);
			*message=buf;
			cmyth_database_close(db);
			return -1;
		}
	}
	snprintf(buf, sizeof(buf), "All Test Successful\n");
	*message=buf;
	return 1;
}
示例#4
0
/*	stat()		*/
static VALUE my_stat(VALUE obj)
{
    MYSQL* m = GetHandler(obj);
    const char* s = mysql_stat(m);
    if (s == NULL)
	mysql_raise(m);
    return rb_tainted_str_new2(s);
}
char const* Connection::GetStatus()
{
    char const* RetVal = mysql_stat(MySQL);
    if (!RetVal)
    {
        ShowMySQLError(MySQL, "mysql_stat()");
    }

    return RetVal;
}
示例#6
0
文件: connection.c 项目: kepkin/wsql
static PyObject* wsql_connection_get_stat(wsql_connection *self, void* closure)
{
    const char *s;
    CHECK_CONNECTION(self, NULL);
    Py_BEGIN_ALLOW_THREADS
    s = mysql_stat(&(self->connection));
    Py_END_ALLOW_THREADS
    if (!s)
        return wsql_raise_error(self);

    return PyString_FromString(s);
}
示例#7
0
void AMySQLServer::emit(AXmlElement& target) const
{
  if (target.useName().isEmpty())
    target.useName().assign("AMySQLServer", 12);

  ADatabase::emitXml(target);

  target.addElement(ASW("client",6)).addData(mysql_get_client_info());
  if (mp_mydata)
  {
    target.addElement(ASW("stat",4)).addData(mysql_stat(mp_mydata)); 
    target.addElement(ASW("server",6)).addData(mysql_get_server_info(mp_mydata)); 
    target.addElement(ASW("host",4)).addData(mysql_get_host_info(mp_mydata)); 
  }
}
示例#8
0
static void my_MySQLstatus(RESULT * result)
{
    const char *value = "";
    const char *status;

    if (configure_mysql() > 0) {

	mysql_ping(&conex);
	status = mysql_stat(&conex);
	if (!status) {
	    error("[MySQL] status error: %s", mysql_error(&conex));
	    value = "error";
	} else {
	    value = status;
	}
    }

    SetResult(&result, R_STRING, value);
}
示例#9
0
void AMySQLServer::debugDump(std::ostream& os, int indent) const
{
  ADebugDumpable::indent(os, indent) << "(" << typeid(*this).name() << " @ " << std::hex << this << std::dec << ") {" << std::endl;
  ADebugDumpable::indent(os, indent+1) << "m_urlConnection=" << std::endl;
  m_urlConnection.debugDump(os,indent+2);
  
  ADebugDumpable::indent(os, indent+1) << "client: " << mysql_get_client_info() << std::endl;
  
  if (mbool_Initialized && mp_mydata)
  {
    ADebugDumpable::indent(os, indent+1) << mysql_stat(mp_mydata) << std::endl;
    ADebugDumpable::indent(os, indent+1) << "server: " << mysql_get_server_info(mp_mydata) << std::endl;
    ADebugDumpable::indent(os, indent+1) << "host  : " << mysql_get_host_info(mp_mydata) << std::endl;
    ADebugDumpable::indent(os, indent+1) << "mp_mydata=0x" << std::hex << (void*)mp_mydata << std::dec << std::endl;
  }
  else
    ADebugDumpable::indent(os, indent+1) << "mp_mydata=NULL" << std::endl;

  ADebugDumpable::indent(os, indent) << "}" << std::endl;
}
示例#10
0
/* {{{ pdo_mysql_get_attribute */
static int pdo_mysql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;

	PDO_DBG_ENTER("pdo_mysql_get_attribute");
	PDO_DBG_INF_FMT("dbh=%p", dbh);
	PDO_DBG_INF_FMT("attr=%l", attr);
	switch (attr) {
		case PDO_ATTR_CLIENT_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_client_info());
			break;

		case PDO_ATTR_SERVER_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_server_info(H->server));
			break;

		case PDO_ATTR_CONNECTION_STATUS:
			ZVAL_STRING(return_value, (char *)mysql_get_host_info(H->server));
			break;
		case PDO_ATTR_SERVER_INFO: {
#if defined(PDO_USE_MYSQLND)
			zend_string *tmp;

			if (mysqlnd_stat(H->server, &tmp) == PASS) {
				ZVAL_STR(return_value, tmp);
#else
			char *tmp;
			if ((tmp = (char *)mysql_stat(H->server))) {
				ZVAL_STRING(return_value, tmp);
#endif
			} else {
				pdo_mysql_error(dbh);
				PDO_DBG_RETURN(-1);
			}
		}
			break;

		case PDO_ATTR_AUTOCOMMIT:
			ZVAL_LONG(return_value, dbh->auto_commit);
			break;

		case PDO_ATTR_DEFAULT_STR_PARAM:
			ZVAL_LONG(return_value, H->assume_national_character_set_strings ? PDO_PARAM_STR_NATL : PDO_PARAM_STR_CHAR);
			break;

		case PDO_MYSQL_ATTR_USE_BUFFERED_QUERY:
			ZVAL_LONG(return_value, H->buffered);
			break;

		case PDO_ATTR_EMULATE_PREPARES:
		case PDO_MYSQL_ATTR_DIRECT_QUERY:
			ZVAL_LONG(return_value, H->emulate_prepare);
			break;

#ifndef PDO_USE_MYSQLND
		case PDO_MYSQL_ATTR_MAX_BUFFER_SIZE:
			ZVAL_LONG(return_value, H->max_buffer_size);
			break;
#endif

		default:
			PDO_DBG_RETURN(0);
	}

	PDO_DBG_RETURN(1);
}
/* }}} */

/* {{{ pdo_mysql_check_liveness */
static int pdo_mysql_check_liveness(pdo_dbh_t *dbh)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;

	PDO_DBG_ENTER("pdo_mysql_check_liveness");
	PDO_DBG_INF_FMT("dbh=%p", dbh);

	if (mysql_ping(H->server)) {
		PDO_DBG_RETURN(FAILURE);
	}
	PDO_DBG_RETURN(SUCCESS);
}
示例#11
0
static int test_status(MYSQL *mysql)
{
  mysql_stat(mysql);
  check_mysql_rc(mysql_errno(mysql), mysql);
  return OK;
}
示例#12
0
int
main (int argc, char **argv)
{

	MYSQL mysql;
	MYSQL_RES *res;
	MYSQL_ROW row;

	/* should be status */

	char *result = NULL;
	char *error = NULL;
	char slaveresult[SLAVERESULTSIZE];

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	/* initialize mysql  */
	mysql_init (&mysql);
	
	if (opt_file != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);

	if (opt_group != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
	else
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");

	/* establish a connection to the server and error checking */
	if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,db_socket,0)) {
		if (mysql_errno (&mysql) == CR_UNKNOWN_HOST)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_VERSION_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	/* get the server stats */
	result = strdup (mysql_stat (&mysql));

	/* error checking once more */
	if (mysql_error (&mysql)) {
		if (mysql_errno (&mysql) == CR_SERVER_GONE_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SERVER_LOST)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_UNKNOWN_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	if(check_slave) {
		/* check the slave status */
		if (mysql_query (&mysql, "show slave status") != 0) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave query error: %s\n"), error);
		}

		/* store the result */
		if ( (res = mysql_store_result (&mysql)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave store_result error: %s\n"), error);
		}

		/* Check there is some data */
		if (mysql_num_rows(res) == 0) {
			mysql_close(&mysql);
			die (STATE_WARNING, "%s\n", _("No slaves defined"));
		}

		/* fetch the first row */
		if ( (row = mysql_fetch_row (res)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_free_result (res);
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave fetch row error: %s\n"), error);
		}

		if (mysql_field_count (&mysql) == 12) {
			/* mysql 3.23.x */
			snprintf (slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
			if (strcmp (row[6], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

		} else {
			/* mysql 4.x.x */
			int slave_io_field = -1 , slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
			MYSQL_FIELD* fields;

			num_fields = mysql_num_fields(res);
			fields = mysql_fetch_fields(res);
			for(i = 0; i < num_fields; i++) {
				if (strcmp(fields[i].name, "Slave_IO_Running") == 0) {
					slave_io_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Slave_SQL_Running") == 0) {
					slave_sql_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Seconds_Behind_Master") == 0) {
					seconds_behind_field = i;
					continue;
				}
			}

			if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "Slave status unavailable\n");
			}

			snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");
			if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

			if (verbose >=3) {
				if (seconds_behind_field == -1) {
					printf("seconds_behind_field not found\n");
				} else {
					printf ("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]);
				}
			}

			if ((seconds_behind_field != -1) && (strcmp (row[seconds_behind_field], "NULL") != 0)) {
				double value = atof(row[seconds_behind_field]);
				int status;

				status = get_status(value, my_threshold);

				if (status == STATE_WARNING) {
					printf("SLOW_SLAVE %s: %s\n", _("WARNING"), slaveresult);
					exit(STATE_WARNING);
				} else if (status == STATE_CRITICAL) {
					printf("SLOW_SLAVE %s: %s\n", _("CRITICAL"), slaveresult);
					exit(STATE_CRITICAL);
				}
			}
		}

		/* free the result */
		mysql_free_result (res);
	}

	/* close the connection */
	mysql_close (&mysql);

	/* print out the result of stats */
	if (check_slave) {
		printf ("%s %s\n", result, slaveresult);
	} else {
		printf ("%s\n", result);
	}

	return STATE_OK;
}
示例#13
0
BOOL MySQL(const char * strParas, char * szReturn, int& nSize)
//(CStringList &paramList, char *szReturn)
{
    BOOL bRet = TRUE;

    CString strHost = _T(""), //MySqL Server
        //strDBName = _T("mysql"),//Database Name,default mysql
        strUser = _T(""), //UserName
        strPwd = _T("");// Password
    int nPort = 3306;//MySQL Server Port,default 3306
/////////////////////////////////////////////////////////////////////////////
    const  char   *pszT;//Temp string
    MYSQL		* myData ;//Access Mysql objcect
/////////////////////////////////////////////////////////////////////////////
	CStringList paramList;
	MakeStringListByChar(paramList,strParas);

    POSITION pos = paramList.GetHeadPosition();
    while(pos)
    {
        CString strTemp = paramList.GetNext(pos);
		if(strTemp.Find(__MACHINENAME__, 0) == 0)
		{//Get Host
			strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__));
		}
		else if(strTemp.Find(__PORT__, 0) == 0)
		{//Get Port
			nPort = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PORT__)));
		}
        else if(strTemp.Find(__USERACCOUNT__, 0) == 0)
		{//Get Username
			strUser = strTemp.Right(strTemp.GetLength() - (int)strlen(__USERACCOUNT__));
		}
        else if(strTemp.Find(__PASSWORD__, 0) == 0)
		{//Get password
			strPwd = strTemp.Right(strTemp.GetLength() - (int)strlen(__PASSWORD__));
		}
        /*else if(strTemp.Find(__DBNAME__, 0) == 0)
		{//Get database name
			strDBName = strTemp.Right(strTemp.GetLength() - strlen(__DBNAME__));
		}*/
    }

    if(strHost.IsEmpty())
    {//host is empty
        sprintf(szReturn, "error=%s", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_SERVER_HOST_IS_NULL"));
        return FALSE;
    }
    if(nPort <= 0)
    {//Invalid port
        sprintf(szReturn, "error=%s", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_SERVER_PORT_IS_BAD"));
        return FALSE;
    }
	printf("----------%s--%s--%s--------\n",strHost,strUser,strPwd);

    if((myData = mysql_init((MYSQL*) 0)) && 
       mysql_real_connect( myData, strHost, strUser, strPwd, NULL, nPort,
			   NULL, 0 ) )
    {
        /*if ( mysql_select_db( myData, strDBName ) < 0 ) 
        {
            sprintf(szReturn, "error=%s(%s)$", FuncGetStringFromIDS("SV_MYSQL",
                "MYSQL_SELECT_DATABASE_FAILED"), strDBName);
	        //printf( "Can't select the %s database !\n", strDBName) ;
	        mysql_close( myData ) ;
	        return FALSE;
        }*/

        pszT = mysql_stat( myData ) ;		//mysql_stat(MYSQL * myData)取得目录数据库系统状况

        if(pszT)
        {
            Parser(pszT, strHost.GetBuffer(strHost.GetLength()), szReturn);
//			mysql_free_result(pszT);
			CString strInput ;
			strInput =szReturn;
			MakeCharByString(szReturn,nSize,strInput);
				

        }
        else
        {
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("SV_MYSQL",
                "MYSQL_QUERY_STAT_FAILED"));
            mysql_close( myData ) ;
            return FALSE;
        }
    }
    else 
    {
        sprintf(szReturn, "error=%s(%s:%d)$", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_CONNECT_DATABASE_FAILED"), strHost, nPort);
        //printf( "Can't connect to the mysql server on port %d !\n",
	    //    MYSQL_PORT ) ;
		fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(myData));

        mysql_close( myData ) ;
        return FALSE;
    }
    mysql_close( myData ) ;
    return TRUE;
}
示例#14
0
/* {{{ pdo_mysql_get_attribute */
static int pdo_mysql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;

	PDO_DBG_ENTER("pdo_mysql_get_attribute");
	PDO_DBG_INF_FMT("dbh=%p", dbh);
	PDO_DBG_INF_FMT("attr=%l", attr);
	switch (attr) {
		case PDO_ATTR_CLIENT_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_client_info());
			break;

		case PDO_ATTR_SERVER_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_server_info(H->server));
			break;

		case PDO_ATTR_CONNECTION_STATUS:
			ZVAL_STRING(return_value, (char *)mysql_get_host_info(H->server));
			break;
		case PDO_ATTR_SERVER_INFO: {
#if defined(PDO_USE_MYSQLND)
			zend_string *tmp;

			if (mysqlnd_stat(H->server, &tmp) == PASS) {
				ZVAL_STR(return_value, tmp);
#else
			char *tmp;
			if ((tmp = (char *)mysql_stat(H->server))) {
				ZVAL_STRING(return_value, tmp);
#endif
			} else {
				pdo_mysql_error(dbh);
				PDO_DBG_RETURN(-1);
			}
		}
			break;
		case PDO_ATTR_AUTOCOMMIT:
			ZVAL_LONG(return_value, dbh->auto_commit);
			break;

		case PDO_MYSQL_ATTR_USE_BUFFERED_QUERY:
			ZVAL_LONG(return_value, H->buffered);
			break;

		case PDO_ATTR_EMULATE_PREPARES:
		case PDO_MYSQL_ATTR_DIRECT_QUERY:
			ZVAL_LONG(return_value, H->emulate_prepare);
			break;

#ifndef PDO_USE_MYSQLND
		case PDO_MYSQL_ATTR_MAX_BUFFER_SIZE:
			ZVAL_LONG(return_value, H->max_buffer_size);
			break;
#endif

		default:
			PDO_DBG_RETURN(0);
	}

	PDO_DBG_RETURN(1);
}
/* }}} */

/* {{{ pdo_mysql_check_liveness */
static int pdo_mysql_check_liveness(pdo_dbh_t *dbh)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;
#if MYSQL_VERSION_ID <= 32230
	void (*handler) (int);
	unsigned int my_errno;
#endif

	PDO_DBG_ENTER("pdo_mysql_check_liveness");
	PDO_DBG_INF_FMT("dbh=%p", dbh);

#if MYSQL_VERSION_ID > 32230
	if (mysql_ping(H->server)) {
		PDO_DBG_RETURN(FAILURE);
	}
#else /* no mysql_ping() */
	handler = signal(SIGPIPE, SIG_IGN);
	mysql_stat(H->server);
	switch (mysql_errno(H->server)) {
		case CR_SERVER_GONE_ERROR:
		case CR_SERVER_LOST:
			signal(SIGPIPE, handler);
			PDO_DBG_RETURN(FAILURE);
		default:
			break;
	}
	signal(SIGPIPE, handler);
#endif /* end mysql_ping() */
	PDO_DBG_RETURN(SUCCESS);
}
示例#15
0
int
main (int argc, char **argv)
{

	MYSQL mysql;
	MYSQL_RES *res;
	MYSQL_ROW row;

	/* should be status */

	char *result = NULL;
	char *error = NULL;
	char slaveresult[SLAVERESULTSIZE];
	char* perf;

        perf = strdup ("");

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	/* initialize mysql  */
	mysql_init (&mysql);
	
	if (opt_file != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);

	if (opt_group != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
	else
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");

	if (ssl)
		mysql_ssl_set(&mysql,key,cert,ca_cert,ca_dir,ciphers);
	/* establish a connection to the server and error checking */
	if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,db_socket,0)) {
		if (mysql_errno (&mysql) == CR_UNKNOWN_HOST)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_VERSION_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	/* get the server stats */
	result = strdup (mysql_stat (&mysql));

	/* error checking once more */
	if (mysql_error (&mysql)) {
		if (mysql_errno (&mysql) == CR_SERVER_GONE_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SERVER_LOST)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_UNKNOWN_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	/* try to fetch some perf data */
	if (mysql_query (&mysql, "show global status") == 0) {
		if ( (res = mysql_store_result (&mysql)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("status store_result error: %s\n"), error);
		}

		while ( (row = mysql_fetch_row (res)) != NULL) {
			int i;

			for(i = 0; i < LENGTH_METRIC_UNIT; i++) {
				if (strcmp(row[0], metric_unit[i]) == 0) {
					xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i],
						atol(row[1]), "", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
					continue;
				}
			}
			for(i = 0; i < LENGTH_METRIC_COUNTER; i++) {
				if (strcmp(row[0], metric_counter[i]) == 0) {
					xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i],
						atol(row[1]), "c", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
					continue;
				}
			}
		}
		/* remove trailing space */
                if (strlen(perf) > 0)
                    perf[strlen(perf) - 1] = '\0';
	}

	if(check_slave) {
		/* check the slave status */
		if (mysql_query (&mysql, "show slave status") != 0) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave query error: %s\n"), error);
		}

		/* store the result */
		if ( (res = mysql_store_result (&mysql)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave store_result error: %s\n"), error);
		}

		/* Check there is some data */
		if (mysql_num_rows(res) == 0) {
			mysql_close(&mysql);
			die (STATE_WARNING, "%s\n", _("No slaves defined"));
		}

		/* fetch the first row */
		if ( (row = mysql_fetch_row (res)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_free_result (res);
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave fetch row error: %s\n"), error);
		}

		if (mysql_field_count (&mysql) == 12) {
			/* mysql 3.23.x */
			snprintf (slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
			if (strcmp (row[6], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

		} else {
			/* mysql 4.x.x and mysql 5.x.x */
			int slave_io_field = -1 , slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
			MYSQL_FIELD* fields;

			num_fields = mysql_num_fields(res);
			fields = mysql_fetch_fields(res);
			for(i = 0; i < num_fields; i++) {
				if (strcmp(fields[i].name, "Slave_IO_Running") == 0) {
					slave_io_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Slave_SQL_Running") == 0) {
					slave_sql_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Seconds_Behind_Master") == 0) {
					seconds_behind_field = i;
					continue;
				}
			}

			/* Check if slave status is available */
			if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "Slave status unavailable\n");
			}

			/* Save slave status in slaveresult */
			snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");

			/* Raise critical error if SQL THREAD or IO THREAD are stopped */
			if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

			if (verbose >=3) {
				if (seconds_behind_field == -1) {
					printf("seconds_behind_field not found\n");
				} else {
					printf ("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]);
				}
			}

			/* Check Seconds Behind against threshold */
			if ((seconds_behind_field != -1) && (strcmp (row[seconds_behind_field], "NULL") != 0)) {
				double value = atof(row[seconds_behind_field]);
				int status;

				status = get_status(value, my_threshold);

				xasprintf (&perf, "%s %s", perf, fperfdata ("seconds behind master", value, "s",
        	                        TRUE, (double) warning_time,
                	                TRUE, (double) critical_time,
                        	        FALSE, 0,
                                	FALSE, 0));

				if (status == STATE_WARNING) {
					printf("SLOW_SLAVE %s: %s|%s\n", _("WARNING"), slaveresult, perf);
					exit(STATE_WARNING);
				} else if (status == STATE_CRITICAL) {
					printf("SLOW_SLAVE %s: %s|%s\n", _("CRITICAL"), slaveresult, perf);
					exit(STATE_CRITICAL);
				}
			}
		}

		/* free the result */
		mysql_free_result (res);
	}

	/* close the connection */
	mysql_close (&mysql);

	/* print out the result of stats */
	if (check_slave) {
		printf ("%s %s|%s\n", result, slaveresult, perf);
	} else {
		printf ("%s|%s\n", result, perf);
	}

	return STATE_OK;
}
示例#16
0
void mexFunction(int nlhs, mxArray *plhs[],
      int nrhs, const mxArray *prhs[])
{
	int cid=-1;  // Handle of the current connection (invalid until we identify)
	int jarg=0;  // Number of first string arg: becomes 1 if id is specified

	/*********************************************************************/
	// Parse the first argument to see if it is a specific database handle
	if ( nrhs>0 && mxIsNumeric(prhs[0]) )
		{ if ( mxGetM(prhs[0])!=1 || mxGetN(prhs[0])!=1 )
			{ showusage();
			  mexPrintf("First argument is array %d x %d, but it should be a scalar\n",
			      mxGetM(prhs[0]),mxGetN(prhs[0]) );
			  mexErrMsgTxt("Invalid connection handle"); }
		  double xid = *mxGetPr(prhs[0]);
		  cid = int(xid);
		  if ( double(cid)!=xid || cid<0 || cid>=MAXCONN )
			{ showusage();
			  mexPrintf("dbHandle = %g -- Must be integer between 0 and %d\n",
			      xid,MAXCONN-1);
			  mexErrMsgTxt("Invalid connection handle"); }
		  jarg = 1;
		  if (debug) mexPrintf("| Explicit  cid = %d\n",cid); }

	/*********************************************************************/
	//  Check that the remaining arguments are all character strings
	{ for ( int j=jarg ; j<nrhs ; j++ )
		{ if (!mxIsChar(prhs[j]))
			{ showusage();
			  mexErrMsgTxt("All args must be strings, except dbHandle"); }}}

	/*********************************************************************/
	//  Identify what action he wants to do

	enum querytype { OPEN, CLOSE, CLOSEALL, USENAMED, USE,
	                     STATUS, STATSALL, QUOTE, CMD } q;
	char *query = NULL;

	if (nrhs<=jarg)   q = STATSALL;
	else
		{ query = mxArrayToString(prhs[jarg]);
		  if (streq(query,"open"))          q = OPEN;
		  else if (streq(query,"close"))    q = CLOSE;
		  else if (streq(query,"closeall")) q = CLOSEALL;
		  else if (streq(query,"use"))      q = USENAMED;
		  else if (streq(query,"use",3))    q = USE;
		  else if (streq(query,"status"))   q = STATUS;
		  else if (streq(query,"quote"))    q = QUOTE;
		  else q = CMD; }

	if (debug)
		{ switch(q)
			{ case OPEN:     mexPrintf("| q = OPEN\n");     break;
			  case CLOSE:    mexPrintf("| q = CLOSE\n");    break;
			  case CLOSEALL: mexPrintf("| q = CLOSEALL\n"); break;
			  case USENAMED: mexPrintf("| q = USENAMED\n"); break;
			  case USE:      mexPrintf("| q = USE\n");      break;
			  case STATUS:   mexPrintf("| q = STATUS\n");   break;
			  case STATSALL: mexPrintf("| q = STATSALL\n"); break;
			  case QUOTE:    mexPrintf("| q = QUOTE\n");    break;
			  case CMD:      mexPrintf("| q = CMD\n");      break;
			                 mexPrintf("| q = ??\n");              }}

	/*********************************************************************/
	//  If he did not specify the handle, choose the appropriate one
	//  If there are no previous connections, then we will still have
	//     cid=-1, and this will be handled in the appropriate place.
	if (jarg==0)
		{
		if (q==OPEN)
			{ for ( cid=0 ; cid<MAXCONN & c[cid].isopen ; cid++ );
			  if (cid>=MAXCONN) mexErrMsgTxt("Can\'t find free handle"); }
		else if (ncid>0)
			cid=prevcid[ncid-1];
		}

	if (debug) mexPrintf("| cid = %d\n",cid);

	//  Shorthand notation so we don't need to write c[cid]...
	//  These values must not be used if  cid<0
	mp dummyconn;     mp &conn = (cid>=0) ? c[cid].conn : dummyconn;
	bool dummyisopen; bool &isopen = (cid>=0) ? c[cid].isopen : dummyisopen;

	if (q==OPEN)
		{
		if (cid<0)
			{ mexPrintf("cid = %d !\n",cid);
			  mexErrMsgTxt("Internal code error\n"); }
		//  Close connection if it is open
		if (isopen)
			{ mexWarnMsgIdAndTxt("mysql:ConnectionAlreadyOpen",
			    "Connection %d has been closed and overwritten",cid);
			  mysql_close(conn);
			  conn=NULL;  isopen=false;  stackdelete(cid); }

		//  Extract information from input arguments
		char *host=NULL;   if (nrhs>=jarg+2)  host = mxArrayToString(prhs[jarg+1]);
		char *user=NULL;   if (nrhs>=jarg+3)  user = mxArrayToString(prhs[jarg+2]);
		char *pass=NULL;   if (nrhs>=jarg+4)  pass = mxArrayToString(prhs[jarg+3]);
		int port = hostport(host);  // returns zero if there is no port

		if (nlhs<1)
			{ mexPrintf("Connecting to  host=%s", (host) ? host : "localhost" );
			  if (port) mexPrintf("  port=%d",port);
			  if (user) mexPrintf("  user=%s",user);
			  if (pass) mexPrintf("  password=%s",pass);
			  mexPrintf("\n"); }

		//  Establish and test the connection
		//  If this fails, then conn is still set, but isopen stays false
		if (!(conn=mysql_init(conn)))
			mexErrMsgTxt("Couldn\'t initialize MySQL connection object");
		if (!mysql_real_connect( conn, host, user, pass, NULL,port,NULL,0 ))
			mexErrMsgTxt(mysql_error(conn));
		const char *c=mysql_stat(conn);
		if (c)  { if (nlhs<1) mexPrintf("%s\n",c); }
		else    mexErrMsgTxt(mysql_error(conn));

		isopen=true;
		ncid++;
		if (ncid>MAXCONN)
			{ mexPrintf("ncid = %d ?\n",ncid);
			  mexErrMsgTxt("Internal logic error\n"); }
		prevcid[ncid-1] = cid;

		if (debug) stackprint();

		//  Now we are OK -- return the connection handle opened.
		setScalarReturn(nlhs,plhs,cid);
		}

	else if (q==CLOSE)
		{
		if ( cid>=0 && isopen )
			{ if (debug) mexPrintf("| Closing %d\n",cid);
			  mysql_close(conn);
			  conn = NULL; isopen=false;  stackdelete(cid); }
		if (debug) stackprint();
		}

	else if (q==CLOSEALL)
		{ while (ncid>0)
			{ if (debug) stackprint();
			  cid = prevcid[ncid-1];
			  if (debug) mexPrintf("| Closing %d\n",cid);
			  if (!(c[cid].isopen))
				{ mexPrintf("Connection %d is not marked open!\n",cid);
				  mexErrMsgTxt("Internal logic error"); }
			  mysql_close(c[cid].conn);
			  c[cid].conn=NULL;  c[cid].isopen=false;  ncid--; }}

	else if ( q==USE || q==USENAMED )
		{
		if ( cid<0 || !isopen ) mexErrMsgTxt("Not connected");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("\nClosing connection %d\n",cid);
			  mexErrMsgTxt("Use command failed"); }
		char *db=NULL;
		if (q==USENAMED)
			{ if (nrhs>=2) db=mxArrayToString(prhs[jarg+1]);
			  else         mexErrMsgTxt("Must specify a database to use"); }
		else
			{ db = query + 3;
			  while ( *db==' ' || *db=='\t' ) db++; }
		if (mysql_select_db(conn,db))  mexErrMsgTxt(mysql_error(conn));
		if (nlhs<1) mexPrintf("Current database is \"%s\"\n",db); 
		else        setScalarReturn(nlhs,plhs,1.);
		}

	else if (q==STATUS)
		{
		if (nlhs<1)  //  He wants a report
			{ // print connection handle only if multiple connections
			  char idstr[10];  idstr[0]=0;
			  if ( cid>=0 && ncid>1 )  sprintf(idstr,"(%d) ",cid);
			  if ( cid<0 || !isopen )
			   { mexPrintf("%sNot connected\n",idstr,cid);  return; }
			  if (mysql_ping(conn))
				{ mexErrMsgTxt(mysql_error(conn)); }
			  mexPrintf("%s%-30s   Server version %s\n",
			    idstr, mysql_get_host_info(conn), mysql_get_server_info(conn) ); }
		else         //  He wants a return value for this connection
			{ double *pr=setScalarReturn(nlhs,plhs,0.);
			  if ( cid<0 || !isopen ) { *pr=1.; return; }
			  if (mysql_ping(conn))   { *pr=2.; return; }}
		}

	else if (q==STATSALL)
		{
		if (debug) stackprint();
		if (ncid==0)      mexPrintf("No connections open\n");
		else if (ncid==1) mexPrintf("1 connection open\n");
		else              mexPrintf("%d connections open\n",ncid);
		for ( int j=0 ; j<ncid ; j++ )
			{ cid = prevcid[j];
			  if (mysql_ping(c[cid].conn))
				  mexPrintf("%2d:  %s\n",cid,mysql_error(conn));
			  else
				  mexPrintf("%2d:  %-30s   Server version %s\n",
				        cid, mysql_get_host_info(c[cid].conn),
				        mysql_get_server_info(c[cid].conn) ); }
		}

	// Quote the second string argument and return it (Chris Rodgers)
	else if (q==QUOTE)
		{
		if ((nrhs-jarg)!=2)
			mexErrMsgTxt("mysql('quote','string_to_quote') takes two string arguments!");

		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexErrMsgTxt(mysql_error(conn)); }

		const mxArray *a = prhs[jarg+1];
		int llen = mxGetM(a)*mxGetN(a)*sizeof(mxChar);
		char *from = (char *) mxCalloc(llen+1,sizeof(char));
		if (mxGetString(a,from,llen)) mexErrMsgTxt("Can\'t copy string");
		int l = strlen(from);

		/* Allocate memory for input and output strings. */
		char *to = (char*) mxCalloc( llen*2+3, sizeof(char));

		/* Call the C subroutine. */
		to[0] = '\'';
		int n = mysql_real_escape_string( conn, to+1, from, l );
		to[n+1] = '\'';

		/* Set C-style string output_buf to MATLAB mexFunction output*/
		plhs[0] = mxCreateString(to);

		mxFree(from);  mxFree(to);  // just in case Matlab forgets
		}

	else if (q==CMD)
		{
		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("Closing connection %d\n",cid);
			  mexErrMsgTxt("Query failed"); }

		//  Execute the query (data stays on server)
		if (mysql_query(conn,query))  mexErrMsgTxt(mysql_error(conn));

		//  Download the data from server into our memory
		//     We need to be careful to deallocate res before returning.
		//  Matlab's allocation routines return instantly if there is not
		//  enough free space, without giving us time to dealloc res.
		//  This is a potential memory leak but I don't see how to fix it.
		MYSQL_RES *res = mysql_store_result(conn);

		//  As recommended in Paul DuBois' MySQL book (New Riders, 1999):
		//  A NULL result set after the query can indicate either
		//    (1) the query was an INSERT, DELETE, REPLACE, or UPDATE, that
		//        affect rows in the table but do not return a result set; or
		//    (2) an error, if the query was a SELECT, SHOW, or EXPLAIN
		//        that should return a result set but didn't.
		//  Distinguish between the two by checking mysql_field_count()
		//  We return in either case, either correctly or with an error
		if (!res)
			{
			if (!mysql_field_count(conn))
				{ unsigned long nrows=mysql_affected_rows(conn);
				  if (nlhs<1)
					{ mexPrintf("%u rows affected\n",nrows);
					  return; }
				  else
					{ setScalarReturn(nlhs,plhs,nrows);
					  return; }}
			else
				  mexErrMsgTxt(mysql_error(conn));
			}

		unsigned long nrow=mysql_num_rows(res), nfield=mysql_num_fields(res);

		//  If he didn't ask for any output (nlhs=0),
		//       then display the output and return
		if ( nlhs<1 )
			{ fancyprint(res);
			  mysql_free_result(res);
			  return; }

		//  If we are here, he wants output
		//  He must give exactly the right number of output arguments
// 		if ( nlhs != nfield )
// 			{ mysql_free_result(res);
// 			  mexPrintf("You specified %d output arguments, "
// 			         "and got %d columns of data\n",nlhs,nfield);
// 			  mexErrMsgTxt("Must give one output argument for each column"); }
        
        if(nlhs > 1) mexErrMsgIdAndTxt( "MYSQL query: ",
                        "Too many output arguments.");

		//  Fix the column types to fix MySQL C API sloppiness
		MYSQL_FIELD *f = mysql_fetch_fields(res);
		fix_types( f, res );

		//  Create the Matlab arrays for output
// 		double **pr = (double **) mxMalloc( nfield * sizeof(double *) );
// 		{ for ( int j=0 ; j<nfield ; j++ )
// 			{ if ( can_convert(f[j].type) )
// 				{ if (!( plhs[j] = mxCreateDoubleMatrix( nrow, 1, mxREAL ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create numeric matrix for output"); }
// 				  pr[j] = mxGetPr(plhs[j]); }
// 			  else
// 				{ if (!( plhs[j] = mxCreateCellMatrix( nrow, 1 ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create cell matrix for output"); }
// 				  pr[j] = NULL; }}}
        
         if (!( plhs[0] = mxCreateCellMatrix( nrow, nfield ) )){
					 mysql_free_result(res);
                     mexErrMsgTxt("Unable to create cell matrix for output");                 
         }

		//  Load the data into the cells
		mysql_data_seek(res,0);
		for ( int i=0 ; i<nrow ; i++ ){ 
			  MYSQL_ROW row = mysql_fetch_row(res);
			  if (!row) { 
				mexPrintf("Scanning row %d for data extraction\n",i+1);
				  mexErrMsgTxt("Internal error:  Failed to get a row"); }
// 			  for ( int j=0 ; j<nfield ; j++ ){ 
//                   if (can_convert(f[j].type)) { 
// 					pr[j][i] = field2num(row[j],f[j].type); 
//                   }
// 				  else {
// 					 mxArray *c = mxCreateString(row[j]);
// 					  mxSetCell(plhs[j],i,c); 
//                   }
//               }
             for ( int j=0 ; j <nfield ; j++ ){
                 mxArray *c = mxCreateString(row[j]);
 					  mxSetCell(plhs[0],j*nrow + i,c); 
             }
        }
		mysql_free_result(res);
		}
	else
		{ mexPrintf("Unknown query type q = %d\n",q);
		  mexErrMsgTxt("Internal code error"); }
}
示例#17
0
int
main( int argc, char * argv[] )
{

  char		szSQL[ 200 ], aszFlds[ 25 ][ 25 ],  szDB[ 50 ] ;
  const char * pszT;
  int			i, j, k, l, x ;
  MYSQL		* myData ;
  MYSQL_RES	* res ;
  MYSQL_FIELD	* fd ;
  MYSQL_ROW	row ;

  //....just curious....
  printf( "sizeof( MYSQL ) == %d\n", sizeof( MYSQL ) ) ;
  if ( argc == 2 )
    {
      strcpy( szDB, argv[ 1 ] ) ;
      strcpy( szSQL, DEFALT_SQL_STMT ) ;
      if (!strcmp(szDB,"--debug"))
      {
	strcpy( szDB, "mysql" ) ;
	printf("Some mysql struct information (size and offset):\n");
	printf("net:\t%3d %3d\n",sizeof(myData->net),offsetof(MYSQL,net));
	printf("host:\t%3d %3d\n",sizeof(myData->host),offsetof(MYSQL,host));
	printf("port:\t%3d %3d\n",sizeof(myData->port),offsetof(MYSQL,port));
	printf("protocol_version:\t%3d %3d\n",sizeof(myData->protocol_version),
	       offsetof(MYSQL,protocol_version));
	printf("thread_id:\t%3d %3d\n",sizeof(myData->thread_id),
	       offsetof(MYSQL,thread_id));
	printf("affected_rows:\t%3d %3d\n",sizeof(myData->affected_rows),
	       offsetof(MYSQL,affected_rows));
	printf("packet_length:\t%3d %3d\n",sizeof(myData->packet_length),
	       offsetof(MYSQL,packet_length));
	printf("status:\t%3d %3d\n",sizeof(myData->status),
	       offsetof(MYSQL,status));
	printf("fields:\t%3d %3d\n",sizeof(myData->fields),
	       offsetof(MYSQL,fields));
	printf("field_alloc:\t%3d %3d\n",sizeof(myData->field_alloc),
	       offsetof(MYSQL,field_alloc));
	printf("free_me:\t%3d %3d\n",sizeof(myData->free_me),
	       offsetof(MYSQL,free_me));
	printf("options:\t%3d %3d\n",sizeof(myData->options),
	       offsetof(MYSQL,options));
	puts("");
      }
    }		
  else if ( argc > 2 ) {
    strcpy( szDB, argv[ 1 ] ) ;
    strcpy( szSQL, argv[ 2 ] ) ;
  }
  else {
    strcpy( szDB, "mysql" ) ;
    strcpy( szSQL, DEFALT_SQL_STMT ) ;
  }
  //....
		  
  if ( (myData = mysql_init((MYSQL*) 0)) && 
       mysql_real_connect( myData, NULL, NULL, NULL, NULL, MYSQL_PORT,
			   NULL, 0 ) )
    {
      if ( mysql_select_db( myData, szDB ) < 0 ) {
	printf( "Can't select the %s database !\n", szDB ) ;
	mysql_close( myData ) ;
	return 2 ;
      }
    }
  else {
    printf( "Can't connect to the mysql server on port %d !\n",
	    MYSQL_PORT ) ;
    mysql_close( myData ) ;
    return 1 ;
  }
  //....
  if ( ! mysql_query( myData, szSQL ) ) {
    res = mysql_store_result( myData ) ;
    i = (int) mysql_num_rows( res ) ; l = 1 ;
    printf( "Query:  %s\nNumber of records found:  %ld\n", szSQL, i ) ;
    //....we can get the field-specific characteristics here....
    for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
      strcpy( aszFlds[ x ], fd->name ) ;
    //....
    while ( row = mysql_fetch_row( res ) ) {
      j = mysql_num_fields( res ) ;
      printf( "Record #%ld:-\n", l++ ) ;
      for ( k = 0 ; k < j ; k++ )
	printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
		(((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
      puts( "==============================\n" ) ;
    }
    mysql_free_result( res ) ;
  }
  else printf( "Couldn't execute %s on the server !\n", szSQL ) ;
  //....
  puts( "====  Diagnostic info  ====" ) ;
  pszT = mysql_get_client_info() ;
  printf( "Client info: %s\n", pszT ) ;
  //....
  pszT = mysql_get_host_info( myData ) ;
  printf( "Host info: %s\n", pszT ) ;
  //....
  pszT = mysql_get_server_info( myData ) ;
  printf( "Server info: %s\n", pszT ) ;
  //....
  res = mysql_list_processes( myData ) ; l = 1 ;
  if (res)
    {
      for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
	strcpy( aszFlds[ x ], fd->name ) ;
      while ( row = mysql_fetch_row( res ) ) {
	j = mysql_num_fields( res ) ;
	printf( "Process #%ld:-\n", l++ ) ;
	for ( k = 0 ; k < j ; k++ )
	  printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
		  (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
	puts( "==============================\n" ) ;
      }
    }
  else
    {
      printf("Got error %s when retreiving processlist\n",mysql_error(myData));
    }
  //....
  res = mysql_list_tables( myData, "%" ) ; l = 1 ;
  for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
    strcpy( aszFlds[ x ], fd->name ) ;
  while ( row = mysql_fetch_row( res ) ) {
    j = mysql_num_fields( res ) ;
    printf( "Table #%ld:-\n", l++ ) ;
    for ( k = 0 ; k < j ; k++ )
      printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
	      (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
    puts( "==============================\n" ) ;
  }
  //....
  pszT = mysql_stat( myData ) ;
  puts( pszT ) ;
  //....
  mysql_close( myData ) ;
  return 0 ;

}
示例#18
0
文件: ext_mysql.cpp 项目: 191919/hhvm
static Variant HHVM_FUNCTION(mysql_stat,
                      const Variant& link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return false;
  return String(mysql_stat(conn), CopyString);
}
示例#19
0
int main(int argc, char **argv)
{
	time_t lastrun;
	char go;

	termsigs = 0;
	verbosity = 1;
	options = 0;
	my_conf = (Config *)NULL;
	DBhandle = (MYSQL *)NULL;
	LocalDB = (MYSQL *)NULL;
	selectedconf = (char *)NULL;

	signal(SIGTSTP, SIG_IGN);
	signal(SIGINT, sig_end);
	signal(SIGTERM, sig_end);
	signal(SIGQUIT, sig_end);
	signal(SIGHUP, sig_hup);

	stats = (struct dbstat *)malloc(sizeof(struct dbstat));
	if (!stats)
	{
		if (dlvl(1)) { fprintf(stdout, "malloc(stats): %s\n", strerror(errno)); }
		return(-1);
	}
	memset(stats, 0, sizeof(struct dbstat));
	stats->created = 0;
	stats->destroyed = 0;

	selectedconf = (char *)malloc(512);
	if (!selectedconf)
	{
		if (dlvl(1)) { fprintf(stdout, "malloc(selectedconf): %s\n", strerror(errno)); }
		return(-1);
	}
	memset(selectedconf, 0, 512);

	while ((go = getopt(argc, argv, "qvlhVc:")) >= 0)
	{
		switch (go)
		{
			case 'V':
			{
				fprintf(stdout, "Crimson Pyramid SQL Agent version %lu\n", VERSION);
				fflush(stdout);
				return(0);
				break;
			}
			case 'v':
			{
				if (verbosity < 5) { verbosity++; }
				break;
			}
			case 'q':
			{
				if (verbosity > 0) { verbosity--; }
				break;
			}
			case 'd':
			{
				options |= OPTION_DAEMON;
				break;
			}
			case 'c':
			{
				if (!optarg)
				{
					fprintf(stdout, "%s -c requires an argument.\n", argv[0]);
					return(-1);
				}
				my_conf = read_config(optarg);
				if (!my_conf)
				{
					fprintf(stdout, "%s -c %s: failed reading config file.\n", argv[0], optarg);
					return(-1);
				}
				else
				{
					if (dlvl(2)) { fprintf(stdout, "Loaded configuration file from: %s\n", optarg); }
					snprintf(selectedconf, 512, "%s", optarg);
				}
				break;
			}
			case 'h':
			default:
			{
				fprintf(stdout, "Crimson Pyramid sqlagent %lu\n", VERSION);
				fprintf(stdout, "\tusage: %s [-v|q] [-h] [-l] [-c <config file path>]\n", argv[0]);
				fflush(stdout);
				return(0);
				break;
			}
		}
	}

#ifdef CONFIG_FILE
	if (!my_conf)
	{
		my_conf = read_config(CONFIG_FILE);
		if (my_conf)
		{
			if (dlvl(2)) { fprintf(stdout, "Loaded configuration file from: %s\n", CONFIG_FILE); }
			snprintf(selectedconf, 512, "%s", CONFIG_FILE);
		}
	}
#endif

	if (!my_conf)
	{
		if (dlvl(1)) { fprintf(stdout, "Could not load configuration file.\n"); }
		return(1);
	}

	if (my_conf->svcdaemon)
	{
		options |= OPTION_DAEMON;
	}

	if (!db_init())
	{
		if (dlvl(1) && DBhandle) { fprintf(stdout, "Database connection failed: %s\n", mysql_error(DBhandle)); }
		else if (dlvl(1)) { fprintf(stdout, "Database connection failed: UNKNOWN\n"); }

		DBhandle = (MYSQL *)NULL;
		free_config(my_conf);
		return(1);
	}

	my_sid = db_getsrvid();
	if (my_sid < 0)
	{
		/* if (dlvl(4)) { fprintf(stdout, "Error getting server ID.\n"); } */
		free_config(my_conf);
		return(0);
	}

	if (rundaemon)
	{
		int fr;

		fr = fork();
		if (fr < 0)
		{
			fprintf(stdout, "Error with fork(): %s\n", strerror(errno));
			exit(1);
		}
		else if (fr > 0)
		{
			exit(0);
		}

		openlog("CP_sqlagent", LOG_NDELAY, LOG_DAEMON);

		run_updates(my_sid);
		lastrun = time(NULL);

		while (!(options & OPTION_TERMINATE))
		{
			if ((lastrun + my_conf->waittime) <= time(NULL))
			{
				if (DBhandle && mysql_stat(DBhandle))
				{
					run_updates(my_sid);
					lastrun = time(NULL);
				}
				else
				{
					if (!db_init())
					{
						if (dlvl(1) && DBhandle) { fprintf(stdout, "Database connection failed: %s\n", mysql_error(DBhandle)); }
						else if (dlvl(1)) { fprintf(stdout, "Database connection failed: UNKNOWN\n"); }
						DBhandle = (MYSQL *)NULL;
						sleep(30);
					}
				}
			}
			usleep(25000);	/* 1/4 of a second at a time */
		}
	}
	else
	{
		run_updates(my_sid);
	}

	if (DBhandle) { db_deinit(); }

	if (dlvl(3))
	{
		if (rundaemon)
		{
			syslog(LOG_INFO, "Created: %u", stats->created);
			syslog(LOG_INFO, "Dropped: %u", stats->destroyed);
		}
		else
		{
			fprintf(stdout, "Created: %u\n", stats->created);
			fprintf(stdout, "Dropped: %u\n", stats->destroyed);
		}
	}

	if (rundaemon) { closelog(); }
	free_config(my_conf);
	if (selectedconf) { free(selectedconf); }
	if (stats) { free(stats); }

	return(0);
}
示例#20
0
Variant f_mysql_stat(CVarRef link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return false;
  return String(mysql_stat(conn), CopyString);
}
示例#21
0
string CDatabase_Connection::stat()
{
	return mysql_stat(&my);
}