Esempio n. 1
0
//-------------------------------------------------------------------------------------
bool DBUtil::initThread()
{
	ENGINE_COMPONENT_INFO& dbcfg = g_kbeSrvConfig.getDBMgr();
	if(strcmp(dbcfg.db_type, "mysql") == 0)
	{
		if (!mysql_thread_safe()) 
		{
			KBE_ASSERT(false);
		}
		else
		{
			mysql_thread_init();
		}
	}

	return true;
}
Esempio n. 2
0
VT_ROW vt_fetch_next(VT_CONN *conn) {
  VT_ROW row = {0, 0, 0};
  if(conn->num_fields == 0) {
    return row;
  }

  mysql_thread_init();
  row.mysql_row = mysql_fetch_row(conn->result);
  if(!row.mysql_row) {
    if(mysql_errno(conn->mysql)) {
      row.has_error = 1;
      return row;
    }
  } else {
    row.lengths = mysql_fetch_lengths(conn->result);
  }
  return row;
}
Esempio n. 3
0
void vt_close_result(VT_CONN *conn) {
  MYSQL_RES *result;

  if(conn->result) {
    mysql_thread_init();
    mysql_free_result(conn->result);
    clear_result(conn);
  }
  // Ignore subsequent results if any. We only
  // return the first set of results for now.
  while(mysql_next_result(conn->mysql) == 0) {
    result = mysql_store_result(conn->mysql);
    if (result) {
      while(mysql_fetch_row(result)) {
      }
      mysql_free_result(result);
    }
  }
}
Esempio n. 4
0
void SqlDelayThread::run()
{
    mysql_thread_init();

    SqlAsyncTask * s = NULL;

    ACE_Time_Value _time(2);
    while (m_running)
    {
        // if the running state gets turned off while sleeping
        // empty the queue before exiting
        s = dynamic_cast<SqlAsyncTask*> (m_sqlQueue.dequeue());
        if (s)
        {
            s->call();
            delete s;
        }
    }

    mysql_thread_end();
}
Esempio n. 5
0
int vt_connect(
    VT_CONN *conn,
    const char *host,
    const char *user,
    const char *passwd,
    const char *db,
    unsigned int port,
    const char *unix_socket,
    const char *csname,
    unsigned long client_flag)
{
  MYSQL *c;

  mysql_thread_init();
  conn->mysql = mysql_init(0);
  c = mysql_real_connect(conn->mysql, host, user, passwd, db, port, unix_socket, client_flag);
  if(!c) {
    return 1;
  }
  return mysql_set_character_set(conn->mysql, csname);
}
Esempio n. 6
0
/* child_main()
 * 
 * Main child process.
 * */
void *
child_main				(void * arg)
{
    int client_sd;
    int pos;
    socklen_t client_len;
    struct sockaddr_in client_addr;
    char * add_info;
	
    pos = (int)arg;
    client_len = sizeof(struct sockaddr_in);
	
    /* Initialize MySQL threaded interaction. */
    mysql_thread_init();
	
    asprintf(&add_info, "Thread ID: %d\n", pos);
    log_message(MESSAGE, IMSG_THREADINIT, add_info);
    free(add_info);
	
    while (alive_flag > 0)
    {
	pthread_mutex_lock(&conn_lock);
	client_sd = accept(server_sd, (struct sockaddr *) &client_addr, &client_len);
	pthread_mutex_unlock(&conn_lock);
		
	/* Abort connection without waiting to send remaining data. */
	setsockopt(client_sd, SOL_SOCKET, SO_LINGER, &close_timeout, sizeof(struct linger));
	children[pos].conn_count++;
		
	/* Process request */
	manage_request(client_sd);
	close(client_sd);
    }
	
    /* End MySQL threaded interaction . */
    mysql_thread_end();
    return (NULL);
}
Esempio n. 7
0
void SqlDelayThread::run()
{
    #ifndef DO_POSTGRESQL
    mysql_thread_init();
    #endif

    while (m_running)
    {
        // if the running state gets turned off while sleeping
        // empty the queue before exiting
        ACE_Based::Thread::Sleep(10);
        SqlOperation* s;
        while (m_sqlQueue.next(s))
        {
            s->Execute(m_dbEngine);
            delete s;
        }
    }

    #ifndef DO_POSTGRESQL
    mysql_thread_end();
    #endif
}
Esempio n. 8
0
void SqlDelayThread::run()
{
    #ifndef DO_POSTGRESQL
    mysql_thread_init();
    #endif
    //lets wait for next async task no more than 2 secs...
    ACE_Time_Value _time(2);
    while (m_running)
    {
        // if the running state gets turned off while sleeping
        // empty the queue before exiting
        SqlAsyncTask * s = dynamic_cast<SqlAsyncTask*> (m_sqlQueue.dequeue(/*&_time*/));
		if(s)
        {
            s->call();
            delete s;
        }
    }

    #ifndef DO_POSTGRESQL
    mysql_thread_end();
    #endif
}
Esempio n. 9
0
void* RunDbTask(void* arg)
{
    int nSeq = *(int*)arg;      //每个线程编一个流水号
   // printf("other runDbTask,seq=%d\n", nSeq);

    LogDebug("other RunDbTask", "db connect begin!!");

    mysql_thread_init();
    CDbTask t(g_worldOther, nSeq);

    string strErr;
    if(!t.Init(GetWorld()->GetDefParser().GetLogDbCfg(), strErr))
    {
        LogDebug("CWorldLog::init().error", "connect db:%s", strErr.c_str());
        printf("CWorldLog::init().error, thread id = %d , connect db:%s", nSeq , strErr.c_str());
        mysql_thread_end();
        return NULL;
    }
    LogDebug("RunDbTask", "db connect ok!!!");

    t.Run();
    mysql_thread_end();
    return NULL;
}
Esempio n. 10
0
/**
 * The entry point for the monitoring module thread
 *
 * @param arg	The handle of the monitor
 */
