Ejemplo n.º 1
0
/* Main rtgpoll */
int main(int argc, char *argv[]) {
    crew_t crew;
    pthread_t sig_thread;
    sigset_t signal_set;
    struct timeval now;
    double begin_time, end_time, sleep_time;
    char *conf_file = NULL;
    char errstr[BUFSIZE];
    int ch, i;

	dfp = stderr;

    /* Check argument count */
    if (argc < 3)
	usage(argv[0]);

	/* Set default environment */
    config_defaults(set);

    /* Parse the command-line. */
    while ((ch = getopt(argc, argv, "c:p:dhmDt:vz")) != EOF)
	switch ((char) ch) {
	case 'c':
	    conf_file = optarg;
	    break;
	case 'd':
	    set->dboff = TRUE;
	    break;
	case 'D':
	    set->daemon = FALSE;
	    break;
	case 'h':
	    usage(argv[0]);
	    break;
	case 'm':
	    set->multiple++;
	    break;
	case 'p':
	    pid_file = optarg;
	    break;
	case 't':
	    target_file = optarg;
	    break;
	case 'v':
	    set->verbose++;
	    break;
	case 'z':
	    set->withzeros = TRUE;
	    break;
	}

	debug(LOW, "RTG version %s starting.\n", VERSION);

	if (set->daemon) {
		if (daemon_init() < 0)
			fatal("Could not fork daemon!\n");
		debug(LOW, "Daemon detached\n");
	}


    /* Initialize signal handler */
    sigemptyset(&signal_set);
    sigaddset(&signal_set, SIGHUP);
    sigaddset(&signal_set, SIGUSR1);
    sigaddset(&signal_set, SIGUSR2);
    sigaddset(&signal_set, SIGTERM);
    sigaddset(&signal_set, SIGINT);
    sigaddset(&signal_set, SIGQUIT);
	if (!set->multiple) 
		checkPID(pid_file, set);

    if (pthread_sigmask(SIG_BLOCK, &signal_set, NULL) != 0)
		printf("pthread_sigmask error\n");

    /* Read configuration file to establish local environment */
    if (conf_file) {
      if ((read_rtg_config(conf_file, set)) < 0) 
		fatal("Could not read config file: %s\n", conf_file);
    } else {
      conf_file = malloc(BUFSIZE);
      if (!conf_file) 
         fatal("Fatal malloc error!\n");
      for(i=0;i<CONFIG_PATHS;i++) {
        snprintf(conf_file, BUFSIZE, "%s%s", config_paths[i], DEFAULT_CONF_FILE); 
        if (read_rtg_config(conf_file, set) >= 0)
           break;
        if (i == CONFIG_PATHS-1) {
			snprintf(conf_file, BUFSIZE, "%s%s", config_paths[0], DEFAULT_CONF_FILE); 
			if ((write_rtg_config(conf_file, set)) < 0) 
				fatal("Couldn't write config file.\n");
        }
      }
    }


    /* hash list of targets to be polled */
    init_hash();
	entries = hash_target_file(target_file);
    if (entries <= 0) 
		fatal("Error updating target list.");

	debug(LOW, "Initializing threads (%d).\n", set->threads);
    pthread_mutex_init(&(crew.mutex), NULL);
    pthread_cond_init(&(crew.done), NULL);
    pthread_cond_init(&(crew.go), NULL);
    crew.work_count = 0;

    /* Initialize the SNMP session */
	debug(LOW, "Initializing SNMP (port %d).\n", set->snmp_port);
    init_snmp("RTG");

    /* Attempt to connect to the MySQL Database */
#ifndef FEATURES
 #if HAVE_MYSQL
    if (!(set->dboff)) {
		if (mysql_dbconnect(set->dbdb, &mysql) < 0) 
			fatal("** Database error - check configuration.\n");
		if (!mysql_ping(&mysql))
			debug(LOW, "connected.\n");
		else
			fatal("server not responding.\n");
    }
 #endif
#else
 #if HAVE_MYSQL
	my_init();
 #endif
#endif


	debug(HIGH, "\nStarting threads.\n");
    for (i = 0; i < set->threads; i++) {
		crew.member[i].index = i;
		crew.member[i].crew = &crew;
		if (pthread_create(&(crew.member[i].thread), NULL, poller, (void *) &(crew.member[i])) != 0)
			printf("pthread_create error\n");
	}
    if (pthread_create(&sig_thread, NULL, sig_handler, (void *) &(signal_set)) != 0)
		printf("pthread_create error\n");

    /* give threads time to start up */
    sleep(1);

	debug(LOW, "RTG Ready.\n");

    /* Loop Forever Polling Target List */
    while (1) {
	lock = TRUE;
	gettimeofday(&now, NULL);
	begin_time = (double) now.tv_usec / 1000000 + now.tv_sec;

	PT_MUTEX_LOCK(&(crew.mutex));
	init_hash_walk();
	current = getNext();
	crew.work_count = entries;
	PT_MUTEX_UNLOCK(&(crew.mutex));
	    
	if (set->verbose >= LOW) {
		if (set->daemon)
			sysloginfo("Queue ready, broadcasting thread go condition.");
		else
        	timestamp("Queue ready, broadcasting thread go condition.");
	}
	PT_COND_BROAD(&(crew.go));
	PT_MUTEX_LOCK(&(crew.mutex));
	    
	while (crew.work_count > 0) {
		PT_COND_WAIT(&(crew.done), &(crew.mutex));
	}
	PT_MUTEX_UNLOCK(&(crew.mutex));

	gettimeofday(&now, NULL);
	lock = FALSE;
	end_time = (double) now.tv_usec / 1000000 + now.tv_sec;
	stats.poll_time = end_time - begin_time;
        stats.round++;
	sleep_time = set->interval - stats.poll_time;

	if (waiting) {
		debug(HIGH, "Processing pending SIGHUP.\n");
	    entries = hash_target_file(target_file);
	    waiting = FALSE;
	}

	if (set->verbose >= LOW) {
        snprintf(errstr, sizeof(errstr), "Poll round %d complete.", stats.round);
		if (set->daemon)
			sysloginfo(errstr);
		else
			timestamp(errstr);
	    print_stats(stats, set);
    }

	if (sleep_time <= 0)
	    stats.slow++;
	else
	    sleepy(sleep_time, set);
    } /* while */

#ifndef FEATURES
  #if HAVE_MYSQL
    /* Disconnect from the MySQL Database, exit. */
    if (!(set->dboff))
	mysql_dbdisconnect(&mysql);
  #endif
#endif
    exit(0);
}
Ejemplo n.º 2
0
/* TBL_Update
**
** Purpose:
**	This updates existing records in the named table.
**
** Parameter Dictionary:
**	TBL_HANDLE **handle: The pointer for the database/table pair
**		to be accessed for modification.  This table must be open.
**	TBL_CRITERIA *criteriaList: Contains the list of criteria to
**		select those records that should be updated.
**	TBL_FIELD *fieldList: Contains a list of the keyword/value
**		pairs to be used to modify the selected records.
**
** Return Values:
**	TBL_NORMAL: normal termination.
**	TBL_BADHANDLE: The handle passed to the routine was invalid.
**	TBL_DBNOEXIST: The database specified does not exist.
**	TBL_NOFIELDLIST: No keyword/value pairs were specified for update.
**	TBL_UPDATEFAILED: The insert operation failed most probably from
**		a bad specification in the fieldList.  This error
**		return could result from a misspelled keyword, etc.
**
** Notes:
**	Nothing unusual.
**
** Algorithm:
**	The records which match the (ANDED) criteria in criteriaList
**	are retreived and updated with the information contained in
**	fieldList.  Only the fields contained in fieldList will be
**	updated by this call.
*/
CONDITION
TBL_Update(TBL_HANDLE ** handle, const TBL_CRITERIA * criteriaList,
           TBL_UPDATE * updateList)
{
    TBL_CONTEXT
    * tc;
    TBL_UPDATE
    * up;
    TBL_CRITERIA
    * cp;
    char
    tabcol[100],
           *dbName,
           *tableName;
    int
    i,
    ret,
    first,
    foundit;

    tc = G_ContextHead;
    foundit = 0;
    while (tc != (TBL_CONTEXT *) NULL) {
        if (tc == (TBL_CONTEXT *) (*handle)) {
            dbName = tc->databaseName;
            tableName = tc->tableName;
            foundit = 1;
        }
        tc = tc->next;
    }
    if (!foundit) {
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_Update");
    }

    if (mysql_select_db(&mysql, dbName) != 0) {
        (void) COND_PushCondition(TBL_ERROR(TBL_DBSPECIFIC), "mySQL",
                                  mysql_error(&mysql), "TBL_Update");
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_Update");
    }

    /*
     * We found the names we need...now make sure we can access it. Actually,
     * given that we found it, we probably already know the outcome of this
     * command...but we do need to set up the correct database for this
     * update...
     */
    /*
     * Set up the update statement
     */
    up = updateList;
    mysqlcmd(&G_DBUpdate, "UPDATE ");
    Add_String_to_Buf(G_DBUpdate, tableName);
    mysqlcmd(&G_DBUpdate, " SET ");
    first = 1;
    foundit = 0;
    while (up->FieldName != NULL) {
        if (!first)
            mysqlcmd(&G_DBUpdate, " , ");
        Add_String_to_Buf(G_DBUpdate, up->FieldName);
        mysqlcmd(&G_DBUpdate, " = ");
        Add_UpdateValue_to_Buf(G_DBUpdate, up);
        first = 0;
        foundit = 1;
        up++;
    }
    if (foundit) {
        if ((cp = criteriaList) != (TBL_CRITERIA *) NULL) {
            mysqlcmd(&G_DBUpdate, " WHERE ");
            Add_Criteria_to_Buf(G_DBUpdate, cp);
            cp++;
            while (cp->FieldName != NULL) {
                mysqlcmd(&G_DBUpdate, " AND ");
                Add_Criteria_to_Buf(G_DBUpdate, cp);
                cp++;
            }
        }
        mysql_ping(&mysql);
        if (mysql_real_query(&mysql, G_DBUpdate, (unsigned int)strlen(G_DBUpdate)) != 0) {
            mysqlfreebuf(&G_DBUpdate);
            (void) COND_PushCondition(TBL_ERROR(TBL_DBSPECIFIC), "mySQL",
                                      mysql_error(&mysql), "TBL_Update");
            return COND_PushCondition(TBL_ERROR(TBL_UPDATEFAILED), DATABASE, "TBL_Update");
        }
    }
    mysqlfreebuf(&G_DBUpdate);
    return TBL_NORMAL;
}
Ejemplo n.º 3
0
/* TBL_Insert
**
** Purpose:
**	This inserts records into the named table.
**
** Parameter Dictionary:
**	TBL_HANDLE **handle: The pointer for the database/table pair
**		to be accessed for deletion.  This table must be open.
**	TBL_FIELD *fieldList: Contains a list of the keyword/value
**		pairs to be inserted into the specified table.
**
** Return Values:
**	TBL_NORMAL: normal termination.
**	TBL_BADHANDLE: The handle passed to the routine was invalid.
**	TBL_DBNOEXIST: The database specified does not exist.
**	TBL_NOFIELDLIST: No keyword/value pairs were specified to
**		insert.
**	TBL_INSERTFAILED: The insert operation failed most probably from
**		a bad specification in the fieldList.  This error
**		return could result from a misspelled keyword, etc.
**
** Notes:
**	Nothing unusual.
**
** Algorithm:
**	The table values contained in fieldList are added to the
**	database and table specified by handle.  Each call inserts
**	exactly one record.  It is the users responsibility to ensure
**	that the correct number of values are supplied for the
**	particular table, and that any values which need to be
**	unique (i.e.for the unique key field in a table) are
**	in-fact unique.
*/
CONDITION
TBL_Insert(TBL_HANDLE ** handle, TBL_FIELD * fieldList)
{
    TBL_CONTEXT
    * tc;
    TBL_FIELD
    * fp;
    char
    tabcol[100],
           *dbName,
           *tableName;
    int
    i,
    ret,
    FoundTextorBinary,
    foundit;

    tc = G_ContextHead;
    foundit = 0;
    while (tc != (TBL_CONTEXT *) NULL) {
        if (tc == (TBL_CONTEXT *) (*handle)) {
            dbName = tc->databaseName;
            tableName = tc->tableName;
            foundit = 1;
        }
        tc = tc->next;
    }
    if (!foundit) {
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_Insert");
    }

    if (mysql_select_db(&mysql, dbName) == -1) {
        (void) COND_PushCondition(TBL_ERROR(TBL_DBSPECIFIC), "mySQL",
                                  mysql_error(&mysql), "TBL_Insert");
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_Insert");
    }

    fp = fieldList;
    if (fp == (TBL_FIELD *) NULL) {
        return COND_PushCondition(TBL_ERROR(TBL_NOFIELDLIST), "TBL_Insert");
    }
    /*
     * Set up the insert statement
     */
    mysqlcmd(&G_DBInsert, "INSERT INTO ");
    Add_String_to_Buf(G_DBInsert, tableName);
    mysqlcmd(&G_DBInsert, " (  ");
    Add_FieldName_to_Buf(G_DBInsert, fp);
    fp++;
    while (fp->FieldName != NULL) {
        mysqlcmd(&G_DBInsert, " , ");
        mysqlcmd(&G_DBInsert, fp->FieldName);
        fp++;
    }
    mysqlcmd(&G_DBInsert, " ) VALUES ( ");

    fp = fieldList;
    Add_FieldValue_to_Buf(G_DBInsert, fp);
    fp++;
    while (fp->FieldName != NULL) {
        mysqlcmd(&G_DBInsert, " , ");
        Add_FieldValue_to_Buf(G_DBInsert, fp);
        fp++;
    }

    mysqlcmd(&G_DBInsert, " )");

    mysql_ping(&mysql);
    if (mysql_real_query(&mysql, G_DBInsert, (unsigned int)strlen(G_DBInsert)) != 0) {
        mysqlfreebuf(&G_DBInsert);
        (void) COND_PushCondition(TBL_ERROR(TBL_DBSPECIFIC), "mySQL",
                                  mysql_error(&mysql), "TBL_Insert");
        return COND_PushCondition(TBL_ERROR(TBL_INSERTFAILED), DATABASE, "TBL_Insert");
    }
    mysqlfreebuf(&G_DBInsert);

    return TBL_NORMAL;
}
Ejemplo n.º 4
0
	bool ping(){ 
		return mysql_ping(pMysql_) == 0; 
	}
