Example #1
0
//*******************************************************************
// IS THIS SLOT COMPLETELY FILLED?
//*******************************************************************
int slot_is_complete(trx *t, int i, guint slotlow, guint slothigh)
{
  dbi_result result;
  int val = FALSE;

  /* 
   * don't know how many raw records go into a day slot, 
   * so we fake it is filled, so it'll always be summarized
   */
  if (i == 0) return 1;
  result = db_query(t->probe->db, 0,
                    "select count(*) as count from pr_%s_%s use index(probstat) "
                    "where  probe = '%u' and stattime >= '%u' and stattime <= '%u'",
                    t->res->name, summ_info[i].from, t->def->probeid, slotlow, slothigh);
  if (!result) return(FALSE);
  if (dbi_result_next_row(result)) {
    if (dbi_result_get_uint(result, "count") >= summ_info[i].perslot) {
      val = TRUE;
    }
  }
  dbi_result_free(result);
  return(val);
}
Example #2
0
swd::integrity_rules swd::database::get_integrity_rules(const int& profile_id,
 const std::string& caller) {
    swd::log::i()->send(swd::notice, "Get integrity rules from db");

    ensure_connection();

    boost::unique_lock<boost::mutex> scoped_lock(dbi_mutex_);

    char *caller_esc = strdup(caller.c_str());
    dbi_conn_quote_string(conn_, &caller_esc);

    dbi_result res = dbi_conn_queryf(conn_, "SELECT r.id, r.algorithm, r.digest FROM "
     "integrity_rules AS r WHERE r.profile_id = %i AND %s LIKE prepare_wildcard(r.caller) "
     "AND r.status = %i", profile_id, caller_esc, STATUS_ACTIVATED);

    free(caller_esc);

    if (!res) {
        throw swd::exceptions::database_exception("Can't execute whitelist_rules query");
    }

    swd::integrity_rules rules;

    while (dbi_result_next_row(res)) {
        swd::integrity_rule_ptr rule(new swd::integrity_rule());
        rule->set_id(dbi_result_get_uint(res, "id"));
        rule->set_algorithm(dbi_result_get_string(res, "algorithm"));
        rule->set_digest(dbi_result_get_string(res, "digest"));

        rules.push_back(rule);
    }

    dbi_result_free(res);

    return rules;
}
Example #3
0
//*******************************************************************
// RETRIEVE FOLLOWING RAW RECORD FROM DATABASE (well just the color)
//*******************************************************************
static struct probe_result *get_following_record(trx *t)
{
  dbi_result result;
  struct probe_result *nxt = NULL;

  if (!t->probe->store_results) return(NULL); // we probably don't have a xxxx_raw table

  result = db_query(t->probe->db, 0,
                    "select   color, stattime "
                    "from     pr_%s_raw use index(probstat) "
                    "where    probe = '%u' and stattime > '%u' "
                    "order by stattime asc limit 1", 
                    t->res->name, t->def->probeid, t->res->stattime);
  if (result) {
    if (dbi_result_next_row(result)) {
      nxt = g_malloc0(sizeof(struct probe_result));

      nxt->color = dbi_result_get_uint(result, "color");
      nxt->stattime = dbi_result_get_uint(result, "stattime");
    }
    dbi_result_free(result);
  }
  return(nxt);
}
Example #4
0
/*
 * Load the lava topology from network
 */