static void
monitorMain(void *arg)
{
    MONITOR* mon = (MONITOR*)arg;
MM_MONITOR	*handle;
MONITOR_SERVERS	*ptr;
int detect_stale_master;
MONITOR_SERVERS *root_master;
size_t nrounds = 0;

spinlock_acquire(&mon->lock);
handle = (MM_MONITOR *)mon->handle;
spinlock_release(&mon->lock);
detect_stale_master = handle->detectStaleMaster;

	if (mysql_thread_init())
	{
		LOGIF(LE, (skygw_log_write_flush(
                                   LOGFILE_ERROR,
                                   "Fatal : mysql_thread_init failed in monitor "
                                   "module. Exiting.\n")));
		return;
	}                         

	handle->status = MONITOR_RUNNING;
	while (1)
	{
		if (handle->shutdown)
		{
			handle->status = MONITOR_STOPPING;
			mysql_thread_end();
			handle->status = MONITOR_STOPPED;
			return;
		}

		/** Wait base interval */
		thread_millisleep(MON_BASE_INTERVAL_MS);
		/**
		 * Calculate how far away the monitor interval is from its full
		 * cycle and if monitor interval time further than the base
		 * interval, then skip monitoring checks. Excluding the first
		 * round.
		 */
                if (nrounds != 0 &&
                        ((nrounds*MON_BASE_INTERVAL_MS)%mon->interval) >=
                        MON_BASE_INTERVAL_MS)
                {
                        nrounds += 1;
                        continue;
                }
                nrounds += 1;

		/* start from the first server in the list */
		ptr = mon->databases;

		while (ptr)
		{
			/* copy server status into monitor pending_status */
			ptr->pending_status = ptr->server->status;

			/* monitor current node */
			monitorDatabase(mon, ptr);

                        if (mon_status_changed(ptr))
                        {
                                dcb_call_foreach(ptr->server,DCB_REASON_NOT_RESPONDING);
                        }
                        
                        if (mon_status_changed(ptr) || 
                                mon_print_fail_status(ptr))
                        {
                                LOGIF(LD, (skygw_log_write_flush(
                                        LOGFILE_DEBUG,
                                        "Backend server %s:%d state : %s",
                                        ptr->server->name,
                                        ptr->server->port,
                                        STRSRVSTATUS(ptr->server))));                                
                        }
                        if (SERVER_IS_DOWN(ptr->server))
                        {
                                /** Increase this server'e error count */
                                ptr->mon_err_count += 1;                                
                        }
                        else
                        {
                                /** Reset this server's error count */
                                ptr->mon_err_count = 0;
                        }

			ptr = ptr->next;
		}
	
		/* Get Master server pointer */
		root_master = get_current_master(mon);

		/* Update server status from monitor pending status on that server*/

                ptr = mon->databases;
		while (ptr)
		{
			if (! SERVER_IN_MAINT(ptr->server)) {
				/* If "detect_stale_master" option is On, let's use the previus master */
				if (detect_stale_master && root_master && (!strcmp(ptr->server->name, root_master->server->name) && ptr->server->port == root_master->server->port) && (ptr->server->status & SERVER_MASTER) && !(ptr->pending_status & SERVER_MASTER)) {
					/* in this case server->status will not be updated from pending_status */
					LOGIF(LM, (skygw_log_write_flush(
						LOGFILE_MESSAGE, "[mysql_mon]: root server [%s:%i] is no longer Master, let's use it again even if it could be a stale master, you have been warned!", ptr->server->name, ptr->server->port)));
					/* Set the STALE bit for this server in server struct */
					server_set_status(ptr->server, SERVER_STALE_STATUS);
				} else {
					ptr->server->status = ptr->pending_status;
				}
			}
			ptr = ptr->next;
		}
		
		ptr = mon->databases;
		monitor_event_t evtype;
		while(ptr)
		{
		    if(mon_status_changed(ptr))
		    {
			evtype = mon_get_event_type(ptr);
			if(isMySQLEvent(evtype))
			{
			    skygw_log_write(LOGFILE_TRACE,"Server changed state: %s[%s:%u]: %s",
				     ptr->server->unique_name,
				     ptr->server->name,ptr->server->port,
				     mon_get_event_name(ptr));
			    if(handle->script && handle->events[evtype])
			    {
				monitor_launch_script(mon,ptr,handle->script);
			    }
			}
		    }
		    ptr = ptr->next;
		}
	}
}
		virtual void Run()	{	mysql_thread_init();	}
Esempio n. 12
0
/**
 * Load the user/passwd form mysql.user table into the service users' hashtable
 * environment.
 *
 * @param service	The current service
 * @param users		The users table into which to load the users
 * @return      -1 on any error or the number of users inserted (0 means no users at all)
 */