Ejemplo n.º 5
0
Variant f_mysql_ping(const Variant& link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return init_null();
  return !mysql_ping(conn);
}
Ejemplo n.º 6
0
void __cdecl _MySQLWorker(void* parameters)
{
	my_bool reconnect		= 1;
	int		processedcount	= 0;

	/******************************************
	/*            Initialization
	/******************************************/
		
	// init the queue
	queue.mutex = CreateMutex(NULL, FALSE, NULL);
	queue.count = 0;
	queue.first = 0;
	queue.last = 0;

	// init mysql
	mysql = mysql_init(NULL);
	
	if (!mysql)
		return;
	
	// enable auto-reconnect
	mysql_options(mysql, MYSQL_OPT_RECONNECT, &reconnect);

	// check if MySQLEnd was somehow already called and switched state to STOPPING
	// we still expect STARTING here and if so go to INITIALIZED
	if (state == STARTING)
		state = INITIALIZED;

	/******************************************
	/*              Work loop
	/******************************************/
	while(state != STOPPING)
	{	
		/**** Something went wrong with mysql ****/
		if (!mysql)		
			state = STOPPING;
				
		/****** No initial connection yet *****/
		else if (state == INITIALIZED)
		{
			// try connect
			if (mysql == mysql_real_connect(mysql, host, user, password, db, 0, NULL, 0))
				state = CONNECTED;

			// not successful, sleep
			else			
				Sleep(SLEEPTIMENOCON);			
		}

		/****** At least was connected once *****/
		else if (state >= CONNECTED)
		{
			// verify connection is still up
			// this will auto-reconnect
			if (mysql_ping(mysql) == 0)
			{
				// schema not yet verified/created
				if (state == CONNECTED)
					_MySQLVerifySchema();

				// fully running
				else if (state >= SCHEMAVERIFIED)
				{
					// reset counter for processed items
					processedcount = 0;

					// process up to limit pending items
					while(_MySQLDequeue(TRUE))
					{
						processedcount++;

						// reached limit, do more next loop
						// to get updated state etc.
						if (processedcount >= MAX_ITEMS_UNTIL_LOOP)
							break;						
					}
					
					// defaultsleep if none processed
					if (processedcount == 0)
						Sleep(SLEEPTIME);					
				}
			}
			else
				Sleep(SLEEPTIMENOCON);	
		}
	}

	/******************************************
	/*              Shutdown
	/******************************************/

	// close mysql
	if (mysql)
		mysql_close(mysql);

	// free local connection strings
	if (host)
		free(host);
	
	if (user)
		free(user);
	
	if (password)
		free(password);
	
	if (db)
		free(db);

	// clear queue
	while(_MySQLDequeue(FALSE));

	// delete mutex
	if (queue.mutex)
		CloseHandle(queue.mutex);

	// mark stopped
	state = STOPPED;

	// finalize thread
	_endthread();
};
Ejemplo n.º 7
0
static VALUE nogvl_ping(void *ptr) {
  MYSQL *client = ptr;

  return mysql_ping(client) == 0 ? Qtrue : Qfalse;
}
Ejemplo n.º 8
0
int MysqlConnection_ping(T C) {
        assert(C);
        return (mysql_ping(C->db) == 0);
}
Ejemplo n.º 9
0
int main()
{

	inits();

	DHT22 * dhtS = new DHT22(18, "Sisämittari(DIG)");
	DHT22 * dht2S = new DHT22(17, "Ulkomittari(DIG)");
	BMP180 * bmp = new BMP180(0x77, "Painemittari(DIG)");

	char *code = NULL;

	short prog = 1;

	clock_t timer1 = clock();
	clock_t timer2 = clock();

	for(tempSensIT it = tempSensors.begin(); it != tempSensors.end(); ++it) {
		it->second->update();
	}

	//while(lirc_nextcode(&code) != 0) {
	while(1) {

		if(float(clock())/CLOCKS_PER_SEC - float(timer1)/CLOCKS_PER_SEC >= 0.012) {

			// Turn on DHT22's
			digitalWrite(20, HIGH);
			usleep(1000);

			for(tempSensIT it = tempSensors.begin(); it != tempSensors.end(); ++it) {
				it->second->update();
			}

			digitalWrite(20, LOW);

			timer1 = clock();

		}

		if(float(clock())/CLOCKS_PER_SEC - float(timer2)/CLOCKS_PER_SEC >= 0.25) {
			#ifdef HCDEBUG
				logfile << "MySQL connection: " << (mysql_ping(sqlcon) == 0 ? "Up" : "Down") << endl;
			#endif
			for(tempSensIT it = tempSensors.begin(); it != tempSensors.end(); ++it) {
				it->second->saveCurTemp();
			}
			for(humSensIT it = humSens.begin(); it != humSens.end(); ++it) {
				it->second->saveCurHumi();
			}
			for(pressSensIT it = pressSens.begin(); it != pressSens.end(); ++it) {
				it->second->saveCurPress();
			}
			timer2 = clock();
		}

		switch(prog) {
			case 0:
			{
				lcdClear(lcdHandle);
				break;
			}
			case 1:
			{
				lcdPrint1("Temperatures("+string(1, (unsigned char)(int)223)+"C)");

				stringstream ss;
				for(tempSensIT it = tempSensors.begin(); it != tempSensors.end(); ++it) {
					ss << (int)it->second->getTemp() << " ";
				}
				lcdPrint2(ss.str());
				break;
			}
			case 2:
			{
				lcdPrint1("Humidities(%)");
				stringstream ss;
				for(humSensIT it = humSens.begin(); it != humSens.end(); ++it) {
					ss << (int)it->second->getHumi() << " ";
				}
				lcdPrint2(ss.str());
				break;
			}
			case 3:
			{
				lcdPrint1("Pressures(hPa)");
				stringstream ss;
				for(pressSensIT it = pressSens.begin(); it != pressSens.end(); ++it) {
					ss << (int)it->second->getPress() << " ";
				}
				lcdPrint2(ss.str());
				break;
			}
		}

		if(code != NULL) {
			if(parseKey(code) == "KEY_SUSPEND") {
				if(shutdown()) {
					break;
				}
			}
			if(parseKey(code) == "KEY_MODE") {
				calibrateAnalogTempSensors();
			}
			if(parseKey(code) == "KEY_0") {
				prog = 0;
			}
			if(parseKey(code) == "KEY_1") {
				prog = 1;
			}
			if(parseKey(code) == "KEY_2") {
				prog = 2;
			}
			free(code);
		}
	}

	delete diS;
	delete diS2;
	delete dhtS;
	delete dht2S;
	delete bmp;

	deinits();

	return EXIT_SUCCESS;
}
Ejemplo n.º 10
0
static void *nogvl_ping(void *ptr) {
  MYSQL *client = ptr;

  return (void *)(mysql_ping(client) == 0 ? Qtrue : Qfalse);
}
Ejemplo n.º 11
0
/**
 * Monitor an individual server
 *
 * @param database	The database to probe
 */
