Пример #1
0
//Create stats update thread
void C_NAS::runThread() {
	logmsg(DBG_THREADS,"Started stats offloading thread for NAS %s", this->getName());
	MYSQL *su_link=connectdb();
	// update values in database
	while (cfg.stayalive) {
	    sleep(cfg.stats_update_interval);
	    logmsg(DBG_OFFLOAD,"Updating stats in MySQL for NAS %s", this->getName());

        //Iterate over users map, keep locking in mind!
        std::map<uint32_t,C_user*>::iterator usersIter;
        C_user* myUser;
        mylock.lockRead();
        usersIter = usersByIP.begin();
        while (usersIter!=usersByIP.end()){
            myUser = usersIter->second;
            mylock.unlockRead();

            if (myUser!=NULL){
                //Got user, save his stats.
                myUser->updateStats(su_link);
                //Check his debit
                if (!myUser->checkDebit(su_link)){
                    //Disconnect him if debit<0
                    myUser->dropUser();
                };
                //Delete him if he is already disconnected
                if (myUser->checkDelete()){
                    logmsg(DBG_EVENTS,"Deleting expired user %u",myUser->getSID());
                    //delete from NAS maps;
                    mylock.lockWrite();
                    usersBySID.erase(myUser->getSID());
                    usersByIP.erase(usersIter);
                    mylock.unlockWrite();
                    //Delete from naslist maps:
                    nases.UserDeleted(myUser);
                    //Delete user himself:
                    delete myUser;
                };
            };

            mylock.lockRead();
            usersIter++;
        };
        mylock.unlockRead();

	}
	logmsg(DBG_THREADS,"Finishing stats offloading thread");
	mysql_close(su_link);
	mysql_thread_end();
	logmsg(DBG_THREADS,"Complete stats offloading thread");
	pthread_exit(NULL);
}
Пример #2
0
//----------------------------------------------------
bool saveObjImpl(
void *self,  // puntero generico al que aplica
int *newId // En la insecion debe retornar el id nuevo.
)
{
   PGconn *conn;
   PGresult *res; 
   int code=0;
   char values[MAX_WHERE_SQL], where[MAX_WHERE_SQL],*sql;   
   t_object *obj = (t_object *) self;
    //Conexion con la base de datos 
   if ((conn = connectdb(SERVER,PORT,DB,USER,PASS))== NULL) {
      exit (-1); 
   }
   //Si esta marcado como nuevo objeto, es decir se creo instancia y no fue obtenido de la BD,
   if(obj->getIsNewObj(obj))
   {// insert
		sql = (char*)getInsertSQL(obj);
		res = PQexec(conn, sql);
		code = PQresultStatus(res);
		*newId = atoi(PQgetvalue(res,0,0));	
		PQclear(res);
		free(sql);
		obj->isNewObj=false;// marcar que esta guardado en la BD.
  }
  else
  {// update
      sql = (char*)getUpdateSQL(obj);
      res = PQexec(conn, sql) ;
      code = PQresultStatus(res);
      PQclear(res);	  
	  free(sql);
  }
  if ( code != PGRES_COMMAND_OK)  {
        disconnectdb(conn);     
       return false;
  }
    else
    {
       disconnectdb(conn);
       return true;    
    }
}
Пример #3
0
/*
funcion generica que recibe como argumento cadena sql puntero a array dinamico en memoria para alojar segun la funcion de
llenado pasada por parametro (puntero a funcion)
*/
int exec_get_fromDB(char *sql,void **rw, size_t t,void(*fcFill)(void **,int ri,PGresult *r)) {
    PGconn *conn;
    //Conexion con la base de datos 
	if ((conn = connectdb(SERVER,PORT,DB,USER,PASS)) == NULL){
        exit(-1);
    }
    int tuplas=0,i=0;
    PGresult *res; //Instancia para contener los datos de ejecucion de consulta
    res = PQexec(conn, sql);

    if (res != NULL && PGRES_TUPLES_OK == PQresultStatus(res)) {
        tuplas = PQntuples(res);
        if(tuplas!=0) {
            *rw = malloc(t * tuplas);
            for (i = 0; i<tuplas; i++) 
            {
             //el puntero a funcion recibido carga la info en la estructura
             fcFill(rw,i,res);
            }        }
        PQclear(res);
    }
    disconnectdb(conn);
    return tuplas;
}
int main(int argc, char **argv)
{
    PGconn     *conn;
    int     msock, ssock, clen;
    struct  sockaddr_in clin;
    char    *caddr;
    pthread_t tid, lbid;
    pthread_attr_t tattr, lattr;


    if (argc != 2) {
        printf("Error: <filename> <portno>\n");
        exit(0);
    }

    int portno = atoi(argv[1]);
    //Connect to the backend database server.
    conn = connectdb();

    //Create a TCP socket.
    msock = tcp_sock(portno);

    printf("\n****MICROBLOGGING SERVER****\n");

    pthread_attr_init(&lattr);
    pthread_attr_setdetachstate(&lattr,PTHREAD_CREATE_DETACHED);

    if (pthread_create(&lbid, &lattr, (void*(*)(void *))loadbalancer, (void *)NULL) < 0)
    {
        printf("Error: Unable to create the start thread.\n");
        exit(0);
    }



    while (1) {

        printf("\nWaiting for the remote host...\n");
        clen = sizeof(clin);
        if ((ssock = accept(msock, (struct sockaddr *)&clin,&clen)) < 0) {
            printf("Error: Failed to connect to remote host.\n");
            exit(0);
        }

        caddr = inet_ntoa(clin.sin_addr);
        printf("Established conn to %s[:%d]\n", caddr,htons(clin.sin_port));

        th_args_dt *args;
        args = (th_args_dt *)malloc(sizeof(th_args_dt));
        args->sock = ssock;
        args->conn = conn;

        pthread_attr_init(&tattr);
        pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_DETACHED);
        pthread_mutex_init(&args->th_mutex,0);

        if (pthread_create(&tid, &tattr, (void*(*)(void *))tweet_server, (void *)args) < 0)
        {
            printf("Error: Unable to create the start thread.\n");
            exit(0);
        }
        //pthread_join(tid, NULL);
        pthread_attr_destroy(&tattr);
        pthread_mutex_destroy (&args->th_mutex);
        //close(ssock);
    }

    PQfinish(conn);
    // close(msock);

    return 0;
}