static int
getUsers(SERVICE *service, struct users *users)
{
	MYSQL			*con = NULL;
	MYSQL_ROW		row;
	MYSQL_RES		*result = NULL;
	int			num_fields = 0;
	char			*service_user = NULL;
	char			*service_passwd = NULL;
	char			*dpwd;
	int			total_users = 0;
	SERVER			*server;
	char			*users_query;
	unsigned char		hash[SHA_DIGEST_LENGTH]="";
	char			*users_data = NULL;
	int 			nusers = 0;
	int			users_data_row_len = MYSQL_USER_MAXLEN + MYSQL_HOST_MAXLEN + MYSQL_PASSWORD_LEN;
	struct sockaddr_in	serv_addr;
	MYSQL_USER_HOST		key;

	/* enable_root for MySQL protocol module means load the root user credentials from backend databases */
	if(service->enable_root) {
		users_query = LOAD_MYSQL_USERS_QUERY " ORDER BY HOST DESC";
	} else {
		users_query = LOAD_MYSQL_USERS_QUERY USERS_QUERY_NO_ROOT " ORDER BY HOST DESC";
	}

	serviceGetUser(service, &service_user, &service_passwd);

	/** multi-thread environment requires that thread init succeeds. */
	if (mysql_thread_init()) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : mysql_thread_init failed.")));
		return -1;
	}
    
	con = mysql_init(NULL);

 	if (con == NULL) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : mysql_init: %s",
                        mysql_error(con))));
		return -1;
	}

	if (mysql_options(con, MYSQL_OPT_USE_REMOTE_CONNECTION, NULL)) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : failed to set external connection. "
                        "It is needed for backend server connections. "
                        "Exiting.")));
		return -1;
	}
	/*
	 * Attempt to connect to each database in the service in turn until
	 * we find one that we can connect to or until we run out of databases
	 * to try
	 */
	server = service->databases;
	dpwd = decryptPassword(service_passwd);
	while (server != NULL && mysql_real_connect(con,
                                                    server->name,
                                                    service_user,
                                                    dpwd,
                                                    NULL,
                                                    server->port,
                                                    NULL,
                                                    0) == NULL)
	{
                server = server->nextdb;
	}
	free(dpwd);

	if (server == NULL)
	{
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : Unable to get user data from backend database "
                        "for service %s. Missing server information.",
                        service->name)));
		mysql_close(con);
		return -1;
	}

	if (mysql_query(con, MYSQL_USERS_COUNT)) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : Loading users for service %s encountered "
                        "error: %s.",
                        service->name,
                        mysql_error(con))));
		mysql_close(con);
		return -1;
	}
	result = mysql_store_result(con);

	if (result == NULL) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : Loading users for service %s encountered "
                        "error: %s.",
                        service->name,
                        mysql_error(con))));
		mysql_close(con);
		return -1;
	}
	num_fields = mysql_num_fields(result);
	row = mysql_fetch_row(result);

	nusers = atoi(row[0]);

	mysql_free_result(result);

	if (!nusers) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : Counting users for service %s returned 0",
                        service->name)));
		mysql_close(con);
		return -1;
	}

	if (mysql_query(con, users_query)) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : Loading users for service %s encountered "
                        "error: %s.",
                        service->name,
                        mysql_error(con))));
		mysql_close(con);
		return -1;
	}

	result = mysql_store_result(con);
  
	if (result == NULL) {
		LOGIF(LE, (skygw_log_write_flush(
                        LOGFILE_ERROR,
                        "Error : Loading users for service %s encountered "
                        "error: %s.",
                        service->name,
                        mysql_error(con))));
		mysql_close(con);
		return -1;
	}
	num_fields = mysql_num_fields(result);
	
	users_data = (char *)malloc(nusers * (users_data_row_len * sizeof(char)) + 1);

	if(users_data == NULL)
		return -1;

	while ((row = mysql_fetch_row(result))) { 
		/**
                 * Four fields should be returned.
                 * user and passwd+1 (escaping the first byte that is '*') are
                 * added to hashtable.
                 */
		
		char ret_ip[INET_ADDRSTRLEN + 1]="";
		const char *rc;

		/* prepare the user@host data struct */
		memset(&serv_addr, 0, sizeof(serv_addr));
		memset(&key, 0, sizeof(key));

		/* if host == '%', 0 is passed */
		if (setipaddress(&serv_addr.sin_addr, strcmp(row[1], "%") ? row[1] : "0.0.0.0")) {

			key.user = strdup(row[0]);

			if(key.user == NULL) {
				LOGIF(LE, (skygw_log_write_flush(
					LOGFILE_ERROR,
					"%lu [getUsers()] strdup() failed for user %s",
					pthread_self(),
					row[0])));

				continue;
			}

			memcpy(&key.ipv4, &serv_addr, sizeof(serv_addr));
			
			rc = inet_ntop(AF_INET, &(serv_addr).sin_addr, ret_ip, INET_ADDRSTRLEN);

			/* add user@host as key and passwd as value in the MySQL users hash table */
			if (mysql_users_add(users, &key, strlen(row[2]) ? row[2]+1 : row[2])) {
				LOGIF(LD, (skygw_log_write_flush(
					LOGFILE_DEBUG,
					"%lu [mysql_users_add()] Added user %s@%s(%s)",
					pthread_self(),
					row[0],
					row[1],
					rc == NULL ? "NULL" : ret_ip)));
		
				/* Append data in the memory area for SHA1 digest */	
				strncat(users_data, row[3], users_data_row_len);

				total_users++;
			} else {
				LOGIF(LE, (skygw_log_write_flush(
					LOGFILE_ERROR,
					"%lu [mysql_users_add()] Failed adding user %s@%s(%s)",
					pthread_self(),
					row[0],
					row[1],
					rc == NULL ? "NULL" : ret_ip)));

				continue;
			}

		} else {
			/* setipaddress() failed, skip user add and log this*/
			LOGIF(LE, (skygw_log_write_flush(
				LOGFILE_ERROR,
				"%lu [getUsers()] setipaddress failed: user %s@%s not added",
				pthread_self(),
				row[0],
				row[1])));
		}
	}

	/* compute SHA1 digest for users' data */
        SHA1((const unsigned char *) users_data, strlen(users_data), hash);

	memcpy(users->cksum, hash, SHA_DIGEST_LENGTH);

	free(users_data);

	mysql_free_result(result);
	mysql_close(con);
	mysql_thread_end();

	return total_users;
}
Esempio n. 13
0
const char *vt_error(VT_CONN *conn) {
  mysql_thread_init();
  return mysql_error(conn->mysql);
}
bool QueryThread::init()
{
  mysql_thread_init();
  return true;
}
Esempio n. 15
0
unsigned int vt_errno(VT_CONN *conn) {
  mysql_thread_init();
  return mysql_errno(conn->mysql);
}
Esempio n. 16
0
void DatabaseMysql::threadEnter()
{
	mysql_thread_init();
}
Esempio n. 17
0
void* startThread(void* arg)
{
    /*
    SELECT W.PageID,PageType,URL,ResetCookies,AuthUser,AuthPass,DownloadThreshold,HackingString,ResetCache,ServiceType,SecurityID,WPS.CurrentErrorRef,WPS.AlertCount,AlertLevel2Count,AlertLevel3Count,WPS.ErrorStatus,W.Status,W.IgnoreRudeWords,W.CustomerNo,W.HTTPMethod,W.IgnoreContentErrors,W.DownloadSpeed,W.Referer,W.StoreResultDetail,W.MinSize,W.MaxSize,C.AlertCount,W.CertID,W.StepName,W.AgentString,W.sm_processScript,WPS.OverallAlertCount,W.StoreRequest,W.StoreHeaders,W.StoreHTML,W.StoreDiag,W.ContentType,W.Header1,W.Header2,W.GzipEncoding from WebPage W, Customer C, WebPageStatus WPS where W.PageID=13714 and WPS.PageID=W.PageID and W.CustomerNo=C.CustomerNo and (W.Status=1 or W.Status=3)
    select VariableName, VariableValue, Encode from FormVariables where PageID=13714 order by OrderNo asc
    SELECT Phrase, ID from ContentError
    SELECT Word, ID from ObsceneWord
    SELECT Phrase, ErrorCode from WebPagePhrase where PageID=13714 order by PhraseOrder
    select CookieValue, CookieDomain from Cookies where PageID=13714
    select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=0
    select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=1
    select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=2
    INSERT INTO ResultHeader040303 (ResultID,PageID,TestServer,StartDateTime,ResultCode,DNSTime,FirstByteTime,CompleteTime,TotalBytes,RunID,BatchID,FirstDataTime) VALUES (0,13714,10,'2004-03-03 14:39:20',1,8,9,5309,25291,0,0,15)
    SELECT LAST_INSERT_ID() from ResultHeader040303 where ResultID=LAST_INSERT_ID()
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:20',0,8,9,15,892,200,4338,'http://192.168.1.5',1)
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1012,1,1,7,4188,200,6543,'http://192.168.1.5/g/p10.png',2)
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1025,0,2,3,4185,200,12237,'http://192.168.1.5/g/MYSQLAuthCSP_small.png',3)
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1008,1,2,6,4301,200,2173,'http://192.168.1.5/g/newlogo.png',4)
    SELECT PageID from WebPageStatus where PageID=13714
    UPDATE WebPageStatus set LastResultID=40,StartDateTime='2004-03-03 14:39:20',LastResultCode=1,CompleteTime=5309 where PageID=13714
    SELECT WS.ErrorStatus,WS.CurrentErrorRef,WS.AlertCount,C.AlertLevel2Count,C.AlertLevel3Count,C.AlertCount,W.OverallAlertCount from Customer C, WebPage W, WebPageStatus WS WHERE C.CustomerNo=W.CustomerNo and W.PageID=WS.PageID and W.PageID=13714
    UPDATE WebPageStatus SET ErrorStatus=0,CurrentErrorRef=0,AlertCount=0 WHERE PageID=13714
    UPDATE WebPageStatus SET OverallAlertCount=0 WHERE PageID=13714
    select ErrorRef from WebPageError where PageID=13714 and Status<>2
    */

    mysql_thread_init();

    Connection* connection;
    Result* result;
    char query[10240];

    for (int repNo = 0; repNo < numRepsPerThreads; ++repNo)
    {
        try
        {
            Trace("Connecting to db", "", repNo);
            connection = new Connection(CConfig::getDBServer(), CConfig::getDBDatabase(),
                                        CConfig::getDBUser(), CConfig::getDBPass(), CConfig::getDBRetryTime());

            // run all the queries here...
            result = connection->Query("SELECT W.PageID,PageType,URL,ResetCookies,AuthUser,AuthPass,DownloadThreshold,HackingString,ResetCache,ServiceType,SecurityID,WPS.CurrentErrorRef,WPS.AlertCount,AlertLevel2Count,AlertLevel3Count,WPS.ErrorStatus,W.Status,W.IgnoreRudeWords,W.CustomerNo,W.HTTPMethod,W.IgnoreContentErrors,W.DownloadSpeed,W.Referer,W.StoreResultDetail,W.MinSize,W.MaxSize,C.AlertCount,W.CertID,W.StepName,W.AgentString,W.sm_processScript,WPS.OverallAlertCount,W.StoreRequest,W.StoreHeaders,W.StoreHTML,W.StoreDiag,W.ContentType,W.Header1,W.Header2,W.GzipEncoding from WebPage W, Customer C, WebPageStatus WPS where W.PageID=13714 and WPS.PageID=W.PageID and W.CustomerNo=C.CustomerNo and (W.Status=1 or W.Status=3)");
            result = connection->Query("select VariableName, VariableValue, Encode from FormVariables where PageID=13714 order by OrderNo asc");
            result = connection->Query("SELECT Phrase, ID from ContentError");
            result = connection->Query("SELECT Word, ID from ObsceneWord");
            result = connection->Query("SELECT Phrase, ErrorCode from WebPagePhrase where PageID=13714 order by PhraseOrder");
            result = connection->Query("select CookieValue, CookieDomain from Cookies where PageID=13714");
            result = connection->Query("select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=0");
            result = connection->Query("select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=1");
            result = connection->Query("select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=2");
            // close the db connection
            connection->Close();
            delete connection;
            connection = NULL;
            Trace("Disonnected from db", "", repNo);

            Trace("Connecting to db", "", repNo);
            connection = new Connection(CConfig::getDBServer(), CConfig::getDBDatabase(),
                                        CConfig::getDBUser(), CConfig::getDBPass(), CConfig::getDBRetryTime());
            result = connection->Query("INSERT INTO ResultHeader040303 (ResultID,PageID,TestServer,StartDateTime,ResultCode,DNSTime,FirstByteTime,CompleteTime,TotalBytes,RunID,BatchID,FirstDataTime) VALUES (0,13714,10,'2004-03-03 14:39:20',1,8,9,5309,25291,0,0,15)");
            result = connection->Query("SELECT LAST_INSERT_ID() from ResultHeader040303 where ResultID=LAST_INSERT_ID()");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:20',0,8,9,15,892,200,4338,'http://192.168.1.5',1)");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1012,1,1,7,4188,200,6543,'http://192.168.1.5/g/p10.png',2)");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1025,0,2,3,4185,200,12237,'http://192.168.1.5/g/MYSQLAuthCSP_small.png',3)");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1008,1,2,6,4301,200,2173,'http://192.168.1.5/g/newlogo.png',4)");
            result = connection->Query("SELECT PageID from WebPageStatus where PageID=13714");
            result = connection->Query("UPDATE WebPageStatus set LastResultID=40,StartDateTime='2004-03-03 14:39:20',LastResultCode=1,CompleteTime=5309 where PageID=13714");
            result = connection->Query("SELECT WS.ErrorStatus,WS.CurrentErrorRef,WS.AlertCount,C.AlertLevel2Count,C.AlertLevel3Count,C.AlertCount,W.OverallAlertCount from Customer C, WebPage W, WebPageStatus WS WHERE C.CustomerNo=W.CustomerNo and W.PageID=WS.PageID and W.PageID=13714");
            result = connection->Query("UPDATE WebPageStatus SET ErrorStatus=0,CurrentErrorRef=0,AlertCount=0 WHERE PageID=13714");
            result = connection->Query("UPDATE WebPageStatus SET OverallAlertCount=0 WHERE PageID=13714");
            result = connection->Query("select ErrorRef from WebPageError where PageID=13714 and Status<>2");
            // close the db connection
            connection->Close();
            delete connection;
            connection = NULL;
            Trace("Disonnected from db", "", repNo);

        }
        catch (const std::exception &e)
        {
            printf("Exception caught: - %s\r\n", e.what());
            // all done - exit the thread
//			pthread_exit(NULL);
        }

        Trace("Sleeping", "", 100 * sleepTime);
        usleep(100 * sleepTime);
    }

    mysql_thread_end();

    // all done - exit the thread
    pthread_exit(NULL);

    Trace("After Thread end", "", 0);
}
Esempio n. 18
0
/**
 * The entry point for the monitoring module thread
 *
 * @param arg	The handle of the monitor
 */