static void
monitorDatabase(MONITOR_SERVERS	*database, char *defaultUser, char *defaultPasswd)
{
MYSQL_ROW	row;
MYSQL_RES	*result;
int		num_fields;
int		isjoined = 0;
char            *uname = defaultUser, *passwd = defaultPasswd;
unsigned long int	server_version = 0;
char 			*server_string;

	if (database->server->monuser != NULL)
	{
		uname = database->server->monuser;
		passwd = database->server->monpw;
	}
	if (uname == NULL)
		return;

	/* Don't even probe server flagged as in maintenance */
	if (SERVER_IN_MAINT(database->server))
		return;

	if (database->con == NULL || mysql_ping(database->con) != 0)
	{
		char *dpwd = decryptPassword(passwd);
		int rc;
		int read_timeout = 1;

		database->con = mysql_init(NULL);
		rc = mysql_options(database->con, MYSQL_OPT_READ_TIMEOUT, (void *)&read_timeout);

		if (mysql_real_connect(database->con, database->server->name,
			uname, dpwd, NULL, database->server->port, NULL, 0) == NULL)
		{
			LOGIF(LE, (skygw_log_write_flush(
				LOGFILE_ERROR,
				"Error : Monitor was unable to connect to "
				"server %s:%d : \"%s\"",
				database->server->name,
				database->server->port,
				mysql_error(database->con))));
			server_clear_status(database->server, SERVER_RUNNING);
			database->server->node_id = -1;
			free(dpwd);
			return;
		}
		free(dpwd);
	}

	/* If we get this far then we have a working connection */
	server_set_status(database->server, SERVER_RUNNING);

	/* get server version from current server */
	server_version = mysql_get_server_version(database->con);

	/* get server version string */
	server_string = (char *)mysql_get_server_info(database->con);
	if (server_string) {
		database->server->server_string = strdup(server_string);
	}	

	/* Check if the the SQL node is able to contact one or more data nodes */
	if (mysql_query(database->con, "SHOW STATUS LIKE 'Ndb_number_of_ready_data_nodes'") == 0
		&& (result = mysql_store_result(database->con)) != NULL)
	{
		num_fields = mysql_num_fields(result);
		while ((row = mysql_fetch_row(result)))
		{
			if (atoi(row[1]) > 0)
				isjoined = 1;
		}
		mysql_free_result(result);
	}

	/* Check the the SQL node id in the MySQL cluster */
	if (mysql_query(database->con, "SHOW STATUS LIKE 'Ndb_cluster_node_id'") == 0
		&& (result = mysql_store_result(database->con)) != NULL)
	{
		long cluster_node_id = -1;
		num_fields = mysql_num_fields(result);
		while ((row = mysql_fetch_row(result)))
		{
			cluster_node_id = strtol(row[1], NULL, 10);
			if ((errno == ERANGE && (cluster_node_id == LONG_MAX
				|| cluster_node_id == LONG_MIN)) || (errno != 0 && cluster_node_id == 0))
			{
				cluster_node_id = -1;
			}
			database->server->node_id = cluster_node_id;
		}
		mysql_free_result(result);
	}

	if (isjoined) {
		server_set_status(database->server, SERVER_NDB);
		database->server->depth = 0;
	} else {
		server_clear_status(database->server, SERVER_NDB);
		database->server->depth = -1;
	}
}
Ejemplo n.º 12
0
static isc_result_t
mysql_get_resultset(const char *zone, const char *record,
		    const char *client, unsigned int query,
		    void *dbdata, MYSQL_RES **rs)
{
	isc_result_t result;
	dbinstance_t *dbi = NULL;
	char *querystring = NULL;
	unsigned int i = 0;
	unsigned int j = 0;
	int qres = 0;

	if (query != COUNTZONE)
		REQUIRE(*rs == NULL);
	else
		REQUIRE(rs == NULL);

	/* get db instance / connection */
	dbi =  (dbinstance_t *) dbdata;

	/* if DBI is null, can't do anything else */
	if (dbi == NULL) {
		result = ISC_R_FAILURE;
		goto cleanup;
	}

	/* what type of query are we going to run? */
	switch(query) {
	case ALLNODES:
		/*
		 * if the query was not passed in from the config file
		 * then we can't run it.  return not_implemented, so
		 * it's like the code for that operation was never
		 * built into the driver.... AHHH flexibility!!!
		 */
		if (dbi->allnodes_q == NULL) {
			result = ISC_R_NOTIMPLEMENTED;
			goto cleanup;
		}
		break;
	case ALLOWXFR:
		/* same as comments as ALLNODES */
		if (dbi->allowxfr_q == NULL) {
			result = ISC_R_NOTIMPLEMENTED;
			goto cleanup;
		}
		break;
	case AUTHORITY:
		/* same as comments as ALLNODES */
		if (dbi->authority_q == NULL) {
			result = ISC_R_NOTIMPLEMENTED;
			goto cleanup;
		}
		break;
	case FINDZONE:
		/* this is required.  It's the whole point of DLZ! */
		if (dbi->findzone_q == NULL) {
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
				      DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2),
				      "No query specified for findzone.  "
				      "Findzone requires a query");
			result = ISC_R_FAILURE;
			goto cleanup;
		}
		break;
	case COUNTZONE:
		/* same as comments as ALLNODES */
		if (dbi->countzone_q == NULL) {
			result = ISC_R_NOTIMPLEMENTED;
			goto cleanup;
		}
		break;
	case LOOKUP:
		/* this is required.  It's also a major point of DLZ! */
		if (dbi->lookup_q == NULL) {
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
				      DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2),
				      "No query specified for lookup.  "
				      "Lookup requires a query");
			result = ISC_R_FAILURE;
			goto cleanup;
		}
		break;
	default:
		/*
		 * this should never happen.  If it does, the code is
		 * screwed up!
		 */
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "Incorrect query flag passed to "
				 "mysql_get_resultset");
		result = ISC_R_UNEXPECTED;
		goto cleanup;
	}


	/*
	 * was a zone string passed?  If so, make it safe for use in
	 * queries.
	 */
	if (zone != NULL) {
		dbi->zone = mysqldrv_escape_string((MYSQL *) dbi->dbconn,
						   zone);
		if (dbi->zone == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
	} else {	/* no string passed, set the string pointer to NULL */
		dbi->zone = NULL;
	}

	/*
	 * was a record string passed?  If so, make it safe for use in
	 * queries.
	 */
	if (record != NULL) {
		dbi->record = mysqldrv_escape_string((MYSQL *) dbi->dbconn,
						     record);
		if (dbi->record == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
	} else {	/* no string passed, set the string pointer to NULL */
		dbi->record = NULL;
	}

	/*
	 * was a client string passed?  If so, make it safe for use in
	 * queries.
	 */
	if (client != NULL) {
		dbi->client = mysqldrv_escape_string((MYSQL *) dbi->dbconn,
						     client);
		if (dbi->client == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
	} else {	/* no string passed, set the string pointer to NULL */
		dbi->client = NULL;
	}

	/*
	 * what type of query are we going to run?  this time we build
	 * the actual query to run.
	 */
	switch(query) {
	case ALLNODES:
		querystring = build_querystring(ns_g_mctx, dbi->allnodes_q);
		break;
	case ALLOWXFR:
		querystring = build_querystring(ns_g_mctx, dbi->allowxfr_q);
		break;
	case AUTHORITY:
		querystring = build_querystring(ns_g_mctx, dbi->authority_q);
		break;
	case FINDZONE:
		querystring = build_querystring(ns_g_mctx, dbi->findzone_q);
		break;
	case COUNTZONE:
		querystring = build_querystring(ns_g_mctx, dbi->countzone_q);
		break;
	case LOOKUP:
		querystring = build_querystring(ns_g_mctx, dbi->lookup_q);
		break;
	default:
		/*
		 * this should never happen.  If it does, the code is
		 * screwed up!
		 */
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "Incorrect query flag passed to "
				 "mysql_get_resultset");
		result = ISC_R_UNEXPECTED;
		goto cleanup;
	}

	/* if the querystring is null, Bummer, outta RAM.  UPGRADE TIME!!!   */
	if (querystring == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}

	/*
	 * output the full query string during debug so we can see
	 * what lame error the query has.
	 */
	isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
		      DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1),
		      "\nQuery String: %s\n", querystring);

	/* attempt query up to 3 times. */
	for (i=0; i < 3; i++) {
		qres = mysql_query((MYSQL *) dbi->dbconn, querystring);
		if (qres == 0)
			break;
		for (j=0; mysql_ping((MYSQL *) dbi->dbconn) != 0 && j < 4; j++)
			;
	}

	if (qres == 0) {
		result = ISC_R_SUCCESS;
		if (query != COUNTZONE) {
			*rs = mysql_store_result((MYSQL *) dbi->dbconn);
			if (*rs == NULL)
				result = ISC_R_FAILURE;
		}
	} else {
		result = ISC_R_FAILURE;
	}


 cleanup:
	/* it's always good to cleanup after yourself */

	/* if we couldn't even get DBI, just return NULL */
	if (dbi == NULL)
		return ISC_R_FAILURE;

	/* free dbi->zone string */
	if (dbi->zone != NULL)
		isc_mem_free(ns_g_mctx, dbi->zone);

	/* free dbi->record string */
	if (dbi->record != NULL)
		isc_mem_free(ns_g_mctx, dbi->record);

	/* free dbi->client string */
	if (dbi->client != NULL)
		isc_mem_free(ns_g_mctx, dbi->client);

	/* release query string */
	if (querystring  != NULL)
		isc_mem_free(ns_g_mctx, querystring);

	/* return result */
	return result;
}
Ejemplo n.º 13
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);
}
Ejemplo n.º 14
0
static apr_status_t dbd_mysql_check_conn(apr_pool_t *pool,
                                         apr_dbd_t *handle)
{
    return mysql_ping(handle->conn) ? APR_EGENERAL : APR_SUCCESS;
}
Ejemplo n.º 15
0
static int mysql_drive_session(eventer_t e, int mask, void *closure,
                                  struct timeval *now) {
  const char *dsn, *sql;
  char sql_buff[8192];
  char dsn_buff[512];
  mysql_check_info_t *ci = closure;
  noit_check_t *check = ci->check;
  struct timeval t1, t2, diff;
  mtev_hash_table dsn_h = MTEV_HASH_EMPTY;
  const char *host=NULL;
  const char *user=NULL;
  const char *password=NULL;
  const char *dbname=NULL;
  const char *port_s=NULL;
  const char *socket=NULL;
  const char *sslmode=NULL;
  u_int32_t port;
  unsigned long client_flag = CLIENT_IGNORE_SIGPIPE;
  unsigned int timeout;

  if(mask & (EVENTER_READ | EVENTER_WRITE)) {
    /* this case is impossible from the eventer.  It is called as
     * such on the synchronous completion of the event.
     */
    mysql_log_results(ci->self, ci->check);
    mysql_cleanup(ci->self, ci->check);
    check->flags &= ~NP_RUNNING;
    return 0;
  }
  switch(mask) {
    case EVENTER_ASYNCH_WORK:
      ci->connect_duration = NULL;
      ci->query_duration = NULL;

      FETCH_CONFIG_OR(dsn, "");
      noit_check_interpolate(dsn_buff, sizeof(dsn_buff), dsn,
                             &ci->attrs, check->config);

      mysql_parse_dsn(dsn_buff, &dsn_h);
      mtev_hash_retrieve(&dsn_h, "host", strlen("host"), (void**)&host);
      mtev_hash_retrieve(&dsn_h, "user", strlen("user"), (void**)&user);
      mtev_hash_retrieve(&dsn_h, "password", strlen("password"), (void**)&password);
      mtev_hash_retrieve(&dsn_h, "dbname", strlen("dbname"), (void**)&dbname);
      mtev_hash_retrieve(&dsn_h, "port", strlen("port"), (void**)&port_s);
      if(mtev_hash_retrieve(&dsn_h, "sslmode", strlen("sslmode"), (void**)&sslmode) &&
         !strcmp(sslmode, "require"))
        client_flag |= CLIENT_SSL;
      port = port_s ? strtol(port_s, NULL, 10) : 3306;
      mtev_hash_retrieve(&dsn_h, "socket", strlen("socket"), (void**)&socket);

      ci->conn = mysql_init(NULL); /* allocate us a handle */
      if(!ci->conn) AVAIL_BAIL("mysql_init failed");
      timeout = check->timeout / 1000;
      mysql_options(ci->conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
      if(!mysql_real_connect(ci->conn, host, user, password,
                             dbname, port, socket, client_flag)) {
        mtevL(noit_stderr, "error during mysql_real_connect: %s\n",
          mysql_error(ci->conn));
        AVAIL_BAIL(mysql_error(ci->conn));
      }
      if(mysql_ping(ci->conn))
        AVAIL_BAIL(mysql_error(ci->conn));

#if MYSQL_VERSION_ID >= 50000
      if (sslmode && !strcmp(sslmode, "require")) {
        /* mysql has a bad habit of silently failing to establish ssl and
         * falling back to unencrypted, so after making the connection, let's 
         * check that we're actually using SSL by checking for a non-NULL 
         * return value from mysql_get_ssl_cipher().
         */
        if (mysql_get_ssl_cipher(ci->conn) == NULL) {
          mtevL(nldeb, "mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
          AVAIL_BAIL("mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
        }
      }
#endif

      gettimeofday(&t1, NULL);
      sub_timeval(t1, check->last_fire_time, &diff);
      ci->connect_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
      ci->connect_duration = &ci->connect_duration_d;

      FETCH_CONFIG_OR(sql, "");
      noit_check_interpolate(sql_buff, sizeof(sql_buff), sql,
                             &ci->attrs, check->config);
      if (mysql_query(ci->conn, sql_buff))
        AVAIL_BAIL(mysql_error(ci->conn));

      gettimeofday(&t2, NULL);
      sub_timeval(t2, t1, &diff);
      ci->query_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
      ci->query_duration = &ci->query_duration_d;

      ci->result = mysql_store_result(ci->conn);
      if(!ci->result) AVAIL_BAIL("mysql_store_result failed");
      ci->rv = mysql_num_rows(ci->result);
      mysql_ingest_stats(ci);
      if(ci->result) {
        MYSQL_RES *result_swap = ci->result;
        ci->result = NULL;
        mysql_free_result(result_swap);
      }
      if(ci->conn) {
        MYSQL *conn_swap = ci->conn;
        ci->conn = NULL;
        mysql_close(conn_swap);
      }
      ci->timed_out = 0;
      mtev_hash_destroy(&dsn_h, free, free);
      return 0;
      break;
    case EVENTER_ASYNCH_CLEANUP:
      /* This sets us up for a completion call. */
      e->mask = EVENTER_READ | EVENTER_WRITE;
      break;
    default:
      abort();
  }
  return 0;
}
Ejemplo n.º 16
0
bool CdbHandler::mySQLPing(void)
{
	return (!mysql_ping(mySQLQuery_));
};
Ejemplo n.º 17
0
/**
 * Monitor an individual server
 *
 * @param handle        The MySQL Monitor object
 * @param database	The database to probe
 */
static void
monitorDatabase(MONITOR* mon, MONITOR_SERVERS *database)
{
    MM_MONITOR *handle = mon->handle;
MYSQL_ROW	  row;
MYSQL_RES	  *result;
int               isslave = 0;
int               ismaster = 0;
char		  *uname  = mon->user;
char              *passwd = mon->password;
unsigned long int server_version = 0;
char 		  *server_string;

        if (database->server->monuser != NULL)
	{
		uname = database->server->monuser;
		passwd = database->server->monpw;
	}
	
	if (uname == NULL)
		return;
        
	/* Don't probe servers in maintenance mode */
	if (SERVER_IN_MAINT(database->server))
		return;

        /** Store previous status */
        database->mon_prev_status = database->server->status;
        
	if (database->con == NULL || mysql_ping(database->con) != 0)
	{
		char *dpwd = decryptPassword(passwd);
                int  read_timeout = 1;
		if(database->con)
		    mysql_close(database->con);
                database->con = mysql_init(NULL);

                mysql_options(database->con, MYSQL_OPT_READ_TIMEOUT, (void *)&read_timeout);
                
		if (mysql_real_connect(database->con,
                                       database->server->name,
                                       uname,
                                       dpwd,
                                       NULL,
                                       database->server->port,
                                       NULL,
                                       0) == NULL)
		{
                        free(dpwd);
                        
                        if (mon_print_fail_status(database))
                        {
                                LOGIF(LE, (skygw_log_write_flush(
                                        LOGFILE_ERROR,
                                        "Error : Monitor was unable to connect to "
                                        "server %s:%d : \"%s\"",
                                        database->server->name,
                                        database->server->port,
                                        mysql_error(database->con))));
                        }

			/* The current server is not running
			 *
			 * Store server NOT running in server and monitor server pending struct
			 *
			 */
			if (mysql_errno(database->con) == ER_ACCESS_DENIED_ERROR)
			{
				server_set_status(database->server, SERVER_AUTH_ERROR);
				monitor_set_pending_status(database, SERVER_AUTH_ERROR);
			}
			server_clear_status(database->server, SERVER_RUNNING);
			monitor_clear_pending_status(database, SERVER_RUNNING);

			/* Also clear M/S state in both server and monitor server pending struct */
			server_clear_status(database->server, SERVER_SLAVE);
			server_clear_status(database->server, SERVER_MASTER);
			monitor_clear_pending_status(database, SERVER_SLAVE);
			monitor_clear_pending_status(database, SERVER_MASTER);

			/* Clean addition status too */
			server_clear_status(database->server, SERVER_STALE_STATUS);
			monitor_clear_pending_status(database, SERVER_STALE_STATUS);

			return;
		}  else {
                        server_clear_status(database->server, SERVER_AUTH_ERROR);
                        monitor_clear_pending_status(database, SERVER_AUTH_ERROR);
                }
		free(dpwd);
	}
        /* Store current status in both server and monitor server pending struct */
	server_set_status(database->server, SERVER_RUNNING);
	monitor_set_pending_status(database, SERVER_RUNNING);

	/* get server version from current server */
	server_version = mysql_get_server_version(database->con);

	/* get server version string */
	server_string = (char *)mysql_get_server_info(database->con);
	if (server_string) {
		database->server->server_string = realloc(database->server->server_string, strlen(server_string)+1);
		if (database->server->server_string)
			strcpy(database->server->server_string, server_string);
	}

        /* get server_id form current node */
        if (mysql_query(database->con, "SELECT @@server_id") == 0
                && (result = mysql_store_result(database->con)) != NULL)
        {
                long server_id = -1;

		if(mysql_field_count(database->con) != 1)
		{
		    mysql_free_result(result);
		    skygw_log_write(LE,"Error: Unexpected result for 'SELECT @@server_id'. Expected 1 column."
				    " MySQL Version: %s",version_str);
		    return;
		}

                while ((row = mysql_fetch_row(result)))
                {
                        server_id = strtol(row[0], NULL, 10);
                        if ((errno == ERANGE && (server_id == LONG_MAX
                                || server_id == LONG_MIN)) || (errno != 0 && server_id == 0))
                        {
                                server_id = -1;
                        }
                        database->server->node_id = server_id;
                }
                mysql_free_result(result);
        }

	/* Check if the Slave_SQL_Running and Slave_IO_Running status is
	 * set to Yes
	 */

	/* Check first for MariaDB 10.x.x and get status for multimaster replication */
	if (server_version >= 100000) {

		if (mysql_query(database->con, "SHOW ALL SLAVES STATUS") == 0
			&& (result = mysql_store_result(database->con)) != NULL)
		{
			int i = 0;
			long master_id = -1;

			if(mysql_field_count(database->con) < 42)
			{
			    mysql_free_result(result);
			    skygw_log_write(LE,"Error: \"SHOW ALL SLAVES STATUS\" "
				    "returned less than the expected amount of columns. Expected 42 columns"
				    " MySQL Version: %s",version_str);
			    return;
			}

			while ((row = mysql_fetch_row(result)))
			{
				/* get Slave_IO_Running and Slave_SQL_Running values*/
				if (strncmp(row[12], "Yes", 3) == 0
						&& strncmp(row[13], "Yes", 3) == 0) {
					isslave += 1;
				}

				/* If Slave_IO_Running = Yes, assign the master_id to current server: this allows building 
				 * the replication tree, slaves ids will be added to master(s) and we will have at least the 
				 * root master server.
				 * Please note, there could be no slaves at all if Slave_SQL_Running == 'No'
				 */
				if (strncmp(row[12], "Yes", 3) == 0) {
					/* get Master_Server_Id values */
                                        master_id = atol(row[41]);
                                        if (master_id == 0)
                                                master_id = -1;
				}

				i++;
			}
			/* store master_id of current node */
			memcpy(&database->server->master_id, &master_id, sizeof(long));

			mysql_free_result(result);

			/* If all configured slaves are running set this node as slave */
			if (isslave > 0 && isslave == i)
				isslave = 1;
			else
				isslave = 0;
		}
	} else {	
		if (mysql_query(database->con, "SHOW SLAVE STATUS") == 0
			&& (result = mysql_store_result(database->con)) != NULL)
		{
			long master_id = -1;

			if(mysql_field_count(database->con) < 40)
			{
			    mysql_free_result(result);

			    if(server_version < 5*10000 + 5*100)
			    {
				if(database->log_version_err)
				{
				    skygw_log_write(LE,"Error: \"SHOW SLAVE STATUS\" "
					    " for versions less than 5.5 does not have master_server_id, "
					    "replication tree cannot be resolved for server %s."
					    " MySQL Version: %s",database->server->unique_name,version_str);
				    database->log_version_err = false;
				}
			    }
			    else
			    {
				skygw_log_write(LE,"Error: \"SHOW SLAVE STATUS\" "
					"returned less than the expected amount of columns. Expected 40 columns."
					" MySQL Version: %s",version_str);
			    }
			    return;
			}

			while ((row = mysql_fetch_row(result)))
			{
				/* get Slave_IO_Running and Slave_SQL_Running values*/
				if (strncmp(row[10], "Yes", 3) == 0
						&& strncmp(row[11], "Yes", 3) == 0) {
					isslave = 1;
				}

				/* If Slave_IO_Running = Yes, assign the master_id to current server: this allows building 
				 * the replication tree, slaves ids will be added to master(s) and we will have at least the 
				 * root master server.
				 * Please note, there could be no slaves at all if Slave_SQL_Running == 'No'
				 */
				if (strncmp(row[10], "Yes", 3) == 0) {
					/* get Master_Server_Id values */
					master_id = atol(row[39]);
					if (master_id == 0)
						master_id = -1;
				}
			}
			/* store master_id of current node */
			memcpy(&database->server->master_id, &master_id, sizeof(long));

			mysql_free_result(result);
		}
	}

	/* get variable 'read_only' set by an external component */
	if (mysql_query(database->con, "SHOW GLOBAL VARIABLES LIKE 'read_only'") == 0
		&& (result = mysql_store_result(database->con)) != NULL)
	{
		if(mysql_field_count(database->con) < 2)
		{
		    mysql_free_result(result);
		    skygw_log_write(LE,"Error: Unexpected result for \"SHOW GLOBAL VARIABLES LIKE 'read_only'\". Expected 2 columns."
				    " MySQL Version: %s",version_str);
		    return;
		}

		while ((row = mysql_fetch_row(result)))
		{
			if (strncasecmp(row[1], "OFF", 3) == 0) {
				ismaster = 1;
			} else {
				isslave = 1;
			}
		}
		mysql_free_result(result);
	}

	/* Remove addition info */
	monitor_clear_pending_status(database, SERVER_STALE_STATUS);

	/* Set the Slave Role */
	if (isslave)
	{
		monitor_set_pending_status(database, SERVER_SLAVE);
		/* Avoid any possible stale Master state */
		monitor_clear_pending_status(database, SERVER_MASTER);

		/* Set replication depth to 1 */
		database->server->depth = 1;
	} else {
		/* Avoid any possible Master/Slave stale state */
		monitor_clear_pending_status(database, SERVER_SLAVE);
		monitor_clear_pending_status(database, SERVER_MASTER);
	}

	/* Set the Master role */
        if (ismaster)
        {
		monitor_clear_pending_status(database, SERVER_SLAVE);
                monitor_set_pending_status(database, SERVER_MASTER);

		/* Set replication depth to 0 */
		database->server->depth = 0;
        }

}
Ejemplo n.º 18
0
int DBConnection::ExecuteSQL(const string& strSQL, MYSQL_RES** res, int& iRelt, unsigned long long* iInsertId)
{
    if (m_pSQLConn == NULL){
        return SQL_TYPE_UNKNOW;
    }
    int iTimes = DB_RECONNECT_TIMES;
    bool bTest = true;
	bool bHasUnlock=false;
    while (iTimes-- > 0){
    	if( m_pSQLConn != NULL ) {
        	if( mysql_ping(m_pSQLConn) != 0 ) {
                bTest = false;
        		if(!bHasUnlock) Unlock();//�Ƚ�����ΪConnect�е�DisConnect��TestIdle��Ҫ����
        		bHasUnlock = true;
                if (Connect()){
                    bTest = true;
                    break;
                }

        	} else {
        		bTest = true;
        		break;
        	}

    	} else {
            bTest = false;
    		if(!bHasUnlock) Unlock();//�Ƚ�����ΪConnect�е�DisConnect��TestIdle��Ҫ����
    		bHasUnlock = true;
            if (Connect()){
                bTest = true;
                break;
            }
    	}

    	usleep(DB_RECONNECT_TIMEOUT);
    }
	if(bHasUnlock)Lock();
    if (!bTest){
        return SQL_TYPE_UNKNOW;
    }
    if (mysql_query(m_pSQLConn, strSQL.c_str()) != 0){
        return SQL_TYPE_UNKNOW;
    }
    int iType = SQLtype(strSQL);
    switch (iType) {
        case SQL_TYPE_SELECT:
            m_pSQLRes = mysql_store_result(m_pSQLConn);
            if (m_pSQLRes==NULL){
            	if( mysql_field_count(m_pSQLConn)!=0 ) {
					iRelt = 0;
            	} else {
            		return SQL_TYPE_UNKNOW;
            	}

            }else{
				*res = m_pSQLRes;
				iRelt = mysql_num_rows(m_pSQLRes);

            }
            break;
        case SQL_TYPE_INSERT: {
        	if( iInsertId != NULL ) {
        		*iInsertId = mysql_insert_id(m_pSQLConn);
        	}
        }
        case SQL_TYPE_REPLACE:
        case SQL_TYPE_UPDATE:
        case SQL_TYPE_DELETE:
        default:
            iRelt = mysql_affected_rows(m_pSQLConn);
            break;
    }
    return iType;
}
Ejemplo n.º 19
0
void MySqlConnection::Ping()
{
	mysql_ping(m_Mysql);
}
Ejemplo n.º 20
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"); }
}
Ejemplo n.º 21
0
void client (net_t *c)
{
    net_t net;
    char temp[128], query[MAXLEN], *type, *what;
	int have = 0;
	MYSQL_RES *result;
	MYSQL_ROW row;

    memcpy (&net, c, sizeof (net_t));

    memset (temp, 0, sizeof (temp));
    memset (query,0, sizeof (query));

    net_domain_recv (&net, 0, temp, sizeof (temp));

    type = strtok(temp,":");
    what = strtok(NULL,":");

    if(mysql_ping(&db))
       fprintf(stderr,"[%s]: Conexao com o banco encerrada, reconectando\n", timestamp());
	switch (atoi(type)) {
	   	case 0:
			snprintf(query,MAXLEN,"SELECT %s FROM %s WHERE (STRCMP(%s,'#%s') = 0)",CHANURL, CHANTBL, CHANCMP, what);
			have++;
			break;
		case 1:
			snprintf(query,MAXLEN,"SELECT %s FROM %s WHERE %s = '%s'", USRURL, USRTBL, USRCMP, what);
			have++;
			break;
		default:
			fprintf(stderr,"[%s]: Table (%s) does not exist!\n",timestamp(),type);
			break;
	}
	if (have) {
		if (mysql_query(&db,query)) {
			fprintf(stderr,"[%s]: Query (%s) Status (%s)\n",timestamp(),query,mysql_error(&db));
			have--;
		} else {
			result = mysql_store_result(&db);
			if (!mysql_num_rows(result) || result == NULL || !mysql_num_fields(result)) {
				fprintf(stderr,"[%s]: Query (%s) Return (%s)\n",timestamp(),query,"Not Found");
				have--;
			} else {
				if ((row = mysql_fetch_row(result))) {
					if ((char *)row[0] != NULL) {
						fprintf(stderr,"[%s]: Query (%s) Return (%s)\n",timestamp(),query,(char *)row[0]);
					} else {
						fprintf(stderr,"[%s]: Query (%s) Return (%s)\n",timestamp(),query,"Not Found");
						have--;
					}
				}
			}
		}
	}
	if (!net_domain_send (&net, (have) ? (char *)row[0] : "0", strlen((have) ? (char *)row[0] : "0"))) {
		fprintf(stderr,"[%s]: Cannot send to socket (%s)\n",timestamp(), (have) ? (char *)row[0] : "Not Found");
	}
	if (have) 
		mysql_free_result(result);
    net_domain_finish (&net);
    _exit (1);
}
Ejemplo n.º 22
0
/**
 * Monitor an individual server
 *
 * @param handle        The MySQL Monitor object
 * @param database      The database to probe
 */
static void
monitorDatabase(MONITOR *mon, MONITOR_SERVERS *database)
{
    GALERA_MONITOR* handle = (GALERA_MONITOR*)mon->handle;
MYSQL_ROW	row;
MYSQL_RES	*result,*result2;
int		isjoined = 0;
char		*uname  = mon->user;
char		*passwd = mon->password;
unsigned long int	server_version = 0;
char 			*server_string;

	if (database->server->monuser != NULL)
	{
		uname = database->server->monuser;
		passwd = database->server->monpw;
	}
	if (uname == NULL)
		return;

	/* Don't even probe server flagged as in maintenance */
	if (SERVER_IN_MAINT(database->server))
		return;

	/** Store previous status */
	database->mon_prev_status = database->server->status;

	if (database->con == NULL || mysql_ping(database->con) != 0)
	{
		char *dpwd = decryptPassword(passwd);
		int connect_timeout = mon->connect_timeout;
		int read_timeout = mon->read_timeout;
		int write_timeout = mon->write_timeout;

		if(database->con)
		    mysql_close(database->con);
		database->con = mysql_init(NULL);

		mysql_options(database->con, MYSQL_OPT_CONNECT_TIMEOUT, (void *)&connect_timeout);
		mysql_options(database->con, MYSQL_OPT_READ_TIMEOUT, (void *)&read_timeout);
		mysql_options(database->con, MYSQL_OPT_WRITE_TIMEOUT, (void *)&write_timeout);

		if (mysql_real_connect(database->con, database->server->name,
			uname, dpwd, NULL, database->server->port, NULL, 0) == NULL)
		{
			free(dpwd);

			server_clear_status(database->server, SERVER_RUNNING);

			/* Also clear Joined, M/S and Stickiness bits */
			server_clear_status(database->server, SERVER_JOINED);
			server_clear_status(database->server, SERVER_SLAVE);
			server_clear_status(database->server, SERVER_MASTER);
			server_clear_status(database->server, SERVER_MASTER_STICKINESS);

			if (mysql_errno(database->con) == ER_ACCESS_DENIED_ERROR)
			{
				server_set_status(database->server, SERVER_AUTH_ERROR);
			}

			database->server->node_id = -1;

			if (mon_status_changed(database) && mon_print_fail_status(database))
			{
				LOGIF(LE, (skygw_log_write_flush(
					LOGFILE_ERROR,
					"Error : Monitor was unable to connect to "
					"server %s:%d : \"%s\"",
					database->server->name,
					database->server->port,
					mysql_error(database->con))));
			}

			return;
		}
		else
		{
			server_clear_status(database->server, SERVER_AUTH_ERROR);
		}
		free(dpwd);
	}

	/* If we get this far then we have a working connection */
	server_set_status(database->server, SERVER_RUNNING);

	/* get server version string */
	server_string = (char *)mysql_get_server_info(database->con);
	if (server_string) {
		database->server->server_string = realloc(database->server->server_string, strlen(server_string)+1);
		if (database->server->server_string)
			strcpy(database->server->server_string, server_string);
	}	

	/* Check if the the Galera FSM shows this node is joined to the cluster */
	if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_state'") == 0
		&& (result = mysql_store_result(database->con)) != NULL)
	{
		if(mysql_field_count(database->con) < 2)
		{
		    mysql_free_result(result);
		    skygw_log_write(LE,"Error: Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_state'\". Expected 2 columns."
				    " MySQL Version: %s",version_str);
		    return;
		}

		while ((row = mysql_fetch_row(result)))
		{
			if (strcmp(row[1], "4") == 0) 
				isjoined = 1;
	
			/* Check if the node is a donor and is using xtrabackup, in this case it can stay alive */
			else if (strcmp(row[1], "2") == 0 && handle->availableWhenDonor == 1) {
				if (mysql_query(database->con, "SHOW VARIABLES LIKE 'wsrep_sst_method'") == 0
					&& (result2 = mysql_store_result(database->con)) != NULL)
				{
				    		if(mysql_field_count(database->con) < 2)
						{
						    mysql_free_result(result);
						    mysql_free_result(result2);
						    skygw_log_write(LE,"Error: Unexpected result for \"SHOW VARIABLES LIKE 'wsrep_sst_method'\". Expected 2 columns."
							    " MySQL Version: %s",version_str);
						    return;
						}
					while ((row = mysql_fetch_row(result)))
					{
						if (strncmp(row[1], "xtrabackup", 10) == 0)
							isjoined = 1;
					}
					mysql_free_result(result2);
				}
			}
		}
		mysql_free_result(result);
	}

	/* Check the the Galera node index in the cluster */
	if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_index'") == 0
		&& (result = mysql_store_result(database->con)) != NULL)
	{
		long local_index = -1;

		if(mysql_field_count(database->con) < 2)
		{
		    mysql_free_result(result);
		    skygw_log_write(LE,"Error: Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_index'\". Expected 2 columns."
							    " MySQL Version: %s",version_str);
		    return;
		}

		while ((row = mysql_fetch_row(result)))
		{
			local_index = strtol(row[1], NULL, 10);
			if ((errno == ERANGE && (local_index == LONG_MAX
				|| local_index == LONG_MIN)) || (errno != 0 && local_index == 0))
			{
				local_index = -1;
			}
			database->server->node_id = local_index;
		}
		mysql_free_result(result);
	}

	if (isjoined)
		server_set_status(database->server, SERVER_JOINED);
	else
		server_clear_status(database->server, SERVER_JOINED);
}
Ejemplo n.º 23
0
static Variant HHVM_FUNCTION(mysql_ping,
                   const Variant& link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return init_null();
  return !mysql_ping(conn);
}
Ejemplo n.º 24
0
bool SupplyEntryDBInterface::RetrieveSupplyEntry(ProjectKeywords& keyword, vector<QueryHit>& supplies, HWND hwnd)
{
	int ret = -1;
	
	CString project = keyword.m_project_name.c_str();

//	project.Replace("\\","\\\\");			// replace the backslash with a "_"
//	project.Replace("\'", "\\\'");		// replace the single quote "'"

	if(project.GetLength() > 50)
	{
		project.Truncate(50);
	}

	CString table = "SUPPLY_TABLE_";
	table += project;
	table.Replace('\\','_');			// replace the backslash with _
	table.Replace('\'', '_');		// replace the single quote "'" with _
	table.Replace(' ', '_');
	table.Replace('-', '_');
	table.Replace('&', '_');
	table.Replace('!', '_');
	table.Replace('$', '_');
	table.Replace('@', '_');
	table.Replace('%', '_');
	table.Replace('(', '_');
	table.Replace(')', '_');
	table.Replace('+', '_');
	table.Replace('~', '_');
	table.Replace('*', '_');
	table.Replace('.', '_');
	table.Replace(',', '_');
	table.Replace('?', '_');
	table.Replace(':', '_');
	table.Replace(';', '_');
	table.Replace('"', '_');
	table.Replace('/', '_');
	table.Replace('#', '_');


	char temp[32];
	CString query_str;
	int track;

	for(int i=0; i==0 || i<keyword.m_supply_keywords.v_keywords.size(); i++)
	{
		if(keyword.m_supply_keywords.v_keywords.size() > 0)
			track = keyword.m_supply_keywords.v_keywords[i].m_track;
		else
			 track = 0;
		
		//post the query status to the main window
		char status[256+1];
		sprintf(status, "%s - Track: %d", keyword.m_project_name.c_str(), track);
		PostMessage(hwnd,WM_SUPPLY_MANAGER_THREAD_PROJECT,(WPARAM)status,0);

		query_str = "SELECT distinct hash, filename, filesize, bitrate, frequency, duration, count(*) as total from ";
		query_str += table;
		query_str += " where track = ";
		query_str += itoa(track, temp, 10);
		if(keyword.m_search_type == ProjectKeywords::audio)
			query_str += " and filesize <= 10000000 ";
		query_str += " group by hash";
		query_str += " order by total desc limit ";

		//if this is single, doubling up the limit
		if(track!=0)
		{
			if(keyword.m_supply_keywords.v_keywords[i].m_single == true)
				query_str += itoa(400, temp, 10);
			else
				//query_str += itoa(200, temp, 10);
				continue; //not protecting non-singles
		}
		else
			query_str += itoa(200, temp, 10);

		ret = mysql_query(p_supply_conn, query_str);

		if(mysql_error(p_supply_conn)[0] != '\0')
		{
			CStdioFile file;
			if( file.Open("SQL_Supply_Entry_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0)
			{
				file.SeekToEnd();

				CString log;
				log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S");
				log += " RetrieveSupplyEntry(...) ";
				log += query_str;
				log += "\n";
				log += "Error: ";
				log += mysql_error(p_supply_conn);
				log += "\n\n";

				file.WriteString(log);
				file.Close();
			}
			else
			{
				DWORD error = GetLastError();
				//MessageBox(NULL, "File Open Error: SQL_Supply_Entry_Error_Log.txt", "File Open Error", MB_OK);
			}

			TRACE(mysql_error(p_supply_conn));
			TRACE("\n");
			TRACE(query_str);
			TRACE("\n");

			//retry this query and reconnect to db
			mysql_ping(p_supply_conn);

			i--;
			if(i<0)
				i=0;
			continue;
		}

		MYSQL_RES *res=NULL;
		MYSQL_ROW row;

		res=mysql_store_result(p_supply_conn);	// allocates memory
		if(res != NULL)
		{
			UINT num_row = (UINT)mysql_num_rows(res);
			if(num_row > 0)
			{
				while ((row = mysql_fetch_row(res)))
				{
					QueryHit info;
					if(row[0]!=NULL)
					{
						HashConversion fthash;
						fthash.HashDecode16(row[0]);
						memset(&info.m_hash,0,sizeof(info.m_hash));
						memcpy(info.m_hash,fthash.m_data,sizeof(info.m_hash));
					}
					if(row[1]!=NULL)
						info.m_filename = row[1];
					if(row[2]!=NULL)
						info.m_file_size = atol(row[2]);
					if(row[3]!=NULL)
						info.m_bitrate = atoi(row[3]);
					if(row[4]!=NULL)
						info.m_sample_frequency = atoi(row[4]);
					if(row[5]!=NULL)
						info.m_duration = atoi(row[5]);


					info.m_track = track;
					info.m_project_id = keyword.m_id;
					info.m_project = keyword.m_project_name.c_str();
					
					switch(keyword.m_search_type)
					{
						case ProjectKeywords::search_type::audio:
						{
							info.m_media_type = MEDIA_TYPE_AUDIO;
							break;
						}
						case ProjectKeywords::search_type::video:
						{
							info.m_media_type = MEDIA_TYPE_VIDEO;
							break;
						}
						case ProjectKeywords::search_type::software:
						{
							info.m_media_type = MEDIA_TYPE_SOFTWARE;
							break;
						}
					}
					/*
					int popularity=0; //share more popular title
					if(row[3]!=NULL)
						popularity=atoi(row[3]);
					popularity /= 100;
					if(popularity > 100)
						popularity = 100;
					if(popularity <= 0)
						popularity = 1;
					for(int j=0;j<popularity;j++)
						supplies.push_back(info);
					*/
					supplies.push_back(info);
				}
			}
		}
		mysql_free_result(res);	// free memory

	}

	if(ret==0)
		return true;
	else
		return false;
}
Ejemplo n.º 25
0
/* TBL_Select
**
** Purpose:
**	This function selects some number of records (possibly zero),
**	that match the criteria specifications given in the input
**	parameter criteriaList.
**
** Parameter Dictionary:
**	TBL_HANDLE **handle: The pointer for the database/table pair
**		to be accessed.  This table must be open.
**	TBL_CRITERIA *criteriaList: Contains a list of the criteria
**		to use when selecting records from the specified table.
**		A null list implies that all records will be selected.
**	TBL_FIELD *fieldList: Contains a list of the fields to be
**		retreived from each record that matches the criteria
**		specification.  It is an error to specify a null
**		fieldList.
**	int *count: Contains a number that represents the total number
**		of records retreived by this particular select.  If this
**		parameter is null, then an internal counter is used and
**		the final count will not be returned when the select
**		finishes.
**	CONDITION (*callback)(): The callback function invoked whenever
**		a new record is retreived from the database.  It is
**		invoked with parameters as described below.
**	void *ctx: Ancillary data passed through to the callback function
**		and untouched by this routine.
**
** Return Values:
**	TBL_NORMAL: normal termination.
**	TBL_BADHANDLE: The handle passed to the routine was invalid.
**	TBL_DBNOEXIST: The database specified does not exist.
**	TBL_NOFIELDLIST: A null field list pointer (fieldList *) was
**		specified.
**	TBL_SELECTFAILED: The select operation failed most probably from
**		a bad specification in the fieldList or criteriaList.  This
**		return is not the same as a valid query returning no records.
**		This error return could result from a misspelled keyword, etc.
**	TBL_EARLYEXIT: The callback routine returned something other than
**		TBL_NORMAL which caused this routine to cancel the remainder
**		of the database operation and return early.
**
** Algorithm:
**	As each record is retreived from the
**	database, the fields requested by the user (contained in
**	fieldList), are filled with the informatiton retreived from
**	the database and a pointer to the list is passed to the
**	callback routine designated by the input parameter callback.
**	The callback routine is invoked as follows:
**
**		callback(fieldList *fieldList, long count, void *ctx)
**
**	The count contains the number of records retreived to this point.
**	ctx contains any additional information the user originally passed
**	to this select function.  If callback returns any value other
**	than TBL_NORMAL, it is assumed that this function should terminate
**	(i.e. cancel the current db operation), and return an abnormal
**	termination message (TBL_EARLYEXIT) to the routine which
**	originally invoked the select.
*/
CONDITION
TBL_Select(TBL_HANDLE ** handle, const TBL_CRITERIA * criteriaList,
           TBL_FIELD * fieldList, long *count, CONDITION(*callback) (), void *ctx)
{
    TBL_CONTEXT
    * tc;
    TBL_FIELD
    * fp;
    TBL_CRITERIA
    * cp;
    char
    *dbName,
    *tableName;
    int
    i,
    foundit;
    long
    realcount,
    *lp;
    MYSQL_ROW
    row;
    MYSQL_RES
    * ans;

#ifdef CTN_USE_THREADS
    THR_ObtainMutex();
#endif

    tc = G_ContextHead;
    foundit = 0;
    while (tc != (TBL_CONTEXT *) NULL) {
        if (tc == (TBL_CONTEXT *) (*handle)) {
            dbName = tc->databaseName;
            tableName = tc->tableName;
            foundit = 1;
        }
        tc = tc->next;
    }
    if (!foundit) {
#ifdef CTN_USE_THREADS
        THR_ReleaseMutex();
#endif
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_Select");
    }

    if (mysql_select_db(&mysql, dbName) != 0) {
#ifdef CTN_USE_THREADS
        THR_ReleaseMutex();
#endif
        (void) COND_PushCondition(TBL_ERROR(TBL_DBSPECIFIC), "mySQL",
                                  mysql_error(&mysql), "TBL_Select");
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_Select");
    }

    /*
     * We found the names we need...just assume we can access it (for now).
     */
    if ((fieldList == (TBL_FIELD *) NULL) || (fieldList->FieldName == 0)) {
#ifdef CTN_USE_THREADS
        THR_ReleaseMutex();
#endif
        return COND_PushCondition(TBL_ERROR(TBL_NOFIELDLIST), "TBL_Select");
    }
    /*
     * Set up the select statement
     */
    mysqlcmd(&G_DBSelect, "SELECT ");
    fp = fieldList;
    Add_FieldName_to_Buf(G_DBSelect, fp);
    fp++;
    while (fp->FieldName != NULL) {
        mysqlcmd(&G_DBSelect, ",");
        Add_FieldName_to_Buf(G_DBSelect, fp);
        fp++;
    }
    mysqlcmd(&G_DBSelect, "FROM ");
    Add_String_to_Buf(G_DBSelect, tableName);
    cp = criteriaList;
    if ((cp != (TBL_CRITERIA *) NULL) && (cp->FieldName != 0)) {
        mysqlcmd(&G_DBSelect, " WHERE ");
        Add_Criteria_to_Buf(G_DBSelect, cp);
        cp++;
        while (cp->FieldName != NULL) {
            mysqlcmd(&G_DBSelect, " AND ");
            Add_Criteria_to_Buf(G_DBSelect, cp);
            cp++;
        }
    }
    if (count != (long *) NULL)
        lp = count;
    else
        lp = &realcount;
    *lp = 0;

    mysql_ping(&mysql);
    if (mysql_real_query(&mysql, G_DBSelect, (unsigned int)strlen(G_DBSelect)) != 0) {
        mysqlfreebuf(&G_DBSelect);
#ifdef CTN_USE_THREADS
        THR_ReleaseMutex();
#endif
        (void) COND_PushCondition(TBL_ERROR(TBL_DBSPECIFIC), "mySQL",
                                  mysql_error(&mysql), "TBL_Select");
        return COND_PushCondition(TBL_ERROR(TBL_SELECTFAILED), DATABASE, "TBL_Select");
    }
    ans = mysql_store_result(&mysql);
    while ((row = (MYSQL_ROW) mysql_fetch_row(ans)) != (MYSQL_ROW) NULL) {
        (*lp)++;
        for (fp = fieldList, i = 0; fp->FieldName != NULL; fp++, i++) {
            fp->Value.IsNull = 0;
            switch (fp->Value.Type) {
            case TBL_SIGNED2:
                fp->Value.Size = 2;
                if (row[i] == NULL)
                    *(fp->Value.Value.Signed2) = BIG_2;
                else
                    *(fp->Value.Value.Signed2) = atoi(row[i]);
                if (*(fp->Value.Value.Signed2) == BIG_2) {
                    fp->Value.IsNull = 1;
                    fp->Value.Size = 0;
                }
                break;
            case TBL_UNSIGNED2:
                fp->Value.Size = 2;
                if (row[i] == NULL)
                    *(fp->Value.Value.Unsigned2) = BIG_2;
                else
                    *(fp->Value.Value.Unsigned2) = atoi(row[i]);
                if (*(fp->Value.Value.Unsigned2) == BIG_2) {
                    fp->Value.IsNull = 1;
                    fp->Value.Size = 0;
                }
                break;
            case TBL_SIGNED4:
                fp->Value.Size = 4;
                if (row[i] == NULL)
                    *(fp->Value.Value.Signed4) = BIG_4;
                else
                    *(fp->Value.Value.Signed4) = atoi(row[i]);
                if (*(fp->Value.Value.Signed4) == BIG_4) {
                    fp->Value.IsNull = 1;
                    fp->Value.Size = 0;
                }
                break;
            case TBL_UNSIGNED4:
                fp->Value.Size = 4;
                if (row[i] == NULL)
                    *(fp->Value.Value.Unsigned4) = BIG_4;
                else
                    *(fp->Value.Value.Unsigned4) = atoi(row[i]);
                if (*(fp->Value.Value.Unsigned4) == BIG_4) {
                    fp->Value.IsNull = 1;
                    fp->Value.Size = 0;
                }
                break;
            case TBL_FLOAT4:
                fp->Value.Size = 4;
                if (row[i] == NULL)
                    *(fp->Value.Value.Float4) = BIG_4;
                else
                    *(fp->Value.Value.Float4) = atof(row[i]);
                if (*(fp->Value.Value.Float4) == BIG_4) {
                    fp->Value.IsNull = 1;
                    fp->Value.Size = 0;
                }
                break;
            case TBL_FLOAT8:
                fp->Value.Size = 8;
                if (row[i] == NULL)
                    *(fp->Value.Value.Float8) = BIG_4;
                else
                    *(fp->Value.Value.Float8) = atof(row[i]);
                if (*(fp->Value.Value.Float8) == BIG_4) {
                    fp->Value.IsNull = 1;
                    fp->Value.Size = 0;
                }
                break;
            case TBL_TEXT:
            case TBL_BINARYDATA:
            case TBL_STRING:
                fp->Value.Size = fp->Value.AllocatedSize;
                if (row[i] == NULL)
                    fp->Value.Value.String[0] = '\0';
                else
                    strncpy(fp->Value.Value.String, row[i], fp->Value.AllocatedSize - 1);
                if (strcmp(fp->Value.Value.String, "") == 0) {
                    fp->Value.IsNull = 1;
                    fp->Value.Size = 0;
                }
                break;
            }
        }
        if (callback != NULL) {
            if (callback(fieldList, *lp, ctx) != TBL_NORMAL) {
                mysqlfreebuf(&G_DBSelect);
                mysql_free_result(ans);
#ifdef CTN_USE_THREADS
                THR_ReleaseMutex();
#endif
                return COND_PushCondition(TBL_ERROR(TBL_EARLYEXIT), "TBL_Select");
            }
        }
    }

    mysqlfreebuf(&G_DBSelect);
    mysql_free_result(ans);
#ifdef CTN_USE_THREADS
    THR_ReleaseMutex();
#endif
    return TBL_NORMAL;
}
Ejemplo n.º 26
0
/// Pings the connection.
int Sql_Ping(Sql* self)
{
	if( self && mysql_ping(&self->handle) == 0 )
		return SQL_SUCCESS;
	return SQL_ERROR;
}
Ejemplo n.º 27
0
/* TBL_NextUnique
**
** Purpose:
**	This routine retrieves the next unique number from a predefined table.
**
** Parameter Dictionary:
**	TBL_HANDLE **handle: The pointer for the database/table pair
**		to be accessed for modification.  This table must be open.
**	char *name : The name of the unique variable to access.
**	int *unique: Contains the next unique number in the sequence upon
**			return.
**
** Return Values:
**	TBL_NORMAL: normal termination.
**	TBL_BADHANDLE: The handle passed to the routine was invalid.
**	TBL_DBNOEXIST: The database specified does not exist.
**	TBL_SELECTFAILED: The unique number name could not be found.
**	TBL_UPDATEFAILED: The unique number could not be incremented.
**
** Notes:
**	Nothing unusual.
**
** Algorithm:
**	The unique number associated with  "name" in the opened table is
**	retrieved and passed back to the user in "unique".  This number is
**	then incremented (by one) and placed back in the table in preparation
**	for the next call to this routine.
*/
CONDITION
TBL_NextUnique(TBL_HANDLE ** handle, char *name, int *unique)
{
    TBL_CONTEXT
    * tc;
    char
    num[20],
        *dbName,
        *tableName;
    int
    i,
    ret,
    foundit;
    MYSQL_ROW
    row;
    MYSQL_RES
    * ans;

    tc = G_ContextHead;
    foundit = 0;
    while (tc != (TBL_CONTEXT *) NULL) {
        if (tc == (TBL_CONTEXT *) (*handle)) {
            dbName = tc->databaseName;
            tableName = tc->tableName;
            foundit = 1;
        }
        tc = tc->next;
    }
    if (!foundit) {
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_NextUnique");
    }

    if (mysql_select_db(&mysql, dbName) != 0) {
        return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_NextUnique");
    }

    mysqlcmd(&G_DBNextUnique, "SELECT UniqueNumber FROM ");
    Add_String_to_Buf(G_DBNextUnique, tableName);
    mysqlcmd(&G_DBNextUnique, " WHERE NumberName='");
    mysqlcmd(&G_DBNextUnique, name);
    mysqlcmd(&G_DBNextUnique, "'");

    mysql_ping(&mysql);
    if (mysql_real_query(&mysql, G_DBNextUnique, (unsigned int)strlen(G_DBNextUnique)) != 0) {
        mysqlfreebuf(&G_DBNextUnique);
        return COND_PushCondition(TBL_ERROR(TBL_SELECTFAILED), DATABASE, "TBL_NextUnique");
    }
    *unique = -1;
    ans = mysql_store_result(&mysql);
    if ((row = (MYSQL_ROW) mysql_fetch_row(ans)) != (MYSQL_ROW) NULL) {
        *unique = atoi(row[0]);
    } else {
        mysqlfreebuf(&G_DBNextUnique);
        mysql_free_result(ans);
        return COND_PushCondition(TBL_ERROR(TBL_SELECTFAILED), DATABASE, "TBL_NextUnique");
    }
    mysql_free_result(ans);
    /*
     * Now perform the update...
     */
    i = *unique + 1;
    mysqlfreebuf(&G_DBNextUnique);
    mysqlcmd(&G_DBNextUnique, "UPDATE ");
    Add_String_to_Buf(G_DBNextUnique, tableName);
    mysqlcmd(&G_DBNextUnique, " SET UniqueNumber=");
    sprintf(num, " %d ", i);
    Add_String_to_Buf(G_DBNextUnique, num);
    mysqlcmd(&G_DBNextUnique, " WHERE NumberName='");
    mysqlcmd(&G_DBNextUnique, name);
    mysqlcmd(&G_DBNextUnique, "'");


    if (mysql_real_query(&mysql, G_DBNextUnique, (unsigned int)strlen(G_DBNextUnique)) != 0) {
        mysqlfreebuf(&G_DBNextUnique);
        return COND_PushCondition(TBL_ERROR(TBL_UPDATEFAILED), DATABASE, "TBL_NextUnique");
    }
    mysqlfreebuf(&G_DBNextUnique);
    return TBL_NORMAL;
}
Ejemplo n.º 28
0
void *
mysql_connector(void *args) {
    char *neaf;

    char *uid;
    char *birth_year;
    char *birth_month;
    char *birth_day;
    char *constellation;
    char *blood_types;
    char *sex;
    char *home_nation;
    char *home_pro;
    char *home_city;
    char *now_nation;
    char *now_pro;
    char *now_city;

    char *header;

    char *edu;
    char *school;
    char *department;
    char *class_;
    char *year;

    char *begin_year;
    char *begin_month;
    char *end_year;
    char *end_month;
    char *company;
    char *post;

    char *update_proto;
    char *delete_proto;
    char *insert_proto;

    int mysql_query_rc;
    int flag;

    void *pop_string;
    char *raw_string;
    char *tmp;
    unsigned long long affect;
    int raw_len;

    MYSQL mysql;

    my_bool reconnect = 1;

    mysql_init(&mysql);
    mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);

    /* Connect to mysql server */
    if(!mysql_real_connect(
                &mysql, server.mysqlIP, server.mysqlUser,
                server.mysqlPasswd, server.db, MYSQL_PORT, NULL, 0)) {
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_ERROR,
                "MySQL_conn: MySQL connecotr error");
        return ((void *)-1);
    }
    log4c_category_log(
            log_handler, LOG4C_PRIORITY_INFO,
            "MySQL_conn: MySQL connecotr start up");

    /* Turn on auto commint */
    mysql_autocommit(&mysql, 1);

    if(!mysql_ping(&mysql)) {
        mysql_query(&mysql, "SET NAMES UTF8");
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_TRACE,
                "MySQL_conn: Mysql Server set utf-8");
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_INFO,
                "MySQL_conn: %s", "SET NAMES UTF8");
    } else {
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_FATAL,
                "MySQL_conn: lost connect to Mysql Server");
        return ((void *)0);
    }

    int malloc_size;

    while(1) {
        update_proto = NULL;
        delete_proto = NULL;
        insert_proto = NULL;
        apr_queue_pop(queue, &pop_string);

        raw_string = pop_string;
        raw_len = strlen(raw_string);

        if(NULL == raw_string) {
            log4c_category_log(
                    log_handler, LOG4C_PRIORITY_NOTICE,
                    "MySQL_conn: POP from queue is NULL");
            continue;
        }

        log4c_category_log(
                log_handler, LOG4C_PRIORITY_TRACE,
                "MySQL_conn: POP from queue: %s", raw_string);

        /* Get flag */
        tmp = strsep(&raw_string, ":");
        flag= atoi(tmp);

        /* Keep elegant */
        /* If Basic Info */
        if(1 == flag) {
            log4c_category_log(
                    log_handler, LOG4C_PRIORITY_TRACE,
                    "MySQL_conn_basic: post basic");
            /* Split raw string */
            uid = strsep(&raw_string, ",");
            birth_year = strsep(&raw_string, ",");
            birth_month = strsep(&raw_string, ",");
            birth_day = strsep(&raw_string, ",");
            constellation = strsep(&raw_string, ",");

            blood_types = strsep(&raw_string, ",");
            sex = strsep(&raw_string, ",");

            home_nation = strsep(&raw_string, ",");
            home_pro = strsep(&raw_string, ",");
            home_city = strsep(&raw_string, ",");

            now_nation = strsep(&raw_string, ",");
            now_pro = strsep(&raw_string, ",");
            now_city = strsep(&raw_string, ",");

            /* Magic number 350 is SQL proto length */
            malloc_size = raw_len + 350;
            update_proto = xmalloc(malloc_size);
            snprintf(update_proto, (malloc_size), "update base_user_info set\
                    birth_year=%s, birth_month=%s, birth_day=%s,\
                    constellation=%s, blood_types=%s, sex=%s,\
                    home_nation='%s', home_pro='%s', home_city='%s',\
                    now_nation='%s', now_pro='%s', now_city='%s'\
                    where uid=%s", 
                    birth_year, birth_month, birth_day,
                    constellation, blood_types, sex,
                    home_nation, home_pro, home_city,
                    now_nation, now_pro, now_city,
                    uid);
            log4c_category_log(
                    log_handler, LOG4C_PRIORITY_TRACE,
                    "MySQL_conn_basic: updata proto: %s", update_proto);
            /* query mysql */
            if(!mysql_ping(&mysql)) {
                mysql_query(&mysql, "SET NAMES UTF8");
                mysql_query_rc = mysql_query(&mysql, update_proto);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: Mysql Server update return: %d",
                        mysql_query_rc);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_INFO,
                        "MySQL_conn_basic: %s", update_proto);
            } else {
                /* Dump to file */
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_ERROR,
                        "MySQL_conn_basic: lost connect to Mysql Server");
                fprintf(server.dump_file_handler, "%s\n", update_proto);
                fflush(server.dump_file_handler);
            }

            if(mysql_field_count(&mysql) == 0) {
                affect = (unsigned long long )mysql_affected_rows(&mysql);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: update affect:%d", affect);
            }
            /* new user */
            if(0 == affect) {
                malloc_size = raw_len + 358;
                insert_proto = xmalloc(malloc_size);
                snprintf(insert_proto, malloc_size,
                        "insert into base_user_info set\
                        birth_year=%s, birth_month=%s, birth_day=%s,\
                        constellation=%s, blood_types=%s, sex=%s,\
                        home_nation='%s', home_pro='%s', home_city='%s',\
                        now_nation='%s', now_pro='%s', now_city='%s',\
                        uid=%s", 
                        birth_year, birth_month, birth_day,
                        constellation, blood_types, sex,
                        home_nation, home_pro, home_city,
                        now_nation, now_pro, now_city,
                        uid);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: insert proto: %s", insert_proto);
                if(!mysql_ping(&mysql)) {
                    mysql_query(&mysql, "SET NAMES UTF8");
                    mysql_query_rc = mysql_query(&mysql, insert_proto);
                    log4c_category_log(
                            log_handler, LOG4C_PRIORITY_TRACE,
                            "MySQL_conn_basic: Mysql Server insert return: %d",
                            mysql_query_rc);
                    log4c_category_log(
                            log_handler, LOG4C_PRIORITY_INFO,
                            "MySQL_conn_basic: %s", insert_proto);
                } else {
                    log4c_category_log(
                            log_handler, LOG4C_PRIORITY_ERROR,
                            "MySQL_conn_basic: lost connect to Mysql Server");
                    /* Dump to file */
                    fprintf(server.dump_file_handler, "%s\n", insert_proto);
                    fflush(server.dump_file_handler);
                }
                affect = (unsigned long long )mysql_affected_rows(&mysql);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: insert affect:%d", affect);
            }

            xfree(insert_proto);
            xfree(update_proto);
        }
Ejemplo n.º 29
0
	bool connection::ping()
	{
		return mysql_ping(mysql) == 0;
	}
Ejemplo n.º 30
0
int dbrelay_mysql_isalive(void *db)
{
   mysql_db_t *mydb = (mysql_db_t *) db;
  
   return mysql_ping(mydb->mysql);
}