void magma_load_status()
{
	/*
	 * allocate a new lava topology
	 */
	magma_lava *new_lava = g_new0(magma_lava, 1);
	if (!new_lava) {
		dbg(LOG_ERR, DEBUG_BOOT, "Error allocating lava network, exiting now.");
		exit (1);
	}

	/*
	 * send the SQL query to load lava nodes
	 */
	gchar *query = g_strdup_printf(
		"select nickname, fqdn, ipaddr, ipport, start_key, stop_key, load, storage, bandwidth "
		"from lava_%s order by start_key", magma_environment.nickname);

	dbi_result result = magma_sql_query(query);
	g_free(query);

	/*
	 * if the query succeeded...
	 */
	if (result) {
		/*
		 * loop through values to load nodes into a lava topology
		 */
        while (dbi_result_next_row(result)) {
        	gchar *nickname		= magma_sql_fetch_string (result, 1);
        	gchar *fqdn			= magma_sql_fetch_string (result, 2);
        	gchar *ipaddr		= magma_sql_fetch_string (result, 3);
        	guint32 ipport		= magma_sql_fetch_integer(result, 4);
        	gchar *start_key	= magma_sql_fetch_string (result, 5);
        	gchar *stop_key		= magma_sql_fetch_string (result, 6);
        	// double load			= magma_sql_fetch_double (result, 7);
        	guint32 storage		= magma_sql_fetch_integer(result, 8);
        	guint32 bandwidth	= magma_sql_fetch_integer(result, 9);

        	magma_volcano *v = magma_volcano_new(
        		nickname, fqdn,	ipaddr, ipport, bandwidth,
        		storage, start_key, stop_key, "");

        	if (!v) {
        		dbg(LOG_ERR, DEBUG_BOOT, "Error allocating volcano %s", nickname);
        		exit(1);
        	}

        	if (!new_lava->first_node) { new_lava->first_node = v; }
        	if ( new_lava->last_node ) { new_lava->last_node->next = v; v->prev = new_lava->last_node; }
        	new_lava->last_node = v;

        	new_lava->participants++;
        }

        if (new_lava->participants < 1) {
        	dbg(LOG_ERR, DEBUG_BOOT, "Error loading lava topology from disk: zero nodes found");
        	exit (1);
        }

        new_lava->last_node->next = new_lava->first_node;
        new_lava->first_node->prev = new_lava->last_node;

        /*
         * free DBI result
         */
		dbi_result_free(result);

		/*
		 * update this node from the lava topology
		 */
		magma_update_myself_from_lava(new_lava);

		/*
		 * install the new topology
		 */
		lava = new_lava;

		/*
		 * check if this node should act as coordinator
		 * or should be coordinated
		 */
		if (!magma_this_node_is_coordinator()) return;

		/*
		 * coordinate network boot
		 */
		magma_coordinate_network_boot();
	}
}
Example #5
0
static int _sql_fetchrow(struct sql_table_helper* th,time_t *timestamp, rrd_value_t *value,int ordered) {
  char* dbi_errstr=NULL;
  char sql[10240];
  time_t startt=0,endt=0;
  /*connect to the database if needed */
  if (! th->conn) {
      rrd_set_error( "libdbi no parameters set for libdbi",th->filename,dbi_errstr);
      return -1;
  }
  if (! th->connected) {
    /* and now connect */
    if (getenv("RRDDEBUGSQL")) { fprintf(stderr,"RRDDEBUGSQL: %li: connect to DB\n",time(NULL) ); }
    if (dbi_conn_connect(th->conn) <0) {
      dbi_conn_error(th->conn,(const char**)&dbi_errstr);
      rrd_set_error( "libdbi: problems connecting to db with connect string %s - error: %s",th->filename,dbi_errstr);
      _sql_close(th);
      return -1;
    }
    th->connected=1;
  }
  /* now find out regarding an existing result-set */
  if (! th->result) {
    /* return if table_next is NULL */
    if (th->table_next==NULL) { 
    if (getenv("RRDDEBUGSQL")) { fprintf(stderr,"RRDDEBUGSQL: %li: reached last table to connect to\n",time(NULL) ); }
      /* but first close connection */
      _sql_close(th);
      /* and return with end of data */
      return 0;
    }
    /* calculate the table to use next */
    th->table_start=th->table_next;
    th->table_next=_find_next_separator(th->table_start,'+');
    _inline_unescape(th->table_start);
    /* and prepare FULL SQL Statement */
    if (ordered) {
      snprintf(sql,sizeof(sql)-1,"SELECT %s as rrd_time, %s as rrd_value FROM %s WHERE %s ORDER BY %s",
  	       th->timestamp,th->value,th->table_start,th->where,th->timestamp);
    } else {
      snprintf(sql,sizeof(sql)-1,"SELECT %s as rrd_time, %s as rrd_value FROM %s WHERE %s",
  	       th->timestamp,th->value,th->table_start,th->where);
    }
    /* and execute sql */
    if (getenv("RRDDEBUGSQL")) { startt=time(NULL); fprintf(stderr,"RRDDEBUGSQL: %li: executing %s\n",startt,sql); }
    th->result=dbi_conn_query(th->conn,sql);
    if (startt) { endt=time(NULL);fprintf(stderr,"RRDDEBUGSQL: %li: timing %li\n",endt,endt-startt); }
    /* handle error case */
    if (! th->result) {
      dbi_conn_error(th->conn,(const char**)&dbi_errstr);      
      if (startt) { fprintf(stderr,"RRDDEBUGSQL: %li: error %s\n",endt,dbi_errstr); }
      rrd_set_error("libdbi: problems with query: %s - errormessage: %s",sql,dbi_errstr);
      _sql_close(th);
      return -1;
    }
  }
  /* and now fetch key and value */
  if (! dbi_result_next_row(th->result)) {
    /* free result */
    dbi_result_free(th->result);
    th->result=NULL;
    /* and call recursively - this will open the next table or close connection as a whole*/
    return _sql_fetchrow(th,timestamp,value,ordered);
  } 
  /* and return with flag for one value */
  *timestamp=rrd_fetch_dbi_long(th->result,1);
  *value=rrd_fetch_dbi_double(th->result,2);
  return 1;
}
//*******************************************************************
// SUMMARIZE A TABLE INTO AN OLDER PERIOD
//*******************************************************************
static void mysqlstats_summarize(trx *t, char *from, char *into, guint slot, guint slotlow, guint slothigh, gint resummarize)
{
  dbi_result result;
  struct probe_def *def = (struct probe_def *)t->def;
  float avg_yellow, avg_red;
  int avg_selectq;
  int avg_insertq;
  int avg_updateq;
  int avg_deleteq;
  guint stattime;
  guint max_color;

  stattime = slotlow + ((slothigh-slotlow)/2);

  result = db_query(t->probe->db, 0,
                    "select avg(selectq) as avg_selectq, avg(insertq) as avg_insertq, avg(updateq) as avg_updateq, "
                    "       avg(deleteq) as avg_deleteq, max(color) as max_color, avg(yellow) as avg_yellow, avg(red) as avg_red"
                    "from   pr_mysqlstats_%s use index(probstat) "
                    "where  probe = '%d' and stattime >= %d and stattime < %d",
                    from, def->probeid, slotlow, slothigh);

  if (!result) return;
  if (dbi_result_get_numrows(result) == 0) { // no records found
    LOG(LOG_NOTICE, "nothing to summarize from %s for probe %u %u %u",
                       from, def->probeid, slotlow, slothigh);
    dbi_result_free(result);
    return;
  }

  if (!dbi_result_next_row(result)) {
    dbi_result_free(result);
    return;
  }
  if (dbi_result_field_is_null_idx(result, 0)) {
    LOG(LOG_NOTICE, "nothing to summarize from %s for probe %u %u %u", 
                       from, def->probeid, slotlow, slothigh);
    dbi_result_free(result);
    return;
  }

  avg_selectq = dbi_result_get_int(result, "avg_selectq");
  avg_insertq = dbi_result_get_int(result, "avg_insertq");
  avg_updateq = dbi_result_get_int(result, "avg_updateq");
  avg_deleteq = dbi_result_get_int(result, "avg_deleteq");
  max_color   = dbi_result_get_int(result, "max_color");
  avg_yellow  = dbi_result_get_float(result, "avg_yellow");
  avg_red     = dbi_result_get_float(result, "avg_red");
  dbi_result_free(result);

  if (resummarize) {
    // delete old values
    result = db_query(t->probe->db, 0,
                    "delete from pr_mysqlstats_%s where probe = '%u' and stattime = '%u'",
                    into, def->probeid, stattime);
    dbi_result_free(result);
  }

  result = db_query(t->probe->db, 0,
                    "insert into pr_mysqlstats_%s (selectq, insertq, updateq, deleteq, probe, color, stattime, "
                    "                              yellow, red, slot) "
                    "            values ('%u', '%u', '%u', '%u', '%d', '%u', '%d', "
                    "                    '%f', '%f', '%u')",
                    into,  avg_selectq, avg_insertq, avg_updateq, avg_deleteq, def->probeid, 
                    max_color, stattime, avg_yellow, avg_red, slot);

  dbi_result_free(result);
}
Example #7
0
//*******************************************************************
// retrieve the definitions + status
// get it from the cache. if there but too old: delete
// If a probe definition does not exist, it will be created.
// in case of mysql-has-gone-away type errors, we keep on running, 
// it will be caught later-on.
//*******************************************************************
void *bb_get_def(trx *t, int create)
{
  struct probe_def *def;
  struct bb_result *res = (struct bb_result *)t->res;
  dbi_result result;

  def = g_malloc0(t->probe->def_size);
  def->stamp    = time(NULL);
  def->server   = res->server;
  def->pgroup   = 1;
  strcpy(def->hide, "no");

  if (res->color == STAT_PURPLE && res->probeid) {
    // find the definition based on the probe id
    result = db_query(t->probe->db, 0,
                      "select id, contact, hide, email, sms, delay from pr_bb_def "
                      "where  id = '%u'", res->probeid);
    if (!result) {
      g_free(def);
      return(NULL);
    }
  } else {
    if (res->server == 0) {
      // first we find the serverid, this will be used to find the probe definition in the database
      if (!query_server_by_name) {
        LOG(LOG_WARNING, "%s:%u@%s: don't know how to find %s by name", 
            res->realm, res->stattime, t->fromhost, res->hostname);
        g_free(def);
        return(NULL);
      }
      result = db_query(t->probe->db, 0, query_server_by_name, res->hostname, res->hostname, 
                        res->hostname, res->hostname, res->hostname);
      if (!result) {
        g_free(def);
        return(NULL);
      }
      if (dbi_result_next_row(result)) {
        res->server   = dbi_result_get_int_idx(result, 0);
      } else {
        LOG(LOG_WARNING, "%s:%u@%s: server %s not found", res->realm, res->stattime, t->fromhost, res->hostname);
        dbi_result_free(result);
        g_free(def);
        return(NULL);
      }
      dbi_result_free(result);
    }

    // first find the definition based on the serverid
    result = db_query(t->probe->db, 0,
                      "select id, contact, hide, email, sms, delay from pr_bb_def "
                      "where  bbname = '%s' and server = '%u'", res->bbname, res->server);
    if (!result) {
      g_free(def);
      return(NULL);
    }
  }
  if (dbi_result_get_numrows(result) == 0) { // DEF RECORD NOT FOUND
    char sequence[40];
    dbi_result_free(result);
    result = db_query(t->probe->db, 0,
                      "insert into pr_%s_def (server, ipaddress, description, bbname) "
                      "            values ('%u', '%s', '%s', '%s')", 
                      res->name, res->server, res->ipaddress ? res->ipaddress : "", 
                      res->hostname, res->bbname);
    dbi_result_free(result);
    sprintf(sequence, "pr_%s_def_id_seq", res->name);
    def->probeid  = dbi_conn_sequence_last(t->probe->db, sequence);
    LOG(LOG_NOTICE, "%s:%u@%s: pr_bb_def %s created for %s, id = %u", 
        res->realm, res->stattime, t->fromhost, res->bbname, res->hostname, def->probeid);
    result = db_query(t->probe->db, 0,
                    "select id, contact, hide, email, sms, delay from pr_bb_def "
                    "where  bbname = '%s' and server = '%u'", res->bbname, res->server);
    if (!result) return(NULL);
  }
  if (!dbi_result_next_row(result)) {
    LOG(LOG_NOTICE, "%s:%u@%s: no pr_%s_def found for server %u - skipped", 
         res->realm, res->stattime, t->fromhost, res->name, res->server);
    dbi_result_free(result);
    return(NULL);
  }
  def->probeid = dbi_result_get_int(result, "id");
  def->contact = dbi_result_get_int(result, "contact");
  strcpy(def->hide, dbi_result_get_string_default(result, "hide", "no"));
  strcpy(def->email, dbi_result_get_string_default(result, "email", ""));
  strcpy(def->sms, dbi_result_get_string_default(result, "sms", ""));
  def->delay = dbi_result_get_int(result, "delay");

  dbi_result_free(result);

  // definition found, get the pr_status
  result = db_query(t->probe->db, 0,
                    "select color, stattime "
                    "from   pr_status "
                    "where  class = '%u' and probe = '%u'", t->probe->class, def->probeid);
  if (result) {
    if (dbi_result_next_row(result)) {
      def->color   = dbi_result_get_int(result, "color");
      def->newest  = dbi_result_get_int(result, "stattime");
    } else {
      LOG(LOG_NOTICE, "%s:%u@%s: pr_status record for %s id %u (server %s) not found", 
                       res->realm, res->stattime, t->fromhost, res->name, def->probeid, res->hostname);
    }
    dbi_result_free(result);
  }
  if (!def->color) def->color = res->color;
  res->probeid = def->probeid;

  return(def);
}
Example #8
0
static void calc_amp_cds(struct module *mod, dbi_conn conn, int interval)
{
    int ct = 0, st = 0;
    dbi_result result = 0;
    ST_CDS *pa = NULL;
    ST_CDS *pe = NULL;
    long long rst = 0;
    
    logRecord( LOG_INFO, "%s(%d): cal amp, interval:%d", __FUNCTION__, __LINE__, interval );

    pa = (ST_CDS *)mod->amp_array;
    pe = (ST_CDS *)mod->emp_array;

    /* acquire omp uss stats */
    pa[0].sdr_id = 0;
    strncpy(pa[0].sdr_amp_id, "0", sizeof(pa[0].sdr_amp_id) - 1);
    convert_time_to_string(statis.cur_time, pa[ct].sdr_record_time, 0);
    convert_time_to_string(statis.cur_time - 24*60*60, pa[ct].sdr_time, 1);
    if (interval == 0) {
        pa[0].sdr_date_flag = 0;
    } else if (interval == 7) {
        pa[0].sdr_date_flag = 1;
    } else {
        pa[0].sdr_date_flag = 2;
    }
    for (ct = 0; ct < mod->emp_record; ct++)
    {
        pa[0].sdr_ptt_htime += pe[ct].sdr_ptt_htime;
        pa[0].sdr_ptt_hcount += pe[ct].sdr_ptt_hcount;
        pa[0].sdr_call_htime += pe[ct].sdr_call_htime;
        pa[0].sdr_call_hcount += pe[ct].sdr_call_hcount;
        pa[0].sdr_video_htime += pe[ct].sdr_video_htime;
        pa[0].sdr_video_hcount += pe[ct].sdr_video_hcount;
        pa[0].sdr_audio_htime += pe[ct].sdr_audio_htime;
        pa[0].sdr_audio_hcount += pe[ct].sdr_audio_hcount;
    }

    st = 1;
    /* acquire amp uss stats */
    result = dbi_conn_queryf(conn, "select ag_number from \"T_Agents\" order by ag_number");
    if (result) {
        while(dbi_result_next_row(result)) {
            //pa[st].sdr_id = atoll(dbi_result_get_string(result, "ag_number"));
            strncpy( pa[st].sdr_amp_id, dbi_result_get_string(result, "ag_number"), sizeof(pa[st].sdr_amp_id) - 1 );
            pa[st].sdr_amp_id[sizeof(pa[st].sdr_amp_id) - 1] = '\0';
            convert_time_to_string(statis.cur_time, pa[st].sdr_record_time, 0);
            convert_time_to_string(statis.cur_time - 24*60*60, pa[st].sdr_time, 1);
            if (interval == 0) {
                pa[st].sdr_date_flag = 0;
            } else if (interval == 7) {
                pa[st].sdr_date_flag = 1;
            } else {
                pa[st].sdr_date_flag = 2;
            }
            st++;
        }
        dbi_result_free(result);
    }

    for (st = 1; st < mod->amp_record; st++)
    {
        /*
        result = dbi_conn_queryf(conn, "select e_id from \"T_Enterprise\" where \
                e_ag_path like '%s%lld%s' order by e_id", "%", pa[st].sdr_id, "%");
                */
                
        result = dbi_conn_queryf(conn, "select e_id from \"T_Enterprise\" where \
                e_ag_path like '%s%s%s' order by e_id", "%", pa[st].sdr_amp_id, "%");
        if (result) {
            while(dbi_result_next_row(result)) {
                rst = dbi_result_get_longlong(result, "e_id");
                for (ct = 0; ct < mod->emp_record; ct++) {
                    if (rst == pe[ct].sdr_id) {
                        pa[st].sdr_ptt_htime += pe[ct].sdr_ptt_htime;
                        pa[st].sdr_ptt_hcount += pe[ct].sdr_ptt_hcount;
                        pa[st].sdr_call_htime += pe[ct].sdr_call_htime;
                        pa[st].sdr_call_hcount += pe[ct].sdr_call_hcount;
                        pa[st].sdr_video_htime += pe[ct].sdr_video_htime;
                        pa[st].sdr_video_hcount += pe[ct].sdr_video_hcount;
                        pa[st].sdr_audio_htime += pe[ct].sdr_audio_htime;
                        pa[st].sdr_audio_hcount += pe[ct].sdr_audio_hcount;

                        break;
                    }
                }
            }
            dbi_result_free(result);
        }
    }

    //log_cds_stats(pa, mod->amp_record);

    return;
}
Example #9
0
static int cdbi_read_database_query (cdbi_database_t *db, /* {{{ */
    udb_query_t *q, udb_query_preparation_area_t *prep_area)
{
  const char *statement;
  dbi_result res;
  size_t column_num;
  char **column_names;
  char **column_values;
  int status;
  size_t i;

  /* Macro that cleans up dynamically allocated memory and returns the
   * specified status. */
#define BAIL_OUT(status) \
  if (column_names != NULL) { sfree (column_names[0]); sfree (column_names); } \
  if (column_values != NULL) { sfree (column_values[0]); sfree (column_values); } \
  if (res != NULL) { dbi_result_free (res); res = NULL; } \
  return (status)

  column_names = NULL;
  column_values = NULL;

  statement = udb_query_get_statement (q);
  assert (statement != NULL);

  res = dbi_conn_query (db->connection, statement);
  if (res == NULL)
  {
    char errbuf[1024];
    ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
        "dbi_conn_query failed: %s",
        db->name, udb_query_get_name (q),
        cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
    BAIL_OUT (-1);
  }
  else /* Get the number of columns */
  {
    unsigned int db_status;

    db_status = dbi_result_get_numfields (res);
    if (db_status == DBI_FIELD_ERROR)
    {
      char errbuf[1024];
      ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
          "dbi_result_get_numfields failed: %s",
          db->name, udb_query_get_name (q),
          cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
      BAIL_OUT (-1);
    }

    column_num = (size_t) db_status;
    DEBUG ("cdbi_read_database_query (%s, %s): There are %zu columns.",
        db->name, udb_query_get_name (q), column_num);
  }

  /* Allocate `column_names' and `column_values'. {{{ */
  column_names = calloc (column_num, sizeof (*column_names));
  if (column_names == NULL)
  {
    ERROR ("dbi plugin: calloc failed.");
    BAIL_OUT (-1);
  }

  column_names[0] = calloc (column_num, DATA_MAX_NAME_LEN);
  if (column_names[0] == NULL)
  {
    ERROR ("dbi plugin: calloc failed.");
    BAIL_OUT (-1);
  }
  for (i = 1; i < column_num; i++)
    column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;

  column_values = calloc (column_num, sizeof (*column_values));
  if (column_values == NULL)
  {
    ERROR ("dbi plugin: calloc failed.");
    BAIL_OUT (-1);
  }

  column_values[0] = calloc (column_num, DATA_MAX_NAME_LEN);
  if (column_values[0] == NULL)
  {
    ERROR ("dbi plugin: calloc failed.");
    BAIL_OUT (-1);
  }
  for (i = 1; i < column_num; i++)
    column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
  /* }}} */

  /* Copy the field names to `column_names' */
  for (i = 0; i < column_num; i++) /* {{{ */
  {
    const char *column_name;

    column_name = dbi_result_get_field_name (res, (unsigned int) (i + 1));
    if (column_name == NULL)
    {
      ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
          "Cannot retrieve name of field %zu.",
          db->name, udb_query_get_name (q), i + 1);
      BAIL_OUT (-1);
    }

    sstrncpy (column_names[i], column_name, DATA_MAX_NAME_LEN);
  } /* }}} for (i = 0; i < column_num; i++) */

  udb_query_prepare_result (q, prep_area, (db->host ? db->host : hostname_g),
      /* plugin = */ "dbi", db->name,
      column_names, column_num, /* interval = */ (db->interval > 0) ? db->interval : 0);

  /* 0 = error; 1 = success; */
  status = dbi_result_first_row (res); /* {{{ */
  if (status != 1)
  {
    char errbuf[1024];
    ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
        "dbi_result_first_row failed: %s. Maybe the statement didn't "
        "return any rows?",
        db->name, udb_query_get_name (q),
        cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
    udb_query_finish_result (q, prep_area);
    BAIL_OUT (-1);
  } /* }}} */

  /* Iterate over all rows and call `udb_query_handle_result' with each list of
   * values. */
  while (42) /* {{{ */
  {
    status = 0;
    /* Copy the value of the columns to `column_values' */
    for (i = 0; i < column_num; i++) /* {{{ */
    {
      status = cdbi_result_get_field (res, (unsigned int) (i + 1),
          column_values[i], DATA_MAX_NAME_LEN);

      if (status != 0)
      {
        ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
            "cdbi_result_get_field (%zu) failed.",
            db->name, udb_query_get_name (q), i + 1);
        status = -1;
        break;
      }
    } /* }}} for (i = 0; i < column_num; i++) */

    /* If all values were copied successfully, call `udb_query_handle_result'
     * to dispatch the row to the daemon. */
    if (status == 0) /* {{{ */
    {
      status = udb_query_handle_result (q, prep_area, column_values);
      if (status != 0)
      {
        ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
            "udb_query_handle_result failed.",
            db->name, udb_query_get_name (q));
      }
    } /* }}} */

    /* Get the next row from the database. */
    status = dbi_result_next_row (res); /* {{{ */
    if (status != 1)
    {
      if (dbi_conn_error (db->connection, NULL) != 0)
      {
        char errbuf[1024];
        WARNING ("dbi plugin: cdbi_read_database_query (%s, %s): "
            "dbi_result_next_row failed: %s.",
            db->name, udb_query_get_name (q),
            cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
      }
      break;
    } /* }}} */
  } /* }}} while (42) */

  /* Tell the db query interface that we're done with this query. */
  udb_query_finish_result (q, prep_area);

  /* Clean up and return `status = 0' (success) */
  BAIL_OUT (0);