static void
monitorMain(void *arg)
{
    MONITOR* mon = (MONITOR*) arg;
    GALERA_MONITOR *handle;
    MONITOR_SERVERS *ptr;
    size_t nrounds = 0;
    MONITOR_SERVERS *candidate_master = NULL;
    int master_stickiness;
    int is_cluster = 0;
    int log_no_members = 1;
    monitor_event_t evtype;

    spinlock_acquire(&mon->lock);
    handle = (GALERA_MONITOR *) mon->handle;
    spinlock_release(&mon->lock);
    master_stickiness = handle->disableMasterFailback;
    if (mysql_thread_init())
    {
        MXS_ERROR("mysql_thread_init failed in monitor module. Exiting.");
        return;
    }
    handle->status = MONITOR_RUNNING;

    while (1)
    {
        if (handle->shutdown)
        {
            handle->status = MONITOR_STOPPING;
            mysql_thread_end();
            handle->status = MONITOR_STOPPED;
            return;
        }
        /** Wait base interval */
        thread_millisleep(MON_BASE_INTERVAL_MS);
        /**
         * Calculate how far away the monitor interval is from its full
         * cycle and if monitor interval time further than the base
         * interval, then skip monitoring checks. Excluding the first
         * round.
         */

        if (nrounds != 0 && ((nrounds * MON_BASE_INTERVAL_MS) % mon->interval) >= MON_BASE_INTERVAL_MS)
        {
            nrounds += 1;
            continue;
        }

        nrounds += 1;

        /* reset cluster members counter */
        is_cluster = 0;

        ptr = mon->databases;

        while (ptr)
        {
            ptr->mon_prev_status = ptr->server->status;

            monitorDatabase(mon, ptr);

            /* Log server status change */
            if (mon_status_changed(ptr))
            {
                MXS_DEBUG("Backend server %s:%d state : %s",
                          ptr->server->name,
                          ptr->server->port,
                          STRSRVSTATUS(ptr->server));
            }

            if (!(SERVER_IS_RUNNING(ptr->server)) ||
                !(SERVER_IS_IN_CLUSTER(ptr->server)))
            {
                dcb_hangup_foreach(ptr->server);
            }

            if (SERVER_IS_DOWN(ptr->server))
            {
                /** Increase this server'e error count */
                dcb_hangup_foreach(ptr->server);
                ptr->mon_err_count += 1;

            }
            else
            {
                /** Reset this server's error count */
                ptr->mon_err_count = 0;
            }

            ptr = ptr->next;
        }

        /*
         * Let's select a master server:
         * it could be the candidate master following MIN(node_id) rule or
         * the server that was master in the previous monitor polling cycle
         * Decision depends on master_stickiness value set in configuration
         */

        /* get the candidate master, following MIN(node_id) rule */
        candidate_master = get_candidate_master(mon);

        /* Select the master, based on master_stickiness */
        if (1 == handle->disableMasterRoleSetting)
        {
            handle->master = NULL;
        }
        else
        {
            handle->master = set_cluster_master(handle->master, candidate_master, master_stickiness);
        }

        ptr = mon->databases;

        while (ptr)
        {
            const int repl_bits = (SERVER_SLAVE | SERVER_MASTER | SERVER_MASTER_STICKINESS);
            if (SERVER_IS_JOINED(ptr->server))
            {
                if (handle->master)
                {
                    if (ptr != handle->master)
                    {
                        /* set the Slave role and clear master stickiness */
                        server_clear_set_status(ptr->server, repl_bits, SERVER_SLAVE);
                    }
                    else
                    {
                        if (candidate_master &&
                            handle->master->server->node_id != candidate_master->server->node_id)
                        {
                            /* set master role and master stickiness */
                            server_clear_set_status(ptr->server, repl_bits,
                                                    (SERVER_MASTER | SERVER_MASTER_STICKINESS));
                        }
                        else
                        {
                            /* set master role and clear master stickiness */
                            server_clear_set_status(ptr->server, repl_bits, SERVER_MASTER);
                        }
                    }
                }
                is_cluster++;
            }
            else
            {
                server_clear_set_status(ptr->server, repl_bits, 0);
            }
            ptr = ptr->next;
        }

        if (is_cluster == 0 && log_no_members)
        {
            MXS_ERROR("There are no cluster members");
            log_no_members = 0;
        }
        else
        {
            if (is_cluster > 0 && log_no_members == 0)
            {
                MXS_NOTICE("Found cluster members");
                log_no_members = 1;
            }
        }


        ptr = mon->databases;

        while (ptr)
        {

            /** Execute monitor script if a server state has changed */
            if (mon_status_changed(ptr))
            {
                evtype = mon_get_event_type(ptr);
                if (isGaleraEvent(evtype))
                {
                    MXS_NOTICE("Server changed state: %s[%s:%u]: %s",
                             ptr->server->unique_name,
                             ptr->server->name, ptr->server->port,
                             mon_get_event_name(ptr));
                    if (handle->script && handle->events[evtype])
                    {
                        monitor_launch_script(mon, ptr, handle->script);
                    }
                }
            }
            ptr = ptr->next;
        }
    }
}
Esempio n. 19
0
bool MyDriver::InitializeThreadSafety()
{
	return (mysql_thread_init() == 0);
}
Esempio n. 20
0
void *func(void *arg)
{
    ThreadArgs *args = (ThreadArgs *)arg;
    MYSQL_RES *result;
    MYSQL_ROW row;
    unsigned int rowCounter = 0;
    MYSQL_FIELD *field;
    unsigned int i;
    unsigned int timeout = 3000;
    const char *pStatement = "SELECT * FROM employees";
    mysql_thread_init();
    MYSQL *mysql = mysql_init(NULL);

    if (mysql == NULL)
    {
        printf("[%ld][%d]mysql init failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        return (void *)0;
    }

    mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);

    if (mysql_real_connect(mysql, DBHOST, DBUSER, DBPASS, DBNAME, DBPORT, DBSOCK, DBPCNT) == NULL)
    {
        printf("[%ld][%d]connect failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        mysql_close(mysql);
        mysql_thread_end();
        return (void *)0;
    }

    if (0 != mysql_real_query(mysql, pStatement, strlen(pStatement)))
    {
        printf("[%ld][%d]query failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        mysql_close(mysql);
        mysql_thread_end();
        return (void *)0;
    }

    result = mysql_store_result(mysql);

    if (result == NULL)
    {
        printf("[%ld][%d]fetch result failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        mysql_close(mysql);
        mysql_thread_end();
        return (void *)0;
    }

    printf("field name: ");
    while (NULL != (field = mysql_fetch_field(result)))
    {
        printf(" %s, ", field->name);
    }

    while (NULL != (row = mysql_fetch_row(result)))
    {
        rowCounter++;
        unsigned long *lengths;
        lengths = mysql_fetch_lengths(result);

    }
    printf("loop through result, total %d rows\n", rowCounter);

    mysql_free_result(result);
    mysql_close(mysql);
    mysql_thread_end();
    return (void *)0;
}
Esempio n. 21
0
/**
 * The main polling loop
 *
 * This routine does the polling and despatches of IO events
 * to the DCB's. It may be called either directly or as the entry point
 * of a polling thread within the gateway.
 *
 * The routine will loop as long as the variable "shutdown" is set to zero,
 * setting this to a non-zero value will cause the polling loop to return.
 *
 * There are two options for the polling, a debug option that is only useful if
 * you have a single thread. This blocks in epoll_wait until an event occurs.
 *
 * The non-debug option does an epoll with a time out. This allows the checking of
 * shutdown value to be checked in all threads. The algorithm for polling in this
 * mode is to do a poll with no-wait, if no events are detected then the poll is
 * repeated with a time out. This allows for a quick check before making the call 
 * with timeout. The call with the timeout differs in that the Linux scheduler may
 * deschedule a process if a timeout is included, but will not do this if a 0 timeout
 * value is given. this improves performance when the gateway is under heavy load.
 *
 * In order to provide a fairer means of sharing the threads between the different
 * DCB's the poll mechanism has been decoupled from the processing of the events.
 * The events are now recieved via the epoll_wait call, a queue of DCB's that have
 * events pending is maintained and as new events arrive the DCB is added to the end
 * of this queue. If an eent arrives for a DCB alreayd in the queue, then the event
 * bits are added to the DCB but the DCB mantains the same point in the queue unless
 * the original events are already being processed. If they are being processed then
 * the DCB is moved to the back of the queue, this means that a DCB that is receiving
 * events at a high rate will not block the execution of events for other DCB's and
 * should result in a fairer polling strategy.
 *
 * The introduction of the ability to inject "fake" write events into the event queue meant
 * that there was a possibility to "starve" new events sicne the polling loop would
 * consume the event queue before looking for new events. If the DCB that inject
 * the fake event then injected another fake event as a result of the first it meant
 * that new events did not get added to the queue. The strategy has been updated to
 * not consume the entire event queue, but process one event before doing a non-blocking
 * call to add any new events before processing any more events. A blocking call to
 * collect events is only made if there are no pending events to be processed on the
 * event queue.
 *
 * Also introduced a "timeout bias" mechanism. This mechansim control the length of
 * of timeout passed to epoll_wait in blocking calls based on previous behaviour.
 * The initial call will block for 10% of the define timeout peroid, this will be
 * increased in increments of 10% until the full timeout value is used. If at any
 * point there is an event to be processed then the value will be reduced to 10% again
 * for the next blocking call.
 *
 * @param arg	The thread ID passed as a void * to satisfy the threading package
 */
void
poll_waitevents(void *arg)
{
struct epoll_event events[MAX_EVENTS];
int		   i, nfds, timeout_bias = 1;
int		   thread_id = (int)arg;
DCB                *zombies = NULL;
int		   poll_spins = 0;

	/** Add this thread to the bitmask of running polling threads */
	bitmask_set(&poll_mask, thread_id);
	if (thread_data)
	{
		thread_data[thread_id].state = THREAD_IDLE;
	}

	/** Init mysql thread context for use with a mysql handle and a parser */
	mysql_thread_init();
	
	while (1)
	{
		if (pollStats.evq_pending == 0 && timeout_bias < 10)
		{
			timeout_bias++;
		}

		atomic_add(&n_waiting, 1);
#if BLOCKINGPOLL
		nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
		atomic_add(&n_waiting, -1);
#else /* BLOCKINGPOLL */
#if MUTEX_EPOLL
                simple_mutex_lock(&epoll_wait_mutex, TRUE);
#endif
		if (thread_data)
		{
			thread_data[thread_id].state = THREAD_POLLING;
		}
                
		atomic_add(&pollStats.n_polls, 1);
		if ((nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, 0)) == -1)
		{
			atomic_add(&n_waiting, -1);
                        int eno = errno;
                        errno = 0;
                        LOGIF(LD, (skygw_log_write(
                                LOGFILE_DEBUG,
                                "%lu [poll_waitevents] epoll_wait returned "
                                "%d, errno %d",
                                pthread_self(),
                                nfds,
                                eno)));
			atomic_add(&n_waiting, -1);
		}
		/*
		 * If there are no new descriptors from the non-blocking call
		 * and nothing to process on the event queue then for do a
		 * blocking call to epoll_wait.
		 *
		 * We calculate a timeout bias to alter the length of the blocking
		 * call based on the time since we last received an event to process
		 */
		else if (nfds == 0 && pollStats.evq_pending == 0 && poll_spins++ > number_poll_spins)
		{
			atomic_add(&pollStats.blockingpolls, 1);
			nfds = epoll_wait(epoll_fd,
                                                  events,
                                                  MAX_EVENTS,
                                                  (max_poll_sleep * timeout_bias) / 10);
			if (nfds == 0 && pollStats.evq_pending)
			{
				atomic_add(&pollStats.wake_evqpending, 1);
				poll_spins = 0;
			}
		}
		else
		{
			atomic_add(&n_waiting, -1);
		}

		if (n_waiting == 0)
			atomic_add(&pollStats.n_nothreads, 1);
#if MUTEX_EPOLL
                simple_mutex_unlock(&epoll_wait_mutex);
#endif
#endif /* BLOCKINGPOLL */
		if (nfds > 0)
		{
			timeout_bias = 1;
			if (poll_spins <= number_poll_spins + 1)
				atomic_add(&pollStats.n_nbpollev, 1);
			poll_spins = 0;
                        LOGIF(LD, (skygw_log_write(
                                LOGFILE_DEBUG,
                                "%lu [poll_waitevents] epoll_wait found %d fds",
                                pthread_self(),
                                nfds)));
			atomic_add(&pollStats.n_pollev, 1);
			if (thread_data)
			{
				thread_data[thread_id].n_fds = nfds;
				thread_data[thread_id].cur_dcb = NULL;
				thread_data[thread_id].event = 0;
				thread_data[thread_id].state = THREAD_PROCESSING;
			}

			pollStats.n_fds[(nfds < MAXNFDS ? (nfds - 1) : MAXNFDS - 1)]++;

			load_average = (load_average * load_samples + nfds)
						/ (load_samples + 1);
			atomic_add(&load_samples, 1);
			atomic_add(&load_nfds, nfds);

			/*
			 * Process every DCB that has a new event and add
			 * it to the poll queue.
			 * If the DCB is currently being processed then we
			 * or in the new eent bits to the pending event bits
			 * and leave it in the queue.
			 * If the DCB was not already in the queue then it was
			 * idle and is added to the queue to process after
			 * setting the event bits.
			 */
			for (i = 0; i < nfds; i++)
			{
				DCB 	*dcb = (DCB *)events[i].data.ptr;
				__uint32_t	ev = events[i].events;

				spinlock_acquire(&pollqlock);
				if (DCB_POLL_BUSY(dcb))
				{
					if (dcb->evq.pending_events == 0)
					{
						pollStats.evq_pending++;
						dcb->evq.inserted = hkheartbeat;
					}
					dcb->evq.pending_events |= ev;
				}
				else
				{
					dcb->evq.pending_events = ev;
					if (eventq)
					{
						dcb->evq.prev = eventq->evq.prev;
						eventq->evq.prev->evq.next = dcb;
						eventq->evq.prev = dcb;
						dcb->evq.next = eventq;
					}
					else
					{
						eventq = dcb;
						dcb->evq.prev = dcb;
						dcb->evq.next = dcb;
					}
					pollStats.evq_length++;
					pollStats.evq_pending++;
					dcb->evq.inserted = hkheartbeat;
					if (pollStats.evq_length > pollStats.evq_max)
					{
						pollStats.evq_max = pollStats.evq_length;
					}
				}
				spinlock_release(&pollqlock);
			}
		}

		/*
		 * Process of the queue of waiting requests
		 * This is done without checking the evq_pending count as a
		 * precautionary measure to avoid issues if the house keeping
		 * of the count goes wrong.
		 */
		if (process_pollq(thread_id))
			timeout_bias = 1;

		if (thread_data)
			thread_data[thread_id].state = THREAD_ZPROCESSING;
		zombies = dcb_process_zombies(thread_id);
		if (thread_data)
			thread_data[thread_id].state = THREAD_IDLE;

		if (do_shutdown)
		{
                        /*<
                         * Remove the thread from the bitmask of running
                         * polling threads.
                         */
			if (thread_data)
			{
				thread_data[thread_id].state = THREAD_STOPPED;
			}
			bitmask_clear(&poll_mask, thread_id);
			/** Release mysql thread context */
			mysql_thread_end();
			return;
		}
		if (thread_data)
		{
			thread_data[thread_id].state = THREAD_IDLE;
		}
	} /*< while(1) */
}
Esempio n. 22
0
void CDatabase::BeginDbThread()
{
	mysql_thread_init();
}
Esempio n. 23
0
/**
 * The entry point for the monitoring module thread
 *
 * @param arg	The handle of the monitor
 */
static void
monitorMain(void *arg)
{
MYSQL_MONITOR		*handle = (MYSQL_MONITOR *)arg;
MONITOR_SERVERS		*ptr;
size_t			nrounds = 0;
MONITOR_SERVERS		*candidate_master = NULL;
int			master_stickiness = handle->disableMasterFailback;
int			is_cluster=0;
int			log_no_members = 1;

	if (mysql_thread_init())
	{
                LOGIF(LE, (skygw_log_write_flush(
                                   LOGFILE_ERROR,
                                   "Fatal : mysql_thread_init failed in monitor "
                                   "module. Exiting.\n")));
                return;
	}                         
	handle->status = MONITOR_RUNNING;
	
	while (1)
	{
		if (handle->shutdown)
		{
			handle->status = MONITOR_STOPPING;
			mysql_thread_end();
			handle->status = MONITOR_STOPPED;
			return;
		}
		/** Wait base interval */
		thread_millisleep(MON_BASE_INTERVAL_MS);
		/** 
		 * Calculate how far away the monitor interval is from its full 
		 * cycle and if monitor interval time further than the base 
		 * interval, then skip monitoring checks. Excluding the first
		 * round.
		 */ 

		if (nrounds != 0 && ((nrounds*MON_BASE_INTERVAL_MS)%handle->interval) >= MON_BASE_INTERVAL_MS) 
		{
			nrounds += 1;
			continue;
		}

		nrounds += 1;

		/* reset cluster members counter */
		is_cluster=0;

		ptr = handle->databases;

		while (ptr)
		{
			monitorDatabase(handle, ptr);

			/* clear bits for non member nodes */
			if ( ! SERVER_IN_MAINT(ptr->server) && (ptr->server->node_id < 0 || ! SERVER_IS_JOINED(ptr->server))) {
				ptr->server->depth = -1;

				/* clear M/S status */
				server_clear_status(ptr->server, SERVER_SLAVE);
                		server_clear_status(ptr->server, SERVER_MASTER);
				
				/* clear master sticky status */
				server_clear_status(ptr->server, SERVER_MASTER_STICKINESS);
			}

			/* Log server status change */
			if (mon_status_changed(ptr))
			{
				LOGIF(LD, (skygw_log_write_flush(
					LOGFILE_DEBUG,
					"Backend server %s:%d state : %s",
					ptr->server->name,
					ptr->server->port,
					STRSRVSTATUS(ptr->server))));
			}

			if (SERVER_IS_DOWN(ptr->server))
			{
				/** Increase this server'e error count */
				ptr->mon_err_count += 1;
			}
			else
			{
				/** Reset this server's error count */
				ptr->mon_err_count = 0;
			}

			ptr = ptr->next;
		}

		/*
		 * Let's select a master server:
		 * it could be the candidate master following MIN(node_id) rule or
		 * the server that was master in the previous monitor polling cycle
		 * Decision depends on master_stickiness value set in configuration
		 */

		/* get the candidate master, followinf MIN(node_id) rule */
		candidate_master = get_candidate_master(handle->databases);

		/* Select the master, based on master_stickiness */
		handle->master = set_cluster_master(handle->master, candidate_master, master_stickiness);

		ptr = handle->databases;

		while (ptr && handle->master) {
			if (!SERVER_IS_JOINED(ptr->server) || SERVER_IN_MAINT(ptr->server)) {
				ptr = ptr->next;
				continue;
			}

			if (ptr != handle->master) {
				/* set the Slave role */
				server_set_status(ptr->server, SERVER_SLAVE);
				server_clear_status(ptr->server, SERVER_MASTER);

				/* clear master stickyness */
				server_clear_status(ptr->server, SERVER_MASTER_STICKINESS);
			} else {
				/* set the Master role */
				server_set_status(handle->master->server, SERVER_MASTER);
				server_clear_status(handle->master->server, SERVER_SLAVE);

				if (candidate_master && handle->master->server->node_id != candidate_master->server->node_id) {
					/* set master stickyness */
					server_set_status(handle->master->server, SERVER_MASTER_STICKINESS);
				} else {
					/* clear master stickyness */
					server_clear_status(ptr->server, SERVER_MASTER_STICKINESS);
				}			
			}

			is_cluster++;

			ptr = ptr->next;
		}

		if (is_cluster == 0 && log_no_members) {
			LOGIF(LE, (skygw_log_write_flush(
					LOGFILE_ERROR,
					"Error: there are no cluster members")));
			log_no_members = 0;
		} else {
			if (is_cluster > 0 && log_no_members == 0) {
				LOGIF(LE, (skygw_log_write_flush(
					LOGFILE_ERROR,
					"Info: found cluster members")));
				log_no_members = 1;
			}
		}
	}
}
Esempio n. 24
0
/**
 * The entry point for the monitoring module thread
 *
 * @param arg	The handle of the monitor
 */
static void
monitorMain(void *arg)
{
MYSQL_MONITOR	*handle = (MYSQL_MONITOR *)arg;
MONITOR_SERVERS	*ptr;
long master_id;
size_t nrounds = 0;

	if (mysql_thread_init())
	{
                LOGIF(LE, (skygw_log_write_flush(
                                   LOGFILE_ERROR,
                                   "Fatal : mysql_thread_init failed in monitor "
                                   "module. Exiting.\n")));
                return;
	}                         
	handle->status = MONITOR_RUNNING;
	
	while (1)
	{
		if (handle->shutdown)
		{
			handle->status = MONITOR_STOPPING;
			mysql_thread_end();
			handle->status = MONITOR_STOPPED;
			return;
		}

		/** Wait base interval */
		thread_millisleep(MON_BASE_INTERVAL_MS);
		/** 
		 * Calculate how far away the monitor interval is from its full 
		 * cycle and if monitor interval time further than the base 
		 * interval, then skip monitoring checks. Excluding the first
		 * round.
		 */ 
		if (nrounds != 0 && 
			((nrounds*MON_BASE_INTERVAL_MS)%handle->interval) >= 
			MON_BASE_INTERVAL_MS) 
		{
			nrounds += 1;
			continue;
		}
		nrounds += 1;
		master_id = -1;
		ptr = handle->databases;

		while (ptr)
		{
			unsigned int prev_status = ptr->server->status;
			monitorDatabase(ptr, handle->defaultUser, handle->defaultPasswd,handle);

			if (ptr->server->status != prev_status ||
				SERVER_IS_DOWN(ptr->server))
			{
				LOGIF(LD, (skygw_log_write_flush(
					LOGFILE_DEBUG,
					"Backend server %s:%d state : %s",
					ptr->server->name,
					ptr->server->port,
					STRSRVSTATUS(ptr->server))));
			}

			ptr = ptr->next;
		}
	}
}
Esempio n. 25
0
/*==============================================================================
------------------------------------------------------------------------------*/
bool db_thread_init(
    )
{
    return mysql_thread_init() == 0;
}
bool ConnectThread::init()
{
	mysql_thread_init();
	return true;
}
Esempio n. 27
0
void *poller(void *thread_args)
{
    worker_t *worker = (worker_t *) thread_args;
    crew_t *crew = worker->crew;
    target_t *entry = NULL;
    void *sessp = NULL;
    struct snmp_session session;
    struct snmp_pdu *pdu = NULL;
    struct snmp_pdu *response = NULL;
    oid anOID[MAX_OID_LEN];
    size_t anOID_len = MAX_OID_LEN;
    struct variable_list *vars = NULL;
    unsigned long long result = 0;
    unsigned long long last_value = 0;
    unsigned long long insert_val = 0;
    int status = 0, bits = 0, init = 0;
    char query[BUFSIZE];
    char storedoid[BUFSIZE];
    char result_string[BUFSIZE];

    if (set.verbose >= HIGH)
	printf("Thread [%d] starting.\n", worker->index);
    if (MYSQL_VERSION_ID > 40000)
       mysql_thread_init();
    else 
       my_thread_init();

    while (1) {
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] locking (wait on work)\n", worker->index);

	PT_MUTEX_LOCK(&crew->mutex);

	while (current == NULL) {
		PT_COND_WAIT(&crew->go, &crew->mutex);
	}
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] done waiting, received go (work cnt: %d)\n", worker->index, crew->work_count);

	if (current != NULL) {
	    if (set.verbose >= HIGH)
	      printf("Thread [%d] processing %s %s (%d work units remain in queue)\n", worker->index, current->host, current->objoid, crew->work_count);
	    snmp_sess_init(&session);
		if (set.snmp_ver == 2)
	      session.version = SNMP_VERSION_2c;
		else
	      session.version = SNMP_VERSION_1;
	    session.peername = current->host;
		session.remote_port = set.snmp_port;
	    session.community = current->community;
	    session.community_len = strlen(session.community);

	    sessp = snmp_sess_open(&session);
	    anOID_len = MAX_OID_LEN;
	    pdu = snmp_pdu_create(SNMP_MSG_GET);
	    read_objid(current->objoid, anOID, &anOID_len);
	    entry = current;
	    last_value = current->last_value;
	    init = current->init;
	    insert_val = 0;
	    bits = current->bits;
	    strncpy(storedoid, current->objoid, sizeof(storedoid));
		current = getNext();
	}
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] unlocking (done grabbing current)\n", worker->index);
	PT_MUTEX_UNLOCK(&crew->mutex);
	snmp_add_null_var(pdu, anOID, anOID_len);
	if (sessp != NULL) 
	   status = snmp_sess_synch_response(sessp, pdu, &response);
	else
	   status = STAT_DESCRIP_ERROR;

	/* Collect response and process stats */
	PT_MUTEX_LOCK(&stats.mutex);
	if (status == STAT_DESCRIP_ERROR) {
	    stats.errors++;
            printf("*** SNMP Error: (%s) Bad descriptor.\n", session.peername);
	} else if (status == STAT_TIMEOUT) {
	    stats.no_resp++;
	    printf("*** SNMP No response: (%s@%s).\n", session.peername,
	       storedoid);
	} else if (status != STAT_SUCCESS) {
	    stats.errors++;
	    printf("*** SNMP Error: (%s@%s) Unsuccessuful (%d).\n", session.peername,
	       storedoid, status);
	} else if (status == STAT_SUCCESS && response->errstat != SNMP_ERR_NOERROR) {
	    stats.errors++;
	    printf("*** SNMP Error: (%s@%s) %s\n", session.peername,
	       storedoid, snmp_errstring(response->errstat));
	} else if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
	    stats.polls++;
	} 
	PT_MUTEX_UNLOCK(&stats.mutex);

	/* Liftoff, successful poll, process it */
	if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
	    vars = response->variables;
#ifdef OLD_UCD_SNMP
            sprint_value(result_string, anOID, anOID_len, vars);
#else
	    snprint_value(result_string, BUFSIZE, anOID, anOID_len, vars);
#endif
	    switch (vars->type) {
		/*
		 * Switch over vars->type and modify/assign result accordingly.
		 */
		case ASN_COUNTER64:
		    if (set.verbose >= DEBUG) printf("64-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = vars->val.counter64->high;
		    result = result << 32;
		    result = result + vars->val.counter64->low;
		    break;
		case ASN_COUNTER:
		    if (set.verbose >= DEBUG) printf("32-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_INTEGER:
		    if (set.verbose >= DEBUG) printf("Integer result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_GAUGE:
		    if (set.verbose >= DEBUG) printf("32-bit gauge: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_TIMETICKS:
		    if (set.verbose >= DEBUG) printf("Timeticks result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_OPAQUE:
		    if (set.verbose >= DEBUG) printf("Opaque result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		default:
		    if (set.verbose >= DEBUG) printf("Unknown result type: (%s@%s) %s\n", session.peername, storedoid, result_string);
	    }

		/* Gauge Type */
		if (bits == 0) {
			if (result != last_value) {
				insert_val = result;
				if (set.verbose >= HIGH)
					printf("Thread [%d]: Gauge change from %lld to %lld\n", worker->index, last_value, insert_val);
			} else {
				if (set.withzeros) 
					insert_val = result;
				if (set.verbose >= HIGH)
					printf("Thread [%d]: Gauge steady at %lld\n", worker->index, insert_val);
			}
	    /* Counter Wrap Condition */
	    } else if (result < last_value) {
			PT_MUTEX_LOCK(&stats.mutex);
              stats.wraps++;
			PT_MUTEX_UNLOCK(&stats.mutex);
	      if (bits == 32) insert_val = (THIRTYTWO - last_value) + result;
	      else if (bits == 64) insert_val = (SIXTYFOUR - last_value) + result;
	      if (set.verbose >= LOW) {
	         printf("*** Counter Wrap (%s@%s) [poll: %llu][last: %llu][insert: %llu]\n",
	         session.peername, storedoid, result, last_value, insert_val);
	      }
	    /* Not a counter wrap and this is not the first poll */
	    } else if ((last_value >= 0) && (init != NEW)) {
		insert_val = result - last_value;
	        /* Print out SNMP result if verbose */
	        if (set.verbose == DEBUG)
		  printf("Thread [%d]: (%lld-%lld) = %llu\n", worker->index, result, last_value, insert_val);
	        if (set.verbose == HIGH)
		  printf("Thread [%d]: %llu\n", worker->index, insert_val);
            /* last_value < 0, so this must be the first poll */
	    } else {
                if (set.verbose >= HIGH) printf("Thread [%d]: First Poll, Normalizing\n", worker->index);
	    }

		/* Check for bogus data, either negative or unrealistic */
	    if (insert_val > entry->maxspeed || result < 0) {
			if (set.verbose >= LOW) printf("*** Out of Range (%s@%s) [insert_val: %llu] [oor: %lld]\n",
				session.peername, storedoid, insert_val, entry->maxspeed);
			insert_val = 0;
			PT_MUTEX_LOCK(&stats.mutex);
			stats.out_of_range++;
			PT_MUTEX_UNLOCK(&stats.mutex);
	    }

		if (!(set.dboff)) {
			if ( (insert_val > 0) || (set.withzeros) ) {
				PT_MUTEX_LOCK(&crew->mutex);
				snprintf(query, sizeof(query), "INSERT INTO %s VALUES (%d, NOW(), %llu)",
					entry->table, entry->iid, insert_val);
				if (set.verbose >= DEBUG) printf("SQL: %s\n", query);
				status = mysql_query(&mysql, query);
				if (status) printf("*** MySQL Error: %s\n", mysql_error(&mysql));
				PT_MUTEX_UNLOCK(&crew->mutex);

				if (!status) {
					PT_MUTEX_LOCK(&stats.mutex);
					stats.db_inserts++;
					PT_MUTEX_UNLOCK(&stats.mutex);
				} 
			} /* insert_val > 0 or withzeros */	
		} /* !dboff */

	} /* STAT_SUCCESS */

        if (sessp != NULL) {
           snmp_sess_close(sessp);
           if (response != NULL) snmp_free_pdu(response);
        }

	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] locking (update work_count)\n", worker->index);
	PT_MUTEX_LOCK(&crew->mutex);
	crew->work_count--;
	/* Only if we received a positive result back do we update the
	   last_value object */
	if (status == STAT_SUCCESS) entry->last_value = result;
	if (init == NEW) entry->init = LIVE;
	if (crew->work_count <= 0) {
	    if (set.verbose >= HIGH) printf("Queue processed. Broadcasting thread done condition.\n");
		PT_COND_BROAD(&crew->done);
	}
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] unlocking (update work_count)\n", worker->index);

		PT_MUTEX_UNLOCK(&crew->mutex);
    }				/* while(1) */
}
Esempio n. 28
0
unsigned long vt_thread_id(VT_CONN *conn) {
  mysql_thread_init();
  return mysql_thread_id(conn->mysql);
}
Esempio n. 29
0
void DatabaseMysql::ThreadStart()
{
    mysql_thread_init();
}
void *func(void *arg)
{
    ThreadArgs *args = (ThreadArgs *)arg;
    MYSQL_ROW row;
    unsigned int rowCounter = 0;
    MYSQL_FIELD *field;
    unsigned int i;
    unsigned int timeout = 3000;
    const char *pStatement = "SELECT * FROM employees";
    mysql_thread_init();
    MYSQL *mysql = mysql_init(NULL);
    MYSQL_STMT *stmt;
    MYSQL_BIND    bind[6];
    MYSQL_RES     *prepare_meta_result;
    short         small_data;
    int           int_data;
    char          str_data[STRING_SIZE];
    char          str_data2[STRING_SIZE];
    my_bool       is_null[6];
    my_bool       error[6];
    MYSQL_TIME    ts;
    unsigned long length[6];

    if (mysql == NULL)
    {
        printf("[%ld][%d]mysql init failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        return (void *)0;
    }

    mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);

    if (mysql_real_connect(mysql, DBHOST, DBUSER, DBPASS, DBNAME, DBPORT, DBSOCK, DBPCNT) == NULL)
    {
        printf("[%ld][%d]connect failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        mysql_close(mysql);
        mysql_thread_end();
        return (void *)0;
    }

    stmt = mysql_stmt_init(mysql);
    if (0 != mysql_stmt_prepare(stmt, pStatement, 23))
    {
        printf("[%ld][%d]prepare statement failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        mysql_close(mysql);
        mysql_thread_end();
        return (void *)0;
    }

    prepare_meta_result = mysql_stmt_result_metadata(stmt);
    if (!prepare_meta_result)
    {
      printf( "mysql_stmt_result_metadata(), returned no meta information\n");
      printf(" %s\n", mysql_stmt_error(stmt));
      exit(0);
    }

    if (0 != mysql_stmt_execute(stmt))
    {
        printf("[%ld][%d]query failed: %s\n", *args->thread_id, args->id, mysql_error(mysql));
        mysql_close(mysql);
        mysql_thread_end();
        return (void *)0;
    }

    /* Bind the result buffers for all 4 columns before fetching them */

    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type= MYSQL_TYPE_LONG;
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= &is_null[0];
    bind[0].length= &length[0];
    bind[0].error= &error[0];

    /* TIMESTAMP COLUMN */
    bind[1].buffer_type= MYSQL_TYPE_DATE;
    bind[1].buffer= (char *)&ts;
    bind[1].is_null= &is_null[1];
    bind[1].length= &length[1];
    bind[1].error= &error[1];

    /* STRING COLUMN */
    bind[2].buffer_type= MYSQL_TYPE_STRING;
    bind[2].buffer= (char *)str_data;
    bind[2].buffer_length= STRING_SIZE;
    bind[2].is_null= &is_null[2];
    bind[2].length= &length[2];
    bind[2].error= &error[2];

    /* STRING COLUMN */
    bind[3].buffer_type= MYSQL_TYPE_STRING;
    bind[3].buffer= (char *)str_data;
    bind[3].buffer_length= STRING_SIZE;
    bind[3].is_null= &is_null[3];
    bind[3].length= &length[3];
    bind[3].error= &error[3];

    /* STRING COLUMN */
    bind[4].buffer_type= MYSQL_TYPE_STRING;
    bind[4].buffer= (char *)str_data;
    bind[4].buffer_length= STRING_SIZE;
    bind[4].is_null= &is_null[4];
    bind[4].length= &length[4];
    bind[4].error= &error[4];

    /* TIMESTAMP COLUMN */
    bind[5].buffer_type= MYSQL_TYPE_DATE;
    bind[5].buffer= (char *)&ts;
    bind[5].is_null= &is_null[5];
    bind[5].length= &length[5];
    bind[5].error= &error[5];

    /* Bind the result buffers */
    if (mysql_stmt_bind_result(stmt, bind))
    {
      printf( " mysql_stmt_bind_result() failed\n");
      printf( " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
    mysql_stmt_store_result(stmt);

    printf("field name: ");
    while (NULL != (field = mysql_fetch_field(prepare_meta_result)))
    {
        printf(" %s, ", field->name);
    }

    while (!mysql_stmt_fetch(stmt))
    {
        rowCounter++;

    }
    printf("loop through result, total %d rows\n", rowCounter);

    mysql_free_result(prepare_meta_result);
    mysql_close(mysql);
    mysql_thread_end();
    return (void *)0;
}