#undef BAIL_OUT
} /* }}} int cdbi_read_database_query */
Example #10
0
int rpserver_db_pair_exec(dbi_conn *db, const char *localid, const char *name, char *buf, size_t maxlen)
{
    dbi_result *result; 
    int len = 0;
    int boxid = -1;

    result = dbi_conn_queryf(db,  "DELETE FROM "DB_TABLE_DEVICES" WHERE name='%s' AND iid IS NULL\n", name);

    if(result){
	dbi_result_free(result);
    } else {
	const char *err;
        dbi_conn_error(db, &err);
        LOG(LOG_INFO, "%s():%d - dbi error querying database (%s)\n", __FUNCTION__, __LINE__, err);
        return -1;
    }

    result = dbi_conn_queryf(db,  "SELECT device_id FROM "DB_TABLE_DEVICES" WHERE localid='%s' AND name IS NULL\n", localid);
    
    if(result){
	if(dbi_result_next_row(result)) {
	    boxid =  dbi_result_get_int(result, "device_id");
	    LOG(LOG_INFO, "%s():%d - boxid is %d\n", __FUNCTION__, __LINE__, boxid);
	}
	dbi_result_free(result);
    } else {
	const char *err;
        dbi_conn_error(db, &err);
        LOG(LOG_INFO, "%s():%d - dbi error querying database (%s)\n", __FUNCTION__, __LINE__, err);
        return -1;
    }
    
    if(boxid < 0){
	LOG(LOG_INFO, "%s():%d - boxid %d !!!!\n", __FUNCTION__, __LINE__, boxid);
	return -1;
    }
    
    result = dbi_conn_queryf(db, "UPDATE "DB_TABLE_DEVICES" SET name='%s' WHERE device_id=%d", name, boxid);
    

    if(result){
	dbi_result_free(result);
    } else {
	const char *err;
        dbi_conn_error(db, &err);
        LOG(LOG_INFO, "%s():%d - dbi error querying database (%s)\n", __FUNCTION__, __LINE__, err);
        return -1;
    } 

    LOG(LOG_INFO, "%s():%d - name updated to '%s' for moxid  %d !!!!\n", __FUNCTION__, __LINE__, name, boxid);

    
    result = dbi_conn_queryf(db, "SELECT hname, localid FROM "DB_TABLE_DEVICES" WHERE  device_id=%d", boxid);
    
    if(result){
	if(dbi_result_next_row(result)) {
	    len +=  snprintf(buf+len, maxlen-len, "%s: %s",
			     dbi_result_get_string(result, "localid"),
			     dbi_result_get_string(result, "hname")
			     );
	}
	dbi_result_free(result);
    } else {
        const char *err;
        dbi_conn_error(db, &err);
        LOG(LOG_INFO, "%s():%d - dbi error querying database (%s)\n", 
            __FUNCTION__, __LINE__, err);
        return -1;
    }

    LOG(LOG_INFO, "%s():%d - read localiid and hname:  %s !!!!\n", __FUNCTION__, __LINE__, name, buf);
    
    int other_pwid = -1;
    int working_pwid = 0;

    result = dbi_conn_queryf(db,  
			     "SELECT pwid , used, atid  FROM acc_devices_pwl JOIN acc_types USING(atid)"
			     " WHERE agid = 1 AND acc_devices_pwl.enable = 1 AND acc_types.enable =1"
			     " AND id = %d  ORDER BY atid ASC", boxid);

    if(result){
	if(dbi_result_next_row(result)) {
	    other_pwid = dbi_result_get_int(result, "pwid");
	    if(dbi_result_get_int(result, "used")==1)
		working_pwid++;
	    if(dbi_result_get_int(result, "atid")== REMACC_TYPE_MAC)
		working_pwid++;
	}
	dbi_result_free(result);
    } else {
        const char *err;
        dbi_conn_error(db, &err);
        LOG(LOG_INFO, "%s():%d - dbi error querying database (%s)\n", 
            __FUNCTION__, __LINE__, err);
        return -1;
    }

    LOG(LOG_INFO, "%s():%d - searched for other pwid :  %d !!!!\n", __FUNCTION__, __LINE__, working_pwid);

    if(working_pwid>0){
	LOG(LOG_INFO, "%s():%d - has working pwid, no new pwid are issued (%d)\n" ,__FUNCTION__, __LINE__,working_pwid);
	return len;
    }	

    char other_pwid_str[32];
    if(other_pwid < 0){
	sprintf(other_pwid_str, "NULL");
    } else {
	sprintf(other_pwid_str, "%d", other_pwid);
    }

    result = dbi_conn_queryf(db,  "INSERT INTO  `rembox`.`acc_devices_pwl`"
			     "        (`pwid` ,`atid` ,`id` ,`username` ,`password` ,`enable` ,`exported` ,`used` ,`created` ,`replaced`)"
			     " VALUES (NULL ,  %d,  %d,  '%s', NULL ,  '1',  '0',  '0', CURRENT_TIMESTAMP ,  %s)"
			     , REMACC_TYPE_MAC, boxid, name, other_pwid_str);

    if(result){
	dbi_result_free(result);
    } else {
	const char *err;
        dbi_conn_error(db, &err);
        LOG(LOG_INFO, "%s():%d - dbi error querying database (%s)\n", __FUNCTION__, __LINE__, err);
        return -1;
    } 

    LOG(LOG_INFO, "%s():%d - inserted new pwid :  %d !!!!\n", __FUNCTION__, __LINE__, dbi_conn_sequence_last(db, NULL));


    return len;

}
Example #11
0
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
int rootjobnet_scheduling(rootjobnet_t * obj, const time_t t)
{
    int rc, num, sec;
    apr_uint64_t id;
    time_t i, tz, start_time, end_time;
    dbi_result result = NULL;
    jobunit_t *obj_topjobnet = NULL;
    schedule_t *obj_schedule = NULL;

    jbxlog_trace("In %s()", __func__);
    if (obj == NULL)
        return -1;

    jbxlog_trace
        ("In %s() id: %llu, loader_interval: %d, current time: %ld",
         __func__, obj->id, obj->loader_interval, t);
    if (t == 0 || obj->loader_interval < 1) {
        jbxlog_warn("In %s() current time or loader_interval is unset",
                    __func__);
        return -1;
    }
    // load jobunit & rootjobnet information to proc_topjobnet
    rc = -1;
    obj_topjobnet = jobunit_new();
    if (jobunit_select(obj_topjobnet, obj->jobunit_id) != 0) {
        jbxlog_warn("In %s() can not find jobunit_id: %llu",
                    __func__, obj->jobunit_id);
        goto error;
    }
    obj_topjobnet->jobunit_id = obj->jobunit_id;
    obj_topjobnet->proc_jobunit_id = 0;
    obj_topjobnet->mode = TOPJOBNET_MODE_SCHEDULE;
    obj_topjobnet->run_type = obj->run_type;
    obj_topjobnet->delay_limit = obj->delay_limit;

    // search schedules
    result =
        jbxdb_select("SELECT * FROM schedules WHERE jobunit_id = %llu",
                     obj->jobunit_id);
    if (result == NULL)
        goto error;

    // calc schedule period
    tz = 0;
    tz = mktime(gmtime(&tz));
    sec = obj->loader_interval * 60;
    start_time = ((time_t) ((t - tz) / sec + 1)) * sec;
    start_time = mktime(gmtime(&start_time));
    end_time = start_time + sec;
    jbxlog_trace
        ("In %s() current time: %ld, sec: %d, start_time: %ld, end_time: %ld",
         __func__, t, sec, start_time, end_time);

    num = 0;
    obj_schedule = schedule_new();
    while (dbi_result_next_row(result)) {
        schedule_load(obj_schedule, result);
        for (i = start_time; i < end_time; i += 60) {
            // check schedule
            if (schedule_on_time(obj_schedule, i) != JOBBOX_TRUE)
                continue;

            // insert topjobnet
            jbxlog_trace
                ("In %s() the schedule_time: %ld will be loaded. schedule_id: %llu",
                 __func__, i, obj_schedule->id);

            //  create topjobnet
            obj_topjobnet->schedule_time = i;
            id = proc_topjobnet_insert(obj_topjobnet);
            if (id == 0) {
                continue;
            }
            num++;
        }
    }
    jbxlog_trace("In %s() rootjobnet is loaded. id: %llu, num: %d",
                 __func__, obj->id, num);

    rc = 0;
  error:
    jobunit_destroy(obj_topjobnet);
    schedule_destroy(obj_schedule);
    dbi_result_free(result);
    return rc;
}
Example #12
0
static void calc_emp_uas_stats(struct module *mod, dbi_conn conn)
{
    int ct = 0;
    char dev_ip[LEN_32];
    char dev_port[LEN_32];
    dbi_result result = 0;
    ST_UAS *pe = NULL;
    tDBConn *pconn = NULL;
    int     user_status = -1;

    pe = (ST_UAS *)mod->emp_array;

    /* acquire every enterprise id */
    result = dbi_conn_queryf(conn, "select u_number, u_e_id from \"T_User\" order by u_e_id");
    if (result) {
        while(dbi_result_next_row(result)) {
            pe[ct].sdr_num = atoll(dbi_result_get_string(result, "u_number"));
            pe[ct].sdr_id = dbi_result_get_longlong(result, "u_e_id");
            convert_time_to_string(statis.cur_time - 24*60*60, pe[ct].sdr_time, 1);
            ct++;
        }
        dbi_result_free(result);
    }

    logRecord(LOG_INFO, "%s(%d) uas start cal...", __FUNCTION__, __LINE__ );
    for (ct = 0; ct < mod->emp_record; ct++)
    {
        long long sdr_id = pe[ct].sdr_id;
        long long sdr_num = pe[ct].sdr_num;

        result = dbi_conn_queryf(conn, "select d_ip2 from \"T_Device\" where d_id = \
                (select e_ss_id from \"T_Enterprise\" where e_id = %lld);", sdr_id);
        if (result) {
            while (dbi_result_next_row(result)) {
                memset(dev_ip, '\0', LEN_32);
                memset(dev_port, '\0', LEN_32);
                strcpy(dev_ip, dbi_result_get_string(result, "d_ip2"));
                strcpy(dev_port, "5432");
            }
            dbi_result_free(result);
        }

        if ((pconn = attach_conn(SSDB, dev_ip, dev_port)) == NULL)
        {
            logRecord(LOG_ERR, "%s(%d): failed to get SSdb conn, ssip(%s)-ssport(%s).\n", \
                __FUNCTION__, __LINE__, dev_ip, dev_port );
            continue;
        }

        pe[ct].sdr_online_times = dbi_query_long(pconn->conn, "count", "select count(*) \
                from \"loginrecord_%lld\" where time between '%lld' and '%lld' \
                and type = 1 and number = '%lld';",
                sdr_id, (statis.cur_time-24*60*60), statis.cur_time, sdr_num);

        pe[ct].sdr_offline_times = dbi_query_long(pconn->conn, "count", "select count(*) \
                from \"loginrecord_%lld\" where time between '%lld' and '%lld' \
                and type = 2 and number = '%lld';",
                sdr_id, (statis.cur_time-24*60*60), statis.cur_time, sdr_num);

        /*
        if (pe[ct].sdr_online_times != 0 || pe[ct].sdr_offline_times != 0)
            pe[ct].sdr_active_flag = 1;
        */
        if ( (pe[ct].sdr_online_times > 0) || (pe[ct].sdr_offline_times > 0) )
        {
            pe[ct].sdr_active_flag = 1;
        }
        else
        {
            /* not find yesterday user status, 
            * need look up user last status in loginrecord_e_id, 
            */
            user_status = dbi_query_long( pconn->conn, "type", "select type \
                from \"loginrecord_%lld\" where number='%lld' order by time desc limit 1;", \
                sdr_id, sdr_num );
            if ( user_status == USER_ONLINE )
            {
                pe[ct].sdr_active_flag = USER_STATUS_ACTIVITY;
            }
            else if ( user_status == USER_OFFLINE )
            {
                pe[ct].sdr_active_flag = USER_STATUS_INACTIVITY;
            }
            else
            {
                pe[ct].sdr_active_flag = USER_STATUS_INACTIVITY;
            }
        }

        detach_conn(pconn);
    }
    logRecord(LOG_INFO, "%s(%d) uas end cal...", __FUNCTION__, __LINE__ );


    //log_uas_stats(pe, mod->emp_record);

    return;
}
Example #13
0
static void calc_ser_ccs(struct module *mod, dbi_conn conn, int interval)
{
    int ct = 0, st = 0;
    dbi_result result = 0;
    ST_CCS *ps = NULL;
    ST_CCS *pe = NULL;
    long long rst = 0;

    ps = (ST_CCS *)mod->ser_array;
    pe = (ST_CCS *)mod->emp_array;

    st = 0;
    /* acquire ser uss stats */
    result = dbi_conn_queryf(conn, "select d_id from \"T_Device\" where d_type = 'mds' order by d_id");
    if (result) {
        while(dbi_result_next_row(result)) {
            ps[st].sdr_id = dbi_result_get_longlong(result, "d_id");
            convert_time_to_string(statis.cur_time, ps[st].sdr_record_time, 0);
            convert_time_to_string(statis.cur_time - 24*60*60, ps[st].sdr_time, 1);
            if (interval == 0) {
                ps[st].sdr_cyc_type = 0;
            } else if (interval == 7) {
                ps[st].sdr_cyc_type = 1;
            } else {
                ps[st].sdr_cyc_type = 2;
            }
            st++;
        }
        dbi_result_free(result);
    }

    for (st = 0; st < mod->ser_record; st++)
    {
        result = dbi_conn_queryf(conn, "select e_id from \"T_Enterprise\" where \
                e_mds_id = '%lld' order by e_id ", ps[st].sdr_id);
        if (result) {
            while(dbi_result_next_row(result)) {
                rst = dbi_result_get_longlong(result, "e_id");
                for (ct = 0; ct < mod->emp_record; ct++) {
                    if (rst == pe[ct].sdr_id) {
                        ps[st].sdr_ptt_time += pe[ct].sdr_ptt_time;
                        ps[st].sdr_ptt_count += pe[ct].sdr_ptt_count;
                        ps[st].sdr_audio_time += pe[ct].sdr_audio_time;
                        ps[st].sdr_audio_caller_time += pe[ct].sdr_audio_caller_time;
                        ps[st].sdr_audio_callee_time += pe[ct].sdr_audio_callee_time;
                        ps[st].sdr_audio_count += pe[ct].sdr_audio_count;
                        ps[st].sdr_audio_caller_count += pe[ct].sdr_audio_caller_count;
                        ps[st].sdr_audio_callee_count += pe[ct].sdr_audio_callee_count;
                        ps[st].sdr_video_time += pe[ct].sdr_video_time;
                        ps[st].sdr_video_caller_time += pe[ct].sdr_video_caller_time;
                        ps[st].sdr_video_callee_time += pe[ct].sdr_video_callee_time;
                        ps[st].sdr_video_count += pe[ct].sdr_video_count;
                        ps[st].sdr_video_caller_count += pe[ct].sdr_video_caller_count;
                        ps[st].sdr_video_callee_count += pe[ct].sdr_video_callee_count;

                        break;
                    }
                }
            }
            dbi_result_free(result);
        }
    }

    //log_ccs_stats(ps, mod->ser_record);

    return;
}
Example #14
0
File: dbi.c Project: Bradan/gammu
/* set pointer to next row */
int SMSDDBI_NextRow(GSM_SMSDConfig * Config, SQL_result *res)
{
	return dbi_result_next_row(res->dbi);
}
Example #15
0
//*******************************************************************
// retrieve the definitions + status
// get it from the cache. if there but too old: delete
// If a probe definition does not exist, it will be created.
// in case of mysql-has-gone-away type errors, we keep on running, 
// it will be caught later-on.
//*******************************************************************
void *bb_cpu_get_def(trx *t, int create)
{
  struct probe_def *def;
  struct bb_cpu_result *res = (struct bb_cpu_result *)t->res;
  dbi_result result;
  time_t now = time(NULL);

  if (res->color != STAT_PURPLE && res->server == 0) { 
    // first we find the serverid, this will be used to find the probe definition in the hashtable
    result = db_query(t->probe->db, 0, query_server_by_name, res->hostname, res->hostname, 
                      res->hostname, res->hostname, res->hostname);
    if (!result) {
      return(NULL);
    }
    if (dbi_result_next_row(result)) {
      res->server   = dbi_result_get_int_idx(result, 0);
    } else {
      LOG(LOG_NOTICE, "%s:%u@%s: server %s not found", res->realm, res->stattime, t->fromhost, res->hostname);
      dbi_result_free(result);
      return(NULL);
    }
    dbi_result_free(result);
  }

  // look in the cache for the def
  def = g_hash_table_lookup(t->probe->cache, &res->server);
  if (def && def->stamp < now - (120 + uw_rand(240))) { // older then 2 - 6 minutes?
     g_hash_table_remove(t->probe->cache, &res->server);
     def = NULL;
  }
  // if not there retrieve from database and insert in hash
  if (def == NULL) {
    def = g_malloc0(t->probe->def_size);
    def->stamp    = time(NULL);
    def->server   = res->server;
    def->pgroup   = 1;
    strcpy(def->hide, "no");

    // first find the definition based on the serverid
    result = db_query(t->probe->db, 0, "select id, yellow, red, contact, hide, email, sms, delay "
                                    "from pr_%s_def where server = '%u'", 
                      res->name, res->server);
    if (!result) {
      g_free(def);
      return(NULL);
    }
    if (dbi_result_get_numrows(result) == 0) { // DEF RECORD NOT FOUND
      char sequence[40];
      // no def record found? Create one. 
      dbi_result_free(result);
      result = db_query(t->probe->db, 0, 
                        "insert into pr_%s_def (server, description) values ('%u', '%s')", 
                         res->name, res->server, res->hostname);
      dbi_result_free(result);
      sprintf(sequence, "pr_%s_def_id_seq", res->name);
      def->probeid = dbi_conn_sequence_last(t->probe->db, sequence);
      LOG(LOG_NOTICE, "%s:%u@%s: pr_%s_def created for %s, id = %u", 
          res->realm, res->stattime, t->fromhost, res->name, res->hostname, def->probeid);
      result = db_query(t->probe->db, 0, "select id, yellow, red, contact, hide, email, sms, delay "
                                      "from pr_%s_def where id = '%u'", 
                        res->name, def->probeid);
    }
    if (!dbi_result_next_row(result)) {
      LOG(LOG_NOTICE, "%s:%u@%s: no pr_%s_def found for server %u - skipped", 
          res->realm, res->stattime, t->fromhost, res->name, res->server);
      dbi_result_free(result);
      g_free(def);
      return(NULL);
    }

    def->probeid = dbi_result_get_int(result, "id");
    def->yellow  = dbi_result_get_float(result, "yellow");
    def->red     = dbi_result_get_float(result, "red");
    def->contact = dbi_result_get_int(result, "contact");
    strcpy(def->hide, dbi_result_get_string_default(result, "hide", "no"));
    strcpy(def->email, dbi_result_get_string_default(result, "email", ""));
    strcpy(def->sms, dbi_result_get_string_default(result, "sms", ""));
    def->delay   = dbi_result_get_int(result, "delay");

    dbi_result_free(result);
    result = db_query(t->probe->db, 0, 
                      "select color "
                      "from   pr_status "
                      "where  class = '%u' and probe = '%u'", t->probe->class, def->probeid);
    if (result) {
      if (dbi_result_next_row(result)) {
        def->color   = dbi_result_get_int(result, "color");
      } else {
        LOG(LOG_NOTICE, "%s:%u@%s: pr_status record for %s id %u not found", 
           res->realm, res->stattime, t->fromhost, res->name, def->probeid);
      }
      dbi_result_free(result);
    }
    if (!def->color) def->color = res->color;

    result = db_query(t->probe->db, 0, 
                      "select stattime from pr_%s_raw use index(probstat) "
                      "where probe = '%u' order by stattime desc limit 1",
                       res->name, def->probeid);
    if (result) {
      if (dbi_result_next_row(result)) {
        def->newest = dbi_result_get_int(result, "stattime");
      }
      dbi_result_free(result);
    }
    g_hash_table_insert(t->probe->cache, guintdup(def->server), def);
  }
Example #16
0
/** Users discovered a bug in some distributions of libdbi, where if
 * it is compiled on certain versions of gcc with the -ffast-math
 * compiler option it fails to correctly handle saving of 64-bit
 * values. This function tests for the problem.
 * @param: conn: The just-opened dbi_conn
 * @returns: GNC_DBI_PASS if the dbi library is safe to use,
 * GNC_DBI_FAIL_SETUP if the test could not be completed, or
 * GNC_DBI_FAIL_TEST if the bug was found.
 */
static GncDbiTestResult
dbi_library_test (dbi_conn conn)
{
    int64_t testlonglong = -9223372036854775807LL, resultlonglong = 0;
    uint64_t testulonglong = 9223372036854775807LLU, resultulonglong = 0;
    double testdouble = 1.7976921348623157E+307, resultdouble = 0.0;
    dbi_result result;
    GncDbiTestResult retval = GNC_DBI_PASS;

    result = dbi_conn_query (conn, "CREATE TEMPORARY TABLE numtest "
                             "( test_int BIGINT, test_unsigned BIGINT,"
                             " test_double FLOAT8 )");
    if (result == nullptr)
    {
        PWARN ("Test_DBI_Library: Create table failed");
        return GNC_DBI_FAIL_SETUP;
    }
    dbi_result_free (result);
    std::stringstream querystr;
    querystr << "INSERT INTO numtest VALUES (" << testlonglong <<
        ", " << testulonglong << ", " << std::setprecision(12) <<
        testdouble << ")";
    auto query = querystr.str();
    result = dbi_conn_query (conn, query.c_str());
    if (result == nullptr)
    {
        PWARN ("Test_DBI_Library: Failed to insert test row into table");
        return GNC_DBI_FAIL_SETUP;
    }
    dbi_result_free (result);
    gnc_push_locale (LC_NUMERIC, "C");
    result = dbi_conn_query (conn, "SELECT * FROM numtest");
    if (result == nullptr)
    {
        const char* errmsg;
        dbi_conn_error (conn, &errmsg);
        PWARN ("Test_DBI_Library: Failed to retrieve test row into table: %s",
               errmsg);
        dbi_conn_query (conn, "DROP TABLE numtest");
        gnc_pop_locale (LC_NUMERIC);
        return GNC_DBI_FAIL_SETUP;
    }
    while (dbi_result_next_row (result))
    {
        resultlonglong = dbi_result_get_longlong (result, "test_int");
        resultulonglong = dbi_result_get_ulonglong (result, "test_unsigned");
        resultdouble = dbi_result_get_double (result, "test_double");
    }
    gnc_pop_locale (LC_NUMERIC);
    if (testlonglong != resultlonglong)
    {
        PWARN ("Test_DBI_Library: LongLong Failed %" PRId64 " != % " PRId64,
               testlonglong, resultlonglong);
        retval = GNC_DBI_FAIL_TEST;
    }
    if (testulonglong != resultulonglong)
    {
        PWARN ("Test_DBI_Library: Unsigned longlong Failed %" PRIu64 " != %"
               PRIu64, testulonglong, resultulonglong);
        retval = GNC_DBI_FAIL_TEST;
    }
    /* A bug in libdbi stores only 7 digits of precision */
    if (testdouble >= resultdouble + 0.000001e307 ||
        testdouble <= resultdouble - 0.000001e307)
    {
        PWARN ("Test_DBI_Library: Double Failed %17e != %17e",
               testdouble, resultdouble);
        retval = GNC_DBI_FAIL_TEST;
    }
    return retval;
}
Example #17
0
/**
 * Go through the database, read and add to the server all
 * the server permissions stored.
 *
 * @param c the configuration of the db
 * @param s the server
 */
int db_create_sv_privileges(struct config *c, struct server *s)
{
	char *q = "SELECT * FROM server_privileges WHERE server_id = %i;";
	dbi_result res;
	const char *group;
	int g;
	struct server_privileges *sp = s->privileges;

	logger(LOG_INFO, "Loading server privileges.");

	res = dbi_conn_queryf(c->conn, q, s->id);
	if (res) {
		while (dbi_result_next_row(res)) {
			/* Get the id of the group from the string */
			group = dbi_result_get_string(res, "user_group");
			if (strcmp(group, "server_admin") == 0) {
				g = PRIV_SERVER_ADMIN;
			} else if (strcmp(group, "channel_admin") == 0) {
				g = PRIV_CHANNEL_ADMIN;
			} else if (strcmp(group, "operator") == 0) {
				g = PRIV_OPERATOR;
			} else if (strcmp(group, "voice") == 0) {
				g = PRIV_VOICE;
			} else if (strcmp(group, "registered") == 0) {
				g = PRIV_REGISTERED;
			} else if (strcmp(group, "anonymous") == 0) {
				g = PRIV_ANONYMOUS;
			} else {
				logger(LOG_ERR, "server_privileges.user_group = %s, \
						expected : server_admin, channel_admin, \
						operator, voice, registered, anonymous.",
						group);
				continue;
			}
			logger(LOG_DBG, "GROUP : %i", g);
			/* Copy all privileges to the server... */
			sp->priv[g][SP_ADM_DEL_SERVER] = dbi_result_get_uint(res, "adm_del_server");
			sp->priv[g][SP_ADM_ADD_SERVER] = dbi_result_get_uint(res, "adm_add_server");
			sp->priv[g][SP_ADM_LIST_SERVERS] = dbi_result_get_uint(res, "adm_list_servers");
			sp->priv[g][SP_ADM_SET_PERMISSIONS] = dbi_result_get_uint(res, "adm_set_permissions");
			sp->priv[g][SP_ADM_CHANGE_USER_PASS] = dbi_result_get_uint(res, "adm_change_user_pass");
			sp->priv[g][SP_ADM_CHANGE_OWN_PASS] = dbi_result_get_uint(res, "adm_change_own_pass");
			sp->priv[g][SP_ADM_LIST_REGISTRATIONS] = dbi_result_get_uint(res, "adm_list_registrations");
			sp->priv[g][SP_ADM_REGISTER_PLAYER] = dbi_result_get_uint(res, "adm_register_player");

			sp->priv[g][SP_ADM_CHANGE_SERVER_CODECS] = dbi_result_get_uint(res, "adm_change_server_codecs");
			sp->priv[g][SP_ADM_CHANGE_SERVER_TYPE] = dbi_result_get_uint(res, "adm_change_server_type");
			sp->priv[g][SP_ADM_CHANGE_SERVER_PASS] = dbi_result_get_uint(res, "adm_change_server_pass");
			sp->priv[g][SP_ADM_CHANGE_SERVER_WELCOME] = dbi_result_get_uint(res, "adm_change_server_welcome");
			sp->priv[g][SP_ADM_CHANGE_SERVER_MAXUSERS] = dbi_result_get_uint(res, "adm_change_server_maxusers");
			sp->priv[g][SP_ADM_CHANGE_SERVER_NAME] = dbi_result_get_uint(res, "adm_change_server_name");
			sp->priv[g][SP_ADM_CHANGE_WEBPOST_URL] = dbi_result_get_uint(res, "adm_change_webpost_url");
			sp->priv[g][SP_ADM_CHANGE_SERVER_PORT] = dbi_result_get_uint(res, "adm_change_server_port");

			sp->priv[g][SP_ADM_START_SERVER] = dbi_result_get_uint(res, "adm_start_server");
			sp->priv[g][SP_ADM_STOP_SERVER] = dbi_result_get_uint(res, "adm_stop_server");
			sp->priv[g][SP_ADM_MOVE_PLAYER] = dbi_result_get_uint(res, "adm_move_player");
			sp->priv[g][SP_ADM_BAN_IP] = dbi_result_get_uint(res, "adm_ban_ip");

			sp->priv[g][SP_CHA_DELETE] = dbi_result_get_uint(res, "cha_delete");
			sp->priv[g][SP_CHA_CREATE_MODERATED] = dbi_result_get_uint(res, "cha_create_moderated");
			sp->priv[g][SP_CHA_CREATE_SUBCHANNELED] = dbi_result_get_uint(res, "cha_create_subchanneled");
			sp->priv[g][SP_CHA_CREATE_DEFAULT] = dbi_result_get_uint(res, "cha_create_default");
			sp->priv[g][SP_CHA_CREATE_UNREGISTERED] = dbi_result_get_uint(res, "cha_create_unregistered");
			sp->priv[g][SP_CHA_CREATE_REGISTERED] = dbi_result_get_uint(res, "cha_create_registered");
			sp->priv[g][SP_CHA_JOIN_REGISTERED] = dbi_result_get_uint(res, "cha_join_registered");

			sp->priv[g][SP_CHA_JOIN_WO_PASS] = dbi_result_get_uint(res, "cha_join_wo_pass");
			sp->priv[g][SP_CHA_CHANGE_CODEC] = dbi_result_get_uint(res, "cha_change_codec");
			sp->priv[g][SP_CHA_CHANGE_MAXUSERS] = dbi_result_get_uint(res, "cha_change_maxusers");
			sp->priv[g][SP_CHA_CHANGE_ORDER] = dbi_result_get_uint(res, "cha_change_order");
			sp->priv[g][SP_CHA_CHANGE_DESC] = dbi_result_get_uint(res, "cha_change_desc");
			sp->priv[g][SP_CHA_CHANGE_TOPIC] = dbi_result_get_uint(res, "cha_change_topic");
			sp->priv[g][SP_CHA_CHANGE_PASS] = dbi_result_get_uint(res, "cha_change_pass");
			sp->priv[g][SP_CHA_CHANGE_NAME] = dbi_result_get_uint(res, "cha_change_name");

			sp->priv[g][SP_PL_GRANT_ALLOWREG] = dbi_result_get_uint(res, "pl_grant_allowreg");
			sp->priv[g][SP_PL_GRANT_VOICE] = dbi_result_get_uint(res, "pl_grant_voice");
			sp->priv[g][SP_PL_GRANT_AUTOVOICE] = dbi_result_get_uint(res, "pl_grant_autovoice");
			sp->priv[g][SP_PL_GRANT_OP] = dbi_result_get_uint(res, "pl_grant_op");
			sp->priv[g][SP_PL_GRANT_AUTOOP] = dbi_result_get_uint(res, "pl_grant_autoop");
			sp->priv[g][SP_PL_GRANT_CA] = dbi_result_get_uint(res, "pl_grant_ca");
			sp->priv[g][SP_PL_GRANT_SA] = dbi_result_get_uint(res, "pl_grant_sa");

			sp->priv[g][SP_PL_REGISTER_PLAYER] = dbi_result_get_uint(res, "pl_register_player");
			sp->priv[g][SP_PL_REVOKE_ALLOWREG] = dbi_result_get_uint(res, "pl_revoke_allowreg");
			sp->priv[g][SP_PL_REVOKE_VOICE] = dbi_result_get_uint(res, "pl_revoke_voice");
			sp->priv[g][SP_PL_REVOKE_AUTOVOICE] = dbi_result_get_uint(res, "pl_revoke_autovoice");
			sp->priv[g][SP_PL_REVOKE_OP] = dbi_result_get_uint(res, "pl_revoke_op");
			sp->priv[g][SP_PL_REVOKE_AUTOOP] = dbi_result_get_uint(res, "pl_revoke_autoop");
			sp->priv[g][SP_PL_REVOKE_CA] = dbi_result_get_uint(res, "pl_revoke_ca");
			sp->priv[g][SP_PL_REVOKE_SA] = dbi_result_get_uint(res, "pl_revoke_sa");

			sp->priv[g][SP_PL_ALLOW_SELF_REG] = dbi_result_get_uint(res, "pl_allow_self_reg");
			sp->priv[g][SP_PL_DEL_REGISTRATION] = dbi_result_get_uint(res, "pl_del_registration");

			sp->priv[g][SP_OTHER_CH_COMMANDER] = dbi_result_get_uint(res, "other_ch_commander");
			sp->priv[g][SP_OTHER_CH_KICK] = dbi_result_get_uint(res, "other_ch_kick");
			sp->priv[g][SP_OTHER_SV_KICK] = dbi_result_get_uint(res, "other_sv_kick");
			sp->priv[g][SP_OTHER_TEXT_PL] = dbi_result_get_uint(res, "other_text_pl");
			sp->priv[g][SP_OTHER_TEXT_ALL_CH] = dbi_result_get_uint(res, "other_text_all_ch");
			sp->priv[g][SP_OTHER_TEXT_IN_CH] = dbi_result_get_uint(res, "other_text_in_ch");
			sp->priv[g][SP_OTHER_TEXT_ALL] = dbi_result_get_uint(res, "other_text_all");
		}
		dbi_result_free(res);
	}
	return 1;
}
Example #18
0
/**
 * Prepare SQL queries and perform them.
 *
 * @param format printf-like string of SQL query
 * @param callback pointer to function to be called on results of SQL query
 * @param firstarg pointer to buffer for callback returned data
 * @return 0 (always, due to SQLite policy)
 */
int tagsistant_real_query(
	dbi_conn dbi,
	const char *format,
	int (*callback)(void *, dbi_result),
	char *file,
	int line,
	void *firstarg,
	...)
{
	va_list ap;
	va_start(ap, firstarg);

	/* check if connection has been created */
	if (NULL == dbi) {
		dbg('s', LOG_ERR, "ERROR! DBI connection was not initialized!");
		return(0);
	}

#if TAGSISTANT_USE_QUERY_MUTEX
	/* lock the connection mutex */
	g_mutex_lock(&tagsistant_query_mutex);
#endif

	/* check if the connection is alive */
	if (!dbi_conn_ping(dbi)	&& dbi_conn_connect(dbi) < 0) {
#if TAGSISTANT_USE_QUERY_MUTEX
		g_mutex_unlock(&tagsistant_query_mutex);
#endif
		dbg('s', LOG_ERR, "ERROR! DBI Connection has gone!");
		return(0);
	}

	/* replace all the single or double quotes with "<><>" in the format */
	gchar *escaped_format = g_regex_replace_literal(RX1, format, -1, 0, "<><>", 0, NULL);

	/* format the statement */
	gchar *statement = g_strdup_vprintf(escaped_format, ap);
	if (NULL == statement) {
#if TAGSISTANT_USE_QUERY_MUTEX
		/* lock the connection mutex */
		g_mutex_unlock(&tagsistant_query_mutex);
#endif
		dbg('s', LOG_ERR, "Null SQL statement");
		g_free(escaped_format);
		return(0);
	}

	/* prepend a backslash to all the single quotes inside the arguments */
	gchar *escaped_statement_tmp = g_regex_replace_literal(RX2, statement, -1, 0, "''", 0, NULL);

	/* replace "<><>" with a single quote */
	gchar *escaped_statement = g_regex_replace_literal(RX3, escaped_statement_tmp, -1, 0, "'", 0, NULL);

	/* log and do the query */
	dbg('s', LOG_INFO, "SQL from %s:%d: [%s]", file, line, escaped_statement);
	dbi_result result = dbi_conn_query(dbi, escaped_statement);

	tagsistant_dirty_logging(escaped_statement);
	tagsistant_wal(dbi, escaped_statement);

	g_free_null(escaped_format);
	g_free_null(escaped_statement_tmp);
	g_free_null(escaped_statement);

	/* call the callback function on results or report an error */
	int rows = 0;
	if (result) {

		if (callback) {
			while (dbi_result_next_row(result)) {
				callback(firstarg, result);
				rows++;
			}
		}
		dbi_result_free(result);

	} else {

		/* get the error message */
		const char *errmsg = NULL;
		dbi_conn_error(dbi, &errmsg);
		if (errmsg) dbg('s', LOG_ERR, "Error: %s.", errmsg);

	}

#if TAGSISTANT_USE_QUERY_MUTEX
	g_mutex_unlock(&tagsistant_query_mutex);
#endif

	return(rows);
}
Example #19
0
static void calc_emp_cds_stats(struct module *mod, dbi_conn conn)
{
    int ct = 0;
    char dev_ip[LEN_32];
    char dev_port[LEN_32];
    dbi_result result = 0;
    ST_CDS *pe = NULL;
    tDBConn *pconn = NULL;

    pe = (ST_CDS *)mod->emp_array;

    /* acquire every enterprise id */
    result = dbi_conn_queryf(conn, "select e_id from \"T_Enterprise\" order by e_id");
    if (result) {
        while(dbi_result_next_row(result)) {
            pe[ct].sdr_id = dbi_result_get_longlong(result, "e_id");
            convert_time_to_string(statis.cur_time, pe[ct].sdr_record_time, 0);
            convert_time_to_string(statis.cur_time - 24*60*60, pe[ct].sdr_time, 1);
            pe[ct].sdr_date_flag = 0;
            ct++;
        }
        dbi_result_free(result);
    }

    for (ct = 0; ct < mod->emp_record; ct++)
    {
        long long sdr_id = pe[ct].sdr_id;

        result = dbi_conn_queryf(conn, "select d_ip2 from \"T_Device\" where d_id = \
                (select e_ss_id from \"T_Enterprise\" where e_id = %lld);", sdr_id);
        if (result) {
            while (dbi_result_next_row(result)) {
                memset(dev_ip, '\0', LEN_32);
                memset(dev_port, '\0', LEN_32);
                strcpy(dev_ip, dbi_result_get_string(result, "d_ip2"));
                strcpy(dev_port, "5432");
            }
            dbi_result_free(result);
        }

        if ((pconn = attach_conn(SSDB, dev_ip, dev_port)) == NULL)
        {
            logRecord(LOG_ERR, "%s(%d): failed to get db conn\n", __FUNCTION__, __LINE__);
            continue;
        }

        pe[ct].sdr_ptt_htime = dbi_query_long(pconn->conn, "sum", "select sum(callsec) from \
                \"cdr_%lld\" where endtime < %lld and (call_type = 3 or call_type = 4);",
                sdr_id, statis.cur_time);
        pe[ct].sdr_ptt_hcount = dbi_query_long(pconn->conn, "count", "select count(*) from \
                \"cdr_%lld\" where endtime < %lld and (call_type = 3 or call_type = 4);",
                sdr_id, statis.cur_time);
        pe[ct].sdr_call_htime = 2 * dbi_query_long(pconn->conn, "sum", "select sum(callsec) from \
                \"cdr_%lld\" where endtime < %lld and (call_type = 1 or call_type = 2);",
                sdr_id, statis.cur_time);
        pe[ct].sdr_call_hcount = 2 * dbi_query_long(pconn->conn, "count", "select count(*) from \
                \"cdr_%lld\" where endtime < %lld and (call_type = 1 or call_type = 2);",
                sdr_id, statis.cur_time);
        pe[ct].sdr_video_htime = 2 * dbi_query_long(pconn->conn, "sum", "select sum(callsec) from \
                \"cdr_%lld\" where endtime < %lld and call_type = 2;",
                sdr_id, statis.cur_time);
        pe[ct].sdr_video_hcount = 2 * dbi_query_long(pconn->conn, "count", "select count(*) from \
                \"cdr_%lld\" where endtime < %lld and call_type = 2",
                sdr_id, statis.cur_time);
        pe[ct].sdr_audio_htime = 2 * dbi_query_long(pconn->conn, "sum", "select sum(callsec) from \
                \"cdr_%lld\" where endtime < %lld and call_type = 1;",
                sdr_id, statis.cur_time);
        pe[ct].sdr_audio_hcount = 2 * dbi_query_long(pconn->conn, "count", "select count(*) from \
                \"cdr_%lld\" where endtime < %lld and call_type = 1;",
                sdr_id, statis.cur_time);

        detach_conn(pconn);

    }

    //log_cds_stats(pe, mod->emp_record);

    return;
}
Example #20
0
//*******************************************************************
// SUMMARIZE A TABLE INTO AN OLDER PERIOD
//*******************************************************************
static void bb_cpu_summarize(trx *t, char *from, char *into, guint slot, guint slotlow, guint slothigh, gint resummarize)
{
  dbi_result result;
  struct probe_def *def = (struct probe_def *)t->def;
  float avg_yellow, avg_red;
  gfloat avg_loadavg;
  guint avg_user, avg_system, avg_idle;
  guint avg_swapped, avg_free, avg_buffered, avg_cached, avg_used;
  guint stattime;
  guint max_color;

  stattime = slotlow + ((slothigh-slotlow)/2);

  result = db_query(t->probe->db, 0,
                    "select avg(loadavg) as avg_loadavg, avg(user) as avg_user, avg(system) as avg_system, "
                    "       avg(idle) as avg_idle, avg(swapped) as avg_swapped, avg(free) as avg_free, "
                    "       avg(buffered) as avg_buffered, avg(cached) as avg_cached, avg(used) as avg_used, "
                    "       max(color) as max_color, avg(yellow) as avg_yellow, avg(red) as avg_red " 
                    "from   pr_bb_cpu_%s use index(probstat) "
                    "where  probe = '%d' and stattime >= %d and stattime < %d",
                    from, def->probeid, slotlow, slothigh);
  
  if (!result) return;
  if (dbi_result_get_numrows(result) == 0) { // no records found
    LOG(LOG_NOTICE, "nothing to summarize from %s for probe %u %u %u",
                       from, def->probeid, slotlow, slothigh);
    dbi_result_free(result);
    return;
  }

  if (!dbi_result_next_row(result)) {
    dbi_result_free(result);
    return;
  }
  if (dbi_result_field_is_null_idx(result, 0)) {
    LOG(LOG_NOTICE, "nothing to summarize from %s for probe %u %u %u", 
                       from, def->probeid, slotlow, slothigh);
    dbi_result_free(result);
    return;
  }

  avg_loadavg = dbi_result_get_float(result, "avg_loadavg");
  avg_user    = dbi_result_get_int(result, "avg_user");
  avg_system  = dbi_result_get_int(result, "avg_system");
  avg_idle    = dbi_result_get_int(result, "avg_idle");
  avg_swapped = dbi_result_get_int(result, "avg_swapped");
  avg_free    = dbi_result_get_int(result, "avg_free");
  avg_buffered= dbi_result_get_int(result, "avg_buffered");
  avg_cached  = dbi_result_get_int(result, "avg_cached");
  avg_used    = dbi_result_get_int(result, "avg_used");
  max_color   = dbi_result_get_int(result, "max_color");
  avg_yellow  = dbi_result_get_float(result, "avg_yellow");
  avg_red     = dbi_result_get_float(result, "avg_red");
  dbi_result_free(result);

  if (resummarize) {
    // delete old values
    result = db_query(t->probe->db, 0,
                    "delete from pr_bb_cpu_%s where probe = '%u' and stattime = '%u'",
                    into, def->probeid, stattime);
    dbi_result_free(result);
  }
  result = db_query(t->probe->db, 0,
                    "insert into pr_bb_cpu_%s (loadavg, user, system, idle, swapped, free, buffered, cached, " 
                    "                          used, probe, color, stattime, yellow, red, slot) "
                    "            values ('%f', '%u', '%u', '%u', '%u', '%u', '%u', '%u', "
                    "                    '%u', '%d', '%u', '%d', '%f', '%f', '%u')",
                    into, 
                    avg_loadavg, avg_user, avg_system, avg_idle, 
                    avg_swapped, avg_free, avg_buffered, avg_cached, 
                    avg_used, def->probeid, max_color, stattime,
                    avg_yellow, avg_red, slot);
  dbi_result_free(result);
}
Example #21
0
void refresh_database(dbi_conn conn)
{
  dbi_result result;
  char qry[1024];

  sprintf(qry,  "SELECT pr_mysql_def.id, pr_mysql_def.domid, pr_mysql_def.tblid, pr_realm.name, "
                "       pr_mysql_def.ipaddress, pr_mysql_def.dbname, "
                "       pr_mysql_def.dbuser, pr_mysql_def.dbpasswd,"
                "       pr_mysql_def.query, "
                "       pr_mysql_def.yellow,  pr_mysql_def.red "
                "FROM   pr_mysql_def, pr_realm "
                "WHERE  pr_mysql_def.id > 1 and pr_mysql_def.disable <> 'yes'"
                "       and pr_mysql_def.pgroup = '%d' and pr_realm.id = pr_mysql_def.domid",
                (unsigned)OPT_VALUE_GROUPID);

  result = db_query(conn, 1, qry);
  if (!result) {
    return;
  }
    
  while (dbi_result_next_row(result)) {
    int id;
    struct probedef *probe;

    id = dbi_result_get_uint(result, "id");
    probe = g_hash_table_lookup(cache, &id);
    if (!probe) {
      probe = g_malloc0(sizeof(struct probedef));
      if (dbi_result_get_uint(result, "domid") > 1) {
        probe->probeid = dbi_result_get_uint(result, "tblid");
        probe->realm=strdup(dbi_result_get_string(result, "name"));
      } else {
        probe->probeid = probe->id;
      }
      g_hash_table_insert(cache, guintdup(id), probe);
    }

    if (probe->ipaddress) g_free(probe->ipaddress);
    probe->ipaddress = dbi_result_get_string_copy(result, "ipaddress");
    if (probe->dbname) g_free(probe->dbname);
    probe->dbname = dbi_result_get_string_copy(result, "dbname");
    if (probe->dbuser) g_free(probe->dbuser);
    probe->dbuser = dbi_result_get_string_copy(result, "dbuser");
    if (probe->dbpasswd) g_free(probe->dbpasswd);
    probe->dbpasswd = dbi_result_get_string_copy(result, "dbpasswd");
    if (probe->query) g_free(probe->query);
    probe->query = dbi_result_get_string_copy(result, "query");
    probe->yellow = dbi_result_get_float(result, "yellow");
    probe->red = dbi_result_get_float(result, "red");
    if (probe->msg) g_free(probe->msg);
    probe->msg = NULL;
    probe->seen = 1;
  }
  if (dbi_conn_error_flag(conn)) {
    const char *errmsg;
    dbi_conn_error(conn, &errmsg);
    LOG(LOG_ERR, "%s", errmsg);
    g_hash_table_foreach(cache, reset_seen, NULL);
  } else {
    g_hash_table_foreach_remove(cache, return_seen, NULL);
  }
  dbi_result_free(result);
}
Example #22
0
static ftpd_chroot_status_t ftpd_dbi_map_chroot(const request_rec *r,
        const char **ret_chroot,
        const char **ret_initroot)
{
    ftpd_chroot_status_t ARV = FTPD_CHROOT_USER_NOT_FOUND;
    ftpd_dbi_config *conf;
    const char *query;
    const char *chroot;
    ftpd_dbi_rest *dbi_res;
    dbi_result result;
    ftpd_dbi_dconfig *dconf = ap_get_module_config(r->per_dir_config,
                              &ftpd_dbi_module);


    conf = apr_hash_get(ftpd_dbi_config_hash, dconf->id, APR_HASH_KEY_STRING);
    if (conf == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "[mod_ftpd_dbi.c] - Server Config for \"%s\" was not found",
                      dconf->id);
        return FTPD_CHROOT_FAIL;
    }

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                  "[mod_ftpd_dbi.c] Attempting to Acquire DBI Connection");
    apr_reslist_acquire(conf->pool, (void **) &dbi_res);

    /* make the query to get the user's password */
    if (conf->rec.isactive_field) {
        if (conf->rec.chroot_query == NULL) {
            query =
                "SELECT &{ChrootField} FROM &{Table} WHERE &{UsernameField}=&{GivenUsername} AND &{IsActiveField}!=0 LIMIT 0,1";
        }
        else {
            query = conf->rec.chroot_query;
        }
    }
    else {
        if (conf->rec.chroot_query == NULL) {
            query =
                "SELECT &{ChrootField} FROM &{Table} WHERE &{UsernameField}=&{GivenUsername} LIMIT 0,1";
        }
        else {
            query = conf->rec.chroot_query;
        }
    }
    /* perform the query */

    if ((query =
                populate_querystring(r, query, conf, dconf, dbi_res, r->user))
            && safe_dbi_query(dbi_res, &result, r, query) == 0) {
        /* store the query result */
        if (dbi_result_next_row(result)
                && dbi_result_get_numrows(result) == 1) {

            chroot =
                dbi_result_get_string_copy(result, conf->rec.chroot_field);
            if ((chroot == NULL) || (strcmp(chroot, "ERROR") == 0)) {
                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                              "[mod_ftpd_dbi.c] - libdbi returned an error when retrieving the chroot.");
                ARV = FTPD_CHROOT_FAIL;
            }
            else {
                // XXXX: Do more checks of the chroot here!
                *ret_chroot = apr_pstrdup(r->pool, chroot);
                ARV = FTPD_CHROOT_USER_FOUND;
            }
        }
        else {
            if (dbi_result_get_numrows(result) == 0) {
                ARV = FTPD_CHROOT_USER_NOT_FOUND;
            }
            else {
                ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                              "[mod_ftpd_dbi.c] %lu row(s) was not returned by dbi_result_get_numrows(result)",
                              (unsigned long) dbi_result_get_numrows(result));
                ARV = FTPD_CHROOT_FAIL;
            }
        }
        dbi_result_free(result);
    }
    else {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "[mod_ftpd_dbi.c] Query Failed!");
        ARV = FTPD_CHROOT_FAIL;
    }

    safe_dbi_rel_server(conf->pool, dbi_res, r);
    return ARV;
}