Ejemplo n.º 1
0
Archivo: michal.c Proyecto: Bakus/gammu
void execute_actions(void)
{
	int first, j = 0;
	size_t i;
	char buf3[5000], buf4[5000];

	//we search for select part
	first = 0;
	buf3[0] = 0;
	buf4[0] = 0;
	for (i = 0; i < strlen(Row2[10]); i++) {
		if (Row2[10][i] == '{') {
			if (first == 0)
				j = i;
			if (first == 1)
				break;
			first++;
		} else {
			if (first == 0) {
				buf3[strlen(buf3) + 1] = 0;
				buf3[strlen(buf3)] = Row2[10][i];
			} else if (first == 1) {
				buf4[strlen(buf4) + 1] = 0;
				buf4[strlen(buf4)] = Row2[10][i];
			}
		}
	}
	if (buf4[0] != 0) {
		if (strstr(buf4, "select") == NULL || strstr(buf4, "from") == NULL || strstr(buf4, "where") == NULL) {
			buf4[0] = 0;
			i = j;
		}
	}
	connect_to_db(Row2[2], Row2[4], Row2[8], Row2[6]);	//user,pass,pc,db
	if (mysql_real_query(&DB2, buf3, strlen(buf3))) {
		return;
	}
	if (!(Res3 = mysql_store_result(&DB2))) {
		return;
	}
	while ((Row3 = mysql_fetch_row(Res3))) {
		//for each value we execute actions
		if (buf4[0] != 0) {
			connect_to_db(Row2[3], Row2[5], Row2[9], Row2[7]);	//user,pass,pc,db
			if (mysql_real_query(&DB2, buf4, strlen(buf4))) {
				return;
			}
			if (!(Res4 = mysql_store_result(&DB2))) {
				return;
			}
			while ((Row4 = mysql_fetch_row(Res4))) {
				execute_all_actions(Row2[10] + i + 1);
			}
			mysql_free_result(Res4);
		} else {
			execute_all_actions(Row2[10] + i + 1);
		}
	}
	mysql_free_result(Res3);
}
Ejemplo n.º 2
0
void
show_current_query(char *conninfo, int procpid)
{
	int			i;
	int			rows;
	char		info[64];
	PGconn	   *pgconn;
	PGresult   *pgresult = NULL;

	sprintf(info, "Current query for procpid %d:\n\n", procpid);
	display_pager(info);

	/* Get the currently running query. */
	pgconn = connect_to_db(conninfo);
	if (pgconn != NULL)
	{
		pgresult = pg_query(pgconn, procpid);
		rows = PQntuples(pgresult);
	}
	else
	{
		rows = 0;
	}
	for (i = 0; i < rows; i++)
	{
		display_pager(PQgetvalue(pgresult, i, 0));
	}
	display_pager("\n\n");

	if (pgresult != NULL)
		PQclear(pgresult);
	PQfinish(pgconn);
}
Ejemplo n.º 3
0
void kitchenFrame::OnSettingsMenuSelected(wxCommandEvent& event)
{
    settings* set_dlg = new settings(this);
    set_dlg -> confi = config;
    set_dlg -> conn = conn;
    set_dlg -> set_now = &set_now;
    set_dlg -> fill_all();
    set_dlg -> ShowModal();

    if (
        host != config->Read(_T("/mysql/host")) ||
        user != config->Read(_T("/mysql/user")) ||
        pass != config->Read(_T("/mysql/pass")) ||
        dbase != config->Read(_T("/mysql/dbase"))
    )
    {
        connect_to_db();
    }


    wxString portTemp;
    portTemp << set_now.port;
    if(     set_now.addres != config->Read(_T("/program/addres")) ||
            portTemp != config->Read(_T("/program/port")))
    {
        read_settings();
        connectToServer();
    }
    else
    {
        read_settings();
    }
}
Ejemplo n.º 4
0
Archivo: michal.c Proyecto: Bakus/gammu
int check_if_avail(unsigned char *buf)
{
	int found;

	if (mysql_real_query(&DB, buf, strlen(buf))) {
		return FALSE;
	}
	if (!(Res2 = mysql_store_result(&DB))) {
		return FALSE;
	}
	found = TRUE;
	while ((Row2 = mysql_fetch_row(Res2))) {
		connect_to_db(Row2[4], Row2[5], Row2[6], Row2[2]);	//user,pass,pc,db
		if (mysql_real_query(&DB2, Row2[3], strlen(Row2[3]))) {
			mysql_free_result(Res2);
			return FALSE;
		}
		if (!(Res3 = mysql_store_result(&DB2))) {
			mysql_free_result(Res2);
			return FALSE;
		}
		Row3 = mysql_fetch_row(Res3);
		if (Row3 == NULL) {
			found = FALSE;
			break;
		}
//              printf("%s\n",Row2[3]);
	}
	mysql_free_result(Res2);
	mysql_free_result(Res3);
	return found;
}
Ejemplo n.º 5
0
int main(int argc, char **argv)
{
	char		line[500];

	SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
	SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

	connect_to_db("DSN=psqlodbc_test_dsn;Database=postgres");
	printf("Dropping and creating database contrib_regression...\n");
	run_statement("DROP DATABASE IF EXISTS contrib_regression");
	run_statement("CREATE DATABASE contrib_regression");

	connect_to_db("DSN=psqlodbc_test_dsn;Database=contrib_regression");

	printf("Running initialization script...\n");
	while (fgets(line, sizeof(line), stdin) != NULL)
		run_statement(line);

	printf("Done!\n");

	return 0;
}
Ejemplo n.º 6
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    add_context_menus();
    read_settings();
    connect_to_db();
    ui->languages->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView_words->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView_translated_words->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView_translated_words->setSelectionBehavior( QAbstractItemView::SelectRows );
    new_crossword = new crossword();
    ui->new_crossword_scroll->setWidget(new_crossword);
}
Ejemplo n.º 7
0
void connect_and_create(char *pluginkey)
{
  string name = cstring_copy_string("my new plugin");
  string desc = cstring_copy_string("Lorem ipsum");
  string author = cstring_copy_string("author of the plugin");
  string license = cstring_copy_string("license foobar");

  connect_to_db();

  assert_int_equal(0, db_plugin_add(pluginkey, name, desc, author, license));

  free_string(name);
  free_string(desc);
  free_string(author);
  free_string(license);
}
Ejemplo n.º 8
0
void Connector::init(string host, string port, string user, string password, string db)
{

#ifdef MSSQL
	login_rec = NULL;
	conn_ptr = NULL;
	dberrhandle (err_handler);
	dbmsghandle (msg_handler);

	conn_status = false;
	cout << "init db connectors.. " << endl;
	init_db_connectors();
	if(conn_status){
		set_login_struct(user , password);
		cout << "added login credentials to struct.. " << endl;
		if (conn_status){
			cout << "connecting to db..." << db << endl;
			connect_to_db(host , port);
			if (conn_status){
				choose_db(db);
			} else {
				cout << "geterror: " << geterror() << endl;
			}
		} else {
			cout << "geterror: " << geterror() << endl;
		}
	} else {
		cout << "geterror: " << geterror() << endl;
	}
#endif
#ifdef WATCHLIST_MYSQL
	cout << "Connecting to mysql db.. "  << endl;
	conn_status = true;
	mysql_init(&mysqlID);
	mysql_options(&mysqlID, MYSQL_OPT_RECONNECT, (char *)&conn_status);
	mysql_real_connect(&mysqlID, host.c_str(), user.c_str(), password.c_str(), db.c_str(), 0, NULL, CLIENT_COMPRESS | CLIENT_MULTI_RESULTS | CLIENT_MULTI_STATEMENTS);

#endif

}
Ejemplo n.º 9
0
void time_loggerFrame::OnButton11Click(wxCommandEvent& event)
{

    if(StaticText1->GetLabel()!=_T("")){
if(StaticText1->GetLabel()==_T("9999")){
    StaticText1->SetLabel(_T(""));
    settings* set_dlg = new settings(this);
    set_dlg->confi = config;
    set_dlg->set_now = &sett;
    set_dlg->conn = conn;
    set_dlg->fill_all();
    set_dlg->ShowModal();
    connect_to_db();
        }else{

    if (getEmployeeId() !=1 )
    {
    StaticText1->SetLabel(_T(""));
        login* Mylogin = new login(0);
        Mylogin->empId = empId;
        Mylogin -> empName = empName;
        Mylogin -> conn = conn;
        Mylogin->setFace();
        Mylogin->ShowModal();
        Mylogin->Destroy();
        delete Mylogin;
    }
    else
    {
    StaticText1->SetLabel(_T(""));
        wxMessageDialog* dlg = new wxMessageDialog(this, _("Sorry, but there is no such ID in our database."),_("Wrong ID"), wxOK);
        dlg->ShowModal();
        delete dlg;
    }
          }
}
}
Ejemplo n.º 10
0
/*
 * Obtain data directory of server if necessary. if this has already been
 * queried to server, return existing value.
 */
char *
get_data_directory(char *conninfo)
{
	PGconn	   *pgconn;
	PGresult   *pgresult = NULL;
	int			rows;

	/* Return existing value if any */
	if (data_directory)
		return data_directory;

	/* No existing value, so query server */
	rows = 0;
	pgconn = connect_to_db(conninfo);
	if (pgconn != NULL)
	{
		pgresult = PQexec(pgconn, QUERY_DATA_DIRECTORY);
		if (PQresultStatus(pgresult) == PGRES_TUPLES_OK)
			rows = PQntuples(pgresult);
	}

	if (rows != 0)
	{
		char *dir;
		dir = PQgetvalue(pgresult, 0, 0);
		if (dir != NULL)
			data_directory = strdup(dir);
	}

	/* Clean up */
	if (pgresult != NULL)
		PQclear(pgresult);
	PQfinish(pgconn);

	return data_directory;
}
Ejemplo n.º 11
0
void *db_worker(void *data)
{
	int id = *((int *) data); /* Whoa... */

	struct transaction_queue_node_t *node;
	struct db_context_t *dbc;
	char code;
	double response_time;
	struct timeval rt0, rt1;
	int local_seed;
	pid_t pid;
	pthread_t tid;
	extern unsigned int seed;
	int status;

	/* Each thread needs to seed in Linux. */
    tid = pthread_self();
    pid = getpid();
	if (seed == -1) {
		struct timeval tv;
		unsigned long junk; /* Purposely used uninitialized */

		local_seed = pid;
		gettimeofday(&tv, NULL);
		local_seed ^=  tid ^ tv.tv_sec ^ tv.tv_usec ^ junk;
	} else {
		local_seed = seed;
	}
	set_random_seed(local_seed);

	/* Open a connection to the database. */
	dbc = db_init();

	if (!exiting && connect_to_db(dbc) != OK) {
		LOG_ERROR_MESSAGE("connect_to_db() error, terminating program");
		printf("cannot connect to database(see details in error.log file, exiting...\n");
		exit(1);
	}

	while (!exiting) {
		/*
		 * I know this loop will prevent the program from exiting
		 * because of the dequeue...
		 */
		node = dequeue_transaction();
		if (node == NULL) {
			LOG_ERROR_MESSAGE("dequeue was null");
			continue;
		}

		/* Execute transaction and record the response time. */
		if (gettimeofday(&rt0, NULL) == -1) {
			perror("gettimeofday");
		}

		status =
			process_transaction(node->client_data.transaction,
								dbc, &node->client_data.transaction_data);
		if (status == ERROR) {
			LOG_ERROR_MESSAGE("process_transaction() error on %s",
							  transaction_name[
								  node->client_data.transaction]);
			/*
			 * Assume this isn't a fatal error, send the results
			 * back, and try processing the next transaction.
			 */
			while (need_reconnect_to_db(dbc))
			{
				LOG_ERROR_MESSAGE("try to reconnect to database");
				disconnect_from_db(dbc);

				if (connect_to_db(dbc) != OK)
				{
					LOG_ERROR_MESSAGE("reconnect to database error, try again after sleep 5 seconds");
					sleep(5);
				}
			}
		}

		if (status == OK) {
			code = 'C';
		} else if (status == STATUS_ROLLBACK) {
			code = 'R';
		} else if (status == ERROR) {
			code = 'E';
		}

		if (gettimeofday(&rt1, NULL) == -1) {
			perror("gettimeofday");
		}

		response_time = difftimeval(rt1, rt0);
		log_transaction_mix(node->client_data.transaction, code, response_time,
							mode_altered > 0 ? node->termworker_id : node->term_id);
		enqueue_terminal(node->termworker_id, node->term_id);

		/* Keep track of how many transactions this thread has done. */
		++worker_count[id];

		/* Keep track of then the last transaction was execute. */
		time(&last_txn[id]);
	}

	/* Disconnect from the database. */
	disconnect_from_db(dbc);

	free(dbc);

	sem_wait(&db_worker_count);

	return NULL;        /* keep compiler quiet */
}
Ejemplo n.º 12
0
Archivo: menus.c Proyecto: aspacsa/vlp
void set_new_db_conn(const char *curr_path) {
  const int n_fields = 5;
  const int width = 20;
  const int starty = 4;
  const int startx = 20;
  FIELD *field[n_fields];
  FORM *my_form;
  char *screen_title = "New DB Connection";
  
  initscr();
  curs_set(1);
  cbreak();
  clear();
  noecho();
  keypad(stdscr, TRUE);

  for (size_t i = 0; i < n_fields - 1; ++i) {
    field[i] = new_field(1, width, starty + i * 2, startx, 0, 0);
  }
  field[n_fields - 1] = NULL;

  set_field_back(field[0], A_UNDERLINE);
  field_opts_off(field[0], O_AUTOSKIP);
  set_field_back(field[1], A_UNDERLINE);
  field_opts_off(field[1], O_AUTOSKIP);
  set_field_back(field[2], A_UNDERLINE);
  field_opts_off(field[2], O_AUTOSKIP);
  field_opts_off(field[2], O_PUBLIC);
  set_field_back(field[3], A_UNDERLINE);
  field_opts_off(field[3], O_AUTOSKIP);

  my_form = new_form(field);
  post_form(my_form);
  refresh();

  mvprintw(0, 0, menu_path(curr_path, screen_title));
  mvprintw(4, 10, "Server:   ");
  mvprintw(6, 10, "User:     "******"Password: "******"DB:       ");
  mvprintw(14, 10, "(F2) = Save and Exit | (F4) = Exit without saving");
  move(4, 20);
  refresh();

  int ch;
  do {
    ch = getch();
    switch(ch) {
      case KEY_DOWN:
        form_driver(my_form, REQ_NEXT_FIELD);
        form_driver(my_form, REQ_END_LINE);
        break;
      case KEY_UP:
        form_driver(my_form, REQ_PREV_FIELD);
        form_driver(my_form, REQ_END_LINE);
        break;
      case KEY_LEFT:
        form_driver(my_form, REQ_LEFT_CHAR);
        break;
      case KEY_RIGHT:
        form_driver(my_form, REQ_RIGHT_CHAR);
        break;
      case ENTER:
        form_driver(my_form, REQ_NEXT_FIELD);
        form_driver(my_form, REQ_END_LINE);
        break;
      case KEY_BACKSPACE:
        form_driver(my_form, REQ_PREV_CHAR);
        form_driver(my_form, REQ_DEL_CHAR);
        break;
      case DEL:
        form_driver(my_form, REQ_DEL_CHAR);
        break;
      default:
        if (is_space(ch) == 0)
          form_driver(my_form, ch);
        break;
    } 
  } while( (ch != KEY_F(2)) && (ch != KEY_F(4)) ); 
  if (ch == KEY_F(2)) {
    char *server = field_buffer(field[0], 0);
    char *admin = field_buffer(field[1], 0);
    char *pass = field_buffer(field[2], 0);
    char *db = field_buffer(field[3], 0);

    strcpy(server, compress_str(server));
    strcpy(admin, compress_str(admin));
    strcpy(pass, compress_str(pass));
    strcpy(db, compress_str(db));
    
    int result = set_db_cnf(server, admin, pass, db);

    mvprintw(16, 10, "**Warning: The system will apply changes to the configuration now.");
    close_db();
    init_db();
    mvprintw(18, 10, "Press any key to continue...");
    ch = getch();
    if (connect_to_db() == 1) {
      mvprintw(20, 10, "[!] Unable to connect to database with new configuration.");
    } else {
      mvprintw(20, 10, "[!] Connection successful.");
    }
    ch = getch();
  }
  unpost_form(my_form);
  free_form(my_form);
  for (size_t i = 0; i < n_fields -1; ++i) {
    free_field(field[i]);
  }
  endwin();
  return;
}
Ejemplo n.º 13
0
struct plugin *helper_get_example_plugin(void)
{
  struct plugin *p = MALLOC(struct plugin);
  struct function *f = MALLOC(struct function);

  if (!p || !f)
    LOG_ERROR("[test] Failed to alloc mem for example plugin.\n");

  p->key = (string) {.str = "0123456789ABCDEF",
                     .length = sizeof("0123456789ABCDEF") - 1};
  p->name = (string) {.str = "plugin name",
                      .length = sizeof("plugin name") - 1};
  p->description = (string) {.str = "plugin desc",
                             .length = sizeof("plugin desc") - 1};
  p->license = (string) {.str = "plugin license",
                         .length = sizeof("plugin license") - 1};
  p->author = (string) {.str = "plugin author",
                        .length = sizeof("plugin author") - 1};

  p->callid = 0;

  f->name = (string) {.str = "function name",
                      .length = sizeof("function name") - 1};
  f->description = (string) {.str = "function desc",
                             .length = sizeof("function desc") - 1};
  f->args[0] = (string) {.str = "arg 1",
                         .length = sizeof("arg 1") - 1};
  f->args[1] = (string) {.str = "arg 2",
                         .length = sizeof("arg 2") - 1};

  p->function = f;
  return p;
}

void helper_free_plugin(struct plugin *p)
{
  FREE(p->function);
  FREE(p);
}


/* Builds a register call and executes handle_register in order
 * to register the plugin. */
void helper_register_plugin(struct plugin *p)
{
  connection_request_event_info info;
  struct message_request *register_request;
  array *meta, *functions, *func1, *args;
  struct api_error err = ERROR_INIT;

  info.request.msgid = 1;
  register_request = &info.request;
  assert_non_null(register_request);

  info.api_error = err;

  info.con = CALLOC(1, struct connection);
  info.con->closed = true;
  info.con->msgid = 1;
  info.con->id = (uint64_t) randommod(281474976710656LL);

  assert_non_null(info.con);

  strlcpy(info.con->cc.pluginkeystring, p->key.str, p->key.length+1);

  connect_to_db();
  assert_int_equal(0, connection_init());

  /* first level arrays:
   *
   * [meta] args->obj[0]
   * [functions] args->obj[1]
   */
  register_request->params.size = 2;
  register_request->params.obj = CALLOC(2, struct message_object);
  register_request->params.obj[0].type = OBJECT_TYPE_ARRAY;
  register_request->params.obj[1].type = OBJECT_TYPE_ARRAY;

  /* meta array:
   *
   * [name]
   * [desciption]
   * [author]
   * [license]
   */
  meta = &register_request->params.obj[0].data.params;
  meta->size = 4;
  meta->obj = CALLOC(meta->size, struct message_object);
  meta->obj[0].type = OBJECT_TYPE_STR;
  meta->obj[0].data.string = cstring_copy_string(p->name.str);
  meta->obj[1].type = OBJECT_TYPE_STR;
  meta->obj[1].data.string = cstring_copy_string(p->description.str);
  meta->obj[2].type = OBJECT_TYPE_STR;
  meta->obj[2].data.string = cstring_copy_string(p->author.str);
  meta->obj[3].type = OBJECT_TYPE_STR;
  meta->obj[3].data.string = cstring_copy_string(p->license.str);

  functions = &register_request->params.obj[1].data.params;
  functions->size = 1;
  functions->obj = CALLOC(functions->size, struct message_object);
  functions->obj[0].type = OBJECT_TYPE_ARRAY;

  func1 = &functions->obj[0].data.params;
  func1->size = 3;
  func1->obj = CALLOC(3, struct message_object);
  func1->obj[0].type = OBJECT_TYPE_STR;
  func1->obj[0].data.string = cstring_copy_string(p->function->name.str);
  func1->obj[1].type = OBJECT_TYPE_STR;
  func1->obj[1].data.string = cstring_copy_string(p->function->description.str);
  func1->obj[2].type = OBJECT_TYPE_ARRAY;

  /* function arguments */
  args = &func1->obj[2].data.params;
  args->size = 2;
  args->obj = CALLOC(2, struct message_object);
  args->obj[0].type = OBJECT_TYPE_STR;
  args->obj[0].data.string = cstring_copy_string(p->function->args[0].str);
  args->obj[1].type = OBJECT_TYPE_STR;
  args->obj[1].data.string = cstring_copy_string(p->function->args[1].str);

  /* before running function, it must be registered successfully */
  info.api_error.isset = false;
  expect_check(__wrap_crypto_write, &deserialized,
                validate_register_response,
                NULL);

  info.con->refcount++;

  connection_hashmap_put(info.con->id, info.con);
  pluginkeys_hashmap_put(info.con->cc.pluginkeystring, info.con->id);

  assert_int_equal(0, handle_register(info.con->id, &info.request,
      info.con->cc.pluginkeystring, &info.api_error));
  assert_false(info.api_error.isset);

  //hashmap_put(uint64_t, ptr_t)(connections, info.con->id, info.con);
  free_params(register_request->params);
  //FREE(args->obj);
  //FREE(func1->obj);
  //FREE(functions->obj);
  //FREE(meta->obj);
  //FREE(register_request->params.obj);
}

/* Builds a run request */
void helper_build_run_request(struct message_request *rr,
    struct plugin *plugin,
    message_object_type metaarraytype,
    size_t metasize,
    message_object_type metaclientidtype,
    message_object_type metacallidtype,
    message_object_type functionnametype,
    message_object_type argstype
)
{
  array argsarray = ARRAY_INIT;
  array *meta;

  rr->msgid = 1;

  rr->params.size = 3;
  rr->params.obj = CALLOC(rr->params.size, struct message_object);
  rr->params.obj[0].type = metaarraytype;

  meta = &rr->params.obj[0].data.params;
  meta->size = metasize;
  meta->obj = CALLOC(meta->size, struct message_object);
  meta->obj[0].type = metaclientidtype;
  meta->obj[0].data.string = cstring_copy_string(plugin->key.str);
  meta->obj[1].type = metacallidtype;

  rr->params.obj[1].type = functionnametype;
  rr->params.obj[1].data.string = cstring_copy_string(plugin->function->name.str);

  argsarray.size = 2;
  argsarray.obj = CALLOC(argsarray.size, struct message_object);
  argsarray.obj[0].type = OBJECT_TYPE_STR; /* first argument */
  argsarray.obj[0].data.string = cstring_copy_string(plugin->function->args[0].str);
  argsarray.obj[1].type = OBJECT_TYPE_STR; /* second argument */
  argsarray.obj[1].data.string = cstring_copy_string(plugin->function->args[1].str);

  rr->params.obj[2].type = argstype;
  rr->params.obj[2].data.params = argsarray;
}


void helper_build_result_request(struct message_request *rr,
    struct plugin *plugin,
    message_object_type metaarraytype,
    size_t metasize,
    message_object_type metacallidtype,
    message_object_type argstype)
{
  array argsarray = ARRAY_INIT;
  array *meta;

  rr->msgid = 1;

  rr->params.size = 2;
  rr->params.obj = CALLOC(rr->params.size, struct message_object);
  rr->params.obj[0].type = metaarraytype;
  meta = &rr->params.obj[0].data.params;
  meta->size = metasize;
  meta->obj = CALLOC(meta->size, struct message_object);
  meta->obj[0].type = metacallidtype;
  meta->obj[0].data.uinteger = plugin->callid;

  argsarray.size = 2;
  argsarray.obj = CALLOC(argsarray.size, struct message_object);
  argsarray.obj[0].type = OBJECT_TYPE_STR; /* first argument */
  argsarray.obj[0].data.string = cstring_copy_string(plugin->function->args[0].str);
  argsarray.obj[1].type = OBJECT_TYPE_STR; /* second argument */
  argsarray.obj[1].data.string = cstring_copy_string(plugin->function->args[1].str);

  rr->params.obj[1].type = argstype;
  rr->params.obj[1].data.params = argsarray;
}

void helper_request_set_callid(struct message_request *rr,
  message_object_type callidtype)
{
  array *meta = &rr->params.obj[0].data.params;

  meta->obj[0].type = callidtype;
}

void helper_request_set_meta_size(struct message_request *rr,
  message_object_type metatype, uint64_t metasize)
{
  rr->params.obj[0].type = metatype;
  rr->params.obj[0].data.params.size = metasize;
}

void helper_request_set_args_size(struct message_request *rr,
  message_object_type argstype, uint64_t argssize)
{
  rr->params.obj[1].type = argstype;
  rr->params.obj[1].data.params.size = argssize;
}

void helper_request_set_function_name(struct message_request *rr,
  message_object_type nametype, char *name)
{
  free_string(rr->params.obj[1].data.string);
  rr->params.obj[1].type = nametype;
  rr->params.obj[1].data.string = cstring_copy_string(name);
}

void helper_request_set_pluginkey_type(struct message_request *rr,
  message_object_type pluginkeytype, char *pluginkey)
{
  array *meta = &rr->params.obj[0].data.params;

  free_string(meta->obj[0].data.string);
  meta->obj[0].data.string = cstring_copy_string(pluginkey);
  meta->obj[0].type = pluginkeytype;
}
Ejemplo n.º 14
0
Archivo: michal.c Proyecto: Bakus/gammu
void execute_one_action(unsigned char *buf3)
{
	char buf4[5000];
	char *b;
	int num, num2;
	char *args[10];
	char buffe[10][200];

	buf4[0] = 0;
	b = buf3;
	num = 0;
	buffe[0][0] = 0;
	while (b[0] != 0) {
		if (strstr(buf3, "daemon_run_program") != NULL) {
			if (b[0] == '<') {
				if (num != 0)
					args[num - 1] = buffe[num];
				num++;
				buffe[num][0] = 0;
				b++;
			} else {
				if (strstr(b, "daemon_column") == b) {
					b += 13;
					num2 = atoi(b);
					while (b[0] >= '0' && b[0] <= '9')
						b++;
					strcat(buffe[num], Row3[num2 - 1]);
				} else if (strstr(b, "daemon2_column") == b) {
					b += 14;
					num2 = atoi(b);
					while (b[0] >= '0' && b[0] <= '9')
						b++;
					strcat(buffe[num], Row4[num2 - 1]);
				} else {
					buffe[num][strlen(buffe[num]) + 1] = 0;
					buffe[num][strlen(buffe[num])] = b[0];
					b++;
				}
			}
		} else {
			if (strstr(b, "daemon_column") == b) {
				b += 13;
				num2 = atoi(b);
				while (b[0] >= '0' && b[0] <= '9')
					b++;
				strcat(buf4, Row3[num2 - 1]);
			} else if (strstr(b, "daemon2_column") == b) {
				b += 14;
				num2 = atoi(b);
				while (b[0] >= '0' && b[0] <= '9')
					b++;
				strcat(buf4, Row4[num2 - 1]);
			} else {
				buf4[strlen(buf4) + 1] = 0;
				buf4[strlen(buf4)] = b[0];
			}
		}
	}
	if (strstr(buf3, "daemon_run_program") != NULL) {
		args[num - 1] = NULL;
//              for (i=0;i<num-1;i++) {
//                      printf("arg %i \"%s\"\n",i,args[i]);
//              }
//              if (num >= 0) {
#ifdef WIN32
# ifdef SPAWNV_ARGUMENT_IS_CONST
		spawnv(_P_NOWAIT, buffe[1], (const char * const*)args);
# else
		spawnv(_P_NOWAIT, buffe[1], (char * const*)args);
#endif
#else
		if (fork() == 0)
			execve(buffe[1], args, NULL);
#endif
//              }
	} else {
		connect_to_db(Row2[11], Row2[12], Row2[14], Row2[13]);	//user,pass,pc,db
		mysql_query(&DB2, buf4);
	}
}
Ejemplo n.º 15
0
void *db_worker(void *data)
{
        int id = *((int *) data); /* Whoa... */
#ifndef STANDALONE
        int length;
#endif /* NOT STANDALONE */
        struct transaction_queue_node_t *node;
        struct db_context_t dbc;
#ifdef STANDALONE
        struct timeval rt0, rt1;
        double response_time;
#endif /* STANDALONE */

        /* Open a connection to the database. */
#ifdef ODBC
        printf("connect to ODBC server with parameters: DSN: |%s| user: |%s| pass: |%s|\n", sname, dbt2_user, dbt2_pass);
        db_init(sname, dbt2_user, dbt2_pass);
#endif /* ODBC */
#ifdef LIBPQ
        db_init(DB_NAME, sname, postmaster_port);
#endif /* LIBPQ */

#ifdef LIBMYSQL
       printf("connect to mysql server with parameters: db_name: |%s| host: |%s| user: |%s| pass: |%s| port: |%s| socket: |%s|\n", sname, dbt2_mysql_host, dbt2_user, dbt2_pass, dbt2_mysql_port, dbt2_mysql_socket);
       db_init(sname, dbt2_mysql_host , dbt2_user, dbt2_pass, dbt2_mysql_port, dbt2_mysql_socket);
#endif /* LIBMYSQL */


        if (!exiting && connect_to_db(&dbc) != OK) {
                LOG_ERROR_MESSAGE("connect_to_db() error, terminating program");
                printf("cannot connect to database(see details in error.log file, exiting...\n");
                exit(1);
        }

        while (!exiting) {
                /*
                 * I know this loop will prevent the program from exiting
                 * because of the dequeue...
                 */
                node = dequeue_transaction();
                if (node == NULL) {
                        LOG_ERROR_MESSAGE("dequeue was null");
                        continue;
                }
#ifdef STANDALONE
                if (gettimeofday(&rt0, NULL) == -1) {
                        perror("gettimeofday");
                }
#endif /* STANDALONE */
                node->client_data.status =
                        process_transaction(node->client_data.transaction,
                        &dbc, &node->client_data.transaction_data);
                if (node->client_data.status == ERROR) {
                        LOG_ERROR_MESSAGE("process_transaction() error on %s",
                                transaction_name[
                                node->client_data.transaction]);
                        /*
                         * Assume this isn't a fatal error, send the results
                         * back, and try processing the next transaction.
                         */
                }
                else
                {
                  if (node->client_data.status == ERROR_FATAL) 
                  {
                        LOG_ERROR_MESSAGE("process_transaction() fatal error on %s",
                                transaction_name[
                                node->client_data.transaction]);
                        LOG_ERROR_MESSAGE("stopping db_thread");
                        exiting=1;
                  }
                }

#ifdef STANDALONE
                if (gettimeofday(&rt1, NULL) == -1) {
                        perror("gettimeofday");
                }
                response_time = difftimeval(rt1, rt0);
                pthread_mutex_lock(&mutex_mix_log);
                fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
                transaction_short_name[node->client_data.transaction],
                        response_time, (int) pthread_self());
                        fflush(log_mix);
                pthread_mutex_unlock(&mutex_mix_log);
#endif /* STANDALONE */

#ifndef STANDALONE
                length = send_transaction_data(node->s, &node->client_data);
                if (length == ERROR) {
                        LOG_ERROR_MESSAGE("send_transaction_data() error");
                        /*
                         * Assume this isn't a fatal error and try processing
                         * the next transaction.
                         */
                }
#endif /* NOT STANDALONE */
                pthread_mutex_lock(&mutex_transaction_counter[REQ_EXECUTING][
                        node->client_data.transaction]);
                --transaction_counter[REQ_EXECUTING][
                        node->client_data.transaction];
                pthread_mutex_unlock(&mutex_transaction_counter[REQ_EXECUTING][
                        node->client_data.transaction]);
                recycle_node(node);

                /* Keep track of how many transactions this thread has done. */
                ++worker_count[id];

                /* Keep track of then the last transaction was execute. */
                time(&last_txn[id]);
        }

        /* Disconnect from the database. */
        disconnect_from_db(&dbc);

        sem_wait(&db_worker_count);

        return NULL;        /* keep compiler quiet */
}
Ejemplo n.º 16
0
Archivo: child.c Proyecto: xiu/child
int main(int argc, char **argv)
{
    startuptime = time(NULL);

    InitMem();

    int retval,mysql_lastconn,newfd,i,lastcheck,lastcheck2,nbfd;
    struct sockaddr_storage sa;
    socklen_t salen = sizeof(sa);
    Eclient *eclient;

    indata.nextline = indata.chunkbufentry = indata.chunkbuf;

    emerg = emerg_req = 0;

    eos = raws = verbose = vv = 0;
    int daemonize = 1;
    char op = 0;
    me.retry_attempts = me.nextretry = me.connected = 0;

    struct sigaction sig, old;
    memset(&sig,0,sizeof(sig));
    sig.sa_handler = sighandler;
    sigaction(SIGHUP,&sig,&old);
#ifdef USE_FILTER
    sigaction(SIGUSR1,&sig,&old);
#endif
    sigaction(SIGUSR2,&sig,&old);
    sigaction(SIGINT,&sig,&old);
    sigaction(SIGCHLD,&sig,&old);
    sigaction(SIGPIPE,&sig,&old);

    struct rlimit rlim;
    if ((getrlimit(RLIMIT_CORE, &rlim)) == -1) {
        perror("getrlimit");
        return -1;
    }
    rlim.rlim_cur = RLIM_INFINITY;
    if ((setrlimit(RLIMIT_CORE, &rlim)) == -1) {
        perror("setrlimit");
        return -1;
    }

    /* Setting default values */

    strcpy(me.nick,"C");
    strcpy(me.name,"services.geeknode.org");
    strcpy(me.ident,"cserve");
    strcpy(me.host,"geeknode.org");
    strcpy(me.linkpass,"f00p4ss");
    strcpy(me.mysql_host,"localhost");
    strcpy(me.mysql_db,"child");
    strcpy(me.mysql_login,"child");
    strcpy(me.mysql_passwd,"childp4ss");
    strcpy(me.logfile,"child.log");
    strcpy(me.guest_prefix,"Geek");
    strcpy(me.pl_logfile,"partyline.log");
    strcpy(me.sendmail,"/usr/sbin/sendmail -t");
    strcpy(me.sendfrom,"*****@*****.**");
    strcpy(me.usercloak,".users.geeknode.org");
    bzero(me.mysql_anope_host,32);
    bzero(me.mysql_anope_db,32);
    bzero(me.mysql_anope_login,32);
    bzero(me.mysql_anope_passwd,32);
    bzero(me.bindip,32);
    me.port = 4400;
    me.maxclones = 5;
    me.nick_expire = 45;
    me.chan_expire = 60;
    me.chanperuser = 10;
    me.level_oper = 100;
    me.level_admin = 500;
    me.level_root = 900;
    me.level_owner = 1000;
    me.limittime = 5;
    me.savedb_interval = 60;
    me.listen_port = 0;
#ifdef USE_GNUTLS
    me.ssl = 0;
#endif
    me.enable_exec = 0;
    me.anonymous_global = 0;
    me.maxmsgtime = 2;
    me.maxmsgnb = 5;
    me.ignoretime = 60;
    me.maxloginatt = 3;
    me.chlev_sadmin = 20;
    me.chlev_admin = 10;
    me.chlev_op = 5;
    me.chlev_halfop = 4;
    me.chlev_voice = 3;
    me.chlev_invite = 1;
    me.chlev_nostatus = -1;
    me.chlev_akick = -2;
    me.chlev_akb = -3;
    me.anopemd5 = 0;
#ifdef USE_FILTER
    me.filter = 0;
#endif
    me.emailreg = 0;

    /* -- */

    int ladb=0,cdb=0;

    while ((op = getopt(argc,argv,"acdhv")) != EOF) {
        switch(op) {
            case 'a':
                ladb = 1;
                break;
            case 'c':
                cdb = 1;
                break;
            case 'd':
                daemonize = 0;
                break;
            case 'v':
                if (verbose)
                    vv = 1;
                else
                    verbose = 1;
                break;
            case 'h':
            default:
                usage(argv[0]);
        }
    }

    loadconf(0);
#ifdef USE_FILTER
    if (me.filter)
        loadrulefile();
#endif

    if (ladb) {
        if (!connect_to_db()) {
            printf("Cannot connect to db\n");
            child_clean();
        }

        loadalldb();
        mysql_close(&mysql);

        if (!connect_to_anope_db()) {
            printf("Cannot connect to anope db\n");
            child_clean();
        }

        printf("Loading anope database... ");
        fflush(stdout);

        loadanopedb();
        mysql_close(&mysql2);
        printf("done.\n");
        printf("Saving databases... ");
        fflush(stdout);
        savealldb();
        printf("done.\n");
        printf("Anope database converted\n");
        child_clean();
    }

    if (cdb) {
        if (!connect_to_db()) {
            printf("Cannot connect to db\n");
            child_clean();
        }

        printf("Creating databases ... ");
        fflush(stdout);
        char tmp[512];
        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_chans` (chname varchar(50) not null, founder varchar(50) not null, entrymsg blob not null, options int not null, mlock varchar(32) not null, autolimit int not null, lastseen int not null, regtime int not null, topic blob not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_chan_access` (chname varchar(50) not null, username varchar(255) not null, level int not null, automode int not null default 1, suspended int not null, uflags int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_trusts` (hostname varchar(255) not null, clones int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_users` (username varchar(50) not null, authlevel int not null, seen int not null, vhost varchar(200) not null, md5_pass varchar(32) not null, options int not null, timeout int not null, email varchar(100) not null, regtime int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_links` (master varchar(50) not null, slave varchar(50) not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_botserv_bots` (name varchar(50) not null, ident varchar(50) not null, host varchar(50) not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_botserv_chans` (chan varchar(50) not null, bot varchar(50) not null)");
        mysql_query(&mysql,tmp);

        RunHooks(HOOK_CREATEDB,NULL,NULL,NULL,NULL);

        printf(" done.\n");
        mysql_close(&mysql);
        child_clean();
    }

    if (me.listen_port) {
        if (!Bind()) {
            fprintf(stderr,"Error while binding\n");
            child_clean();
        }
        pllog("Partyline created");
    }

    retval = ConnectToServer();
    switch(retval) {
        case -1:
            fprintf(stderr,"Failed to connect to %s:%d (connection timed out)\n",me.server,me.port);
            operlog("Failed to connect to %s:%d (connection timed out)",me.server,me.port);
            child_clean();
        case 0:
            fprintf(stderr,"Failed to connect to %s:%d",me.server,me.port);
            operlog("Failed to connect to %s:%d",me.server,me.port);
            child_clean();
    }

    if (verbose) printf("Connected to server\n");

    if (!connect_to_db()) {
        fprintf(stderr,"Cannot connect to mysql\n");
        operlog("Cannot connect to mysql db");
        child_clean();
    }

    if (verbose) printf("Connected to mysql DB\n");
    loadalldb();
    mysql_close(&mysql);
    if (verbose) printf("Logging in to server\n");
    SendInitToServer();
    me.connected = 1;
    if (verbose) printf("Logged in to server\n");

    SendRaw("EOS");

    lastcheck = lastcheck2 = mysql_lastconn = time(NULL);
    if (daemonize) daemon(1,0);
    write_pid();

    nbfd = build_poll();
    struct pollfd pfdout;
    pfdout.fd = sock;
    pfdout.events = POLLOUT;
    pfdout.revents = 0;

    while(1) {
        if (outdata.writebytes > 0) {
            retval = poll(&pfdout,1,1000);
            if (retval > 0 && (pfdout.revents & POLLOUT))
                flush_sendq();
        }
        retval = poll(ufds,nbfd,1000);
        if (retval > 0) {
            for (i=0;i<nbfd;i++) {
                if (ufds[i].revents & (POLLIN | POLLPRI)) {
                    switch(i) {
                        case 0:
                            if (!ReadChunk()) {
                                if (!me.connected || !eos) break;
                                operlog("Connection reset by peer");
                                savealldb();
                                eos = me.retry_attempts = me.connected = 0;
                                me.nextretry = time(NULL)+1;
                                cleanup_reconnect();
                                close(sock);
                                break;
                            }
                            while (GetLineFromChunk())
                                ParseLine();
                            break;
                        case 1:
                            if (!me.listen_port) break;
                            newfd = accept(esock,(struct sockaddr *)&sa,&salen);
                            if (eclient_list.size+1 >= ECL_MAXSOCK) {
                                close(newfd);
                                break;
                            }
                            fcntl(newfd,F_SETFL,O_NONBLOCK);
                            eclient = AddEclient(newfd,sa,salen);
                            sendto_all_butone(eclient,"*** Connection from %s (%s)",eclient->host,eclient->addr);
                            nbfd = build_poll(); i++;
                            break;
                        default:
                            eclient = find_eclient(ufds[i].fd);
                            if (!eclient) break;
                            int oldnbfd = nbfd;
                            int old_eclient_size = eclient_list.size;
                            if (!ReadPChunk(eclient)) {
                                if (eclient->authed == 1)
                                    sendto_all_butone(eclient,"*** User %s (%s) logged out (Connection reset by peer)",eclient->nick,eclient->host);
                                else
                                    sendto_all_butone(eclient,"*** Lost connection from %s",eclient->host);
                                close(eclient->fd);
                                DeleteEclient(eclient);
                                nbfd = build_poll();
                                i--;
                                break;
                            }
                            int tmpfd = eclient->fd;
                            while (GetLineFromPChunk(tmpfd))
                                ParseEclient(eclient);
                            if (old_eclient_size > eclient_list.size)
                                nbfd = build_poll();
                            if (nbfd < oldnbfd) i -= (oldnbfd - nbfd);
                            break;
                    }
                }
            }
        }

        int timenow = time(NULL);

        if (!me.connected && timenow - me.nextretry >= 0) {
            retval = ConnectToServer();
            if (retval == -1 || retval == 0) {
                me.retry_attempts++;
                operlog("Reconnecting attempt #%d failed (%s)",me.retry_attempts,retval ? "timeout" : "error");
                if (me.retry_attempts >= MAX_RECO_ATTEMPTS) {
                    operlog("Maximum reconnection attempts reached, exiting");
                    savealldb();
                    unloadallmod();
                    CloseAllSock();
                    child_clean();
                }
                me.nextretry = timenow + RECONNECT_DELAY;
            } else {
                SendInitToServer();
                me.connected = 1;
                me.nextretry = 0;
                SendRaw("EOS");
                operlog("Reconnected");
            }
            if (me.connected) continue;
        }

        if (timenow - mysql_lastconn >= 60*me.savedb_interval) {
            savealldb();
            mysql_lastconn = timenow;
        }

        if (timenow - lastcheck >= 1) {
            CheckGuests();
            CheckLimits();
            CheckTB();
            lastcheck = timenow;
        }

        if (timenow - lastcheck2 >= 60) {
            checkexpired();
            lastcheck2 = timenow;
        }
    }

    operlog("Program shouldn't reach this piece of code, WTF ? Saving DBs and exiting.");
    savealldb();
    unloadallmod();
    CloseAllSock();
    child_clean();

    return 0;
}
Ejemplo n.º 17
0
void *terminal_worker(void *data)
{
#ifndef STANDALONE
	int length;
	int sockfd;
#endif /* NOT STANDALONE */

	struct terminal_context_t *tc;
	struct client_transaction_t client_data;
	double threshold;
	int keying_time;
	struct timespec thinking_time, rem;
	int mean_think_time; /* In milliseconds. */
	struct timeval rt0, rt1;
	double response_time;
	extern int errno;
	int rc;
	int local_seed;

#ifdef STANDALONE
	struct db_context_t dbc;
	struct transaction_queue_node_t *node =
			(struct transaction_queue_node_t *)
			malloc(sizeof(struct transaction_queue_node_t));
	extern char sname[32];
	extern int exiting;
#ifdef LIBPQ
	extern char postmaster_port[32];
#endif /* LIBPQ */

#ifdef LIBMYSQL
	extern char dbt2_mysql_port[32];
#endif /* LIBMYSQL */

#endif /* STANDALONE */

	tc = (struct terminal_context_t *) data;
	/* Each thread needs to seed in Linux. */
	if (seed == -1) {
		struct timeval tv;
		unsigned long junk; /* Purposely used uninitialized */

		gettimeofday(&tv, NULL);
		local_seed = getpid() ^ (int) pthread_self() ^ tv.tv_sec ^
				tv.tv_usec ^ junk;
	} else {
		local_seed = seed;
	}
	printf("seed: %u\n", local_seed);
	fflush(stdout);
	srand(local_seed);

#ifdef STANDALONE
#ifdef ODBC
	db_init(sname, DB_USER, DB_PASS);
#endif /* ODBC */
#ifdef LIBPQ
	db_init(DB_NAME, sname, postmaster_port);
#endif /* LIBPQ */
#ifdef LIBMYSQL
	printf("CONNECTED TO DB |%s| |%s| |%s|\n", DB_NAME, sname, dbt2_mysql_port);
	db_init(sname, "", dbt2_mysql_port);
#endif /* LIBMYSQL */

	if (!exiting && connect_to_db(&dbc) != OK) {
		LOG_ERROR_MESSAGE("db_connect() error, terminating program");
		printf("cannot connect to database, exiting...\n");
		exit(1);
	}
#else
	/* Connect to the client program. */
	sockfd = connect_to_client(hostname, client_port);
	if (sockfd < 1) {
		LOG_ERROR_MESSAGE( "connect_to_client() failed, thread exiting...");
		printf("connect_to_client() failed, thread exiting...");
		pthread_exit(NULL);
	}
#endif /* STANDALONE */

	do {
		if (mode_altered == 1) {
			/*
			 * Determine w_id and d_id for the client per
			 * transaction.
			 */
			tc->w_id = w_id_min + get_random(w_id_max - w_id_min + 1);
			tc->d_id = get_random(table_cardinality.districts) + 1;
		}

		/*
		 * Determine which transaction to execute, minimum keying time,
		 * and mean think time.
		 */
		threshold = get_percentage();
		if (threshold < transaction_mix.new_order_threshold) {
			client_data.transaction = NEW_ORDER;
			keying_time = key_time.new_order;
			mean_think_time = think_time.new_order;
		} else if (transaction_mix.payment_actual != 0 &&
			threshold < transaction_mix.payment_threshold) {
			client_data.transaction = PAYMENT;
			keying_time = key_time.payment;
			mean_think_time = think_time.payment;
		} else if (transaction_mix.order_status_actual != 0 &&
			threshold < transaction_mix.order_status_threshold) {
			client_data.transaction = ORDER_STATUS;
			keying_time = key_time.order_status;
			mean_think_time = think_time.order_status;
		} else if (transaction_mix.delivery_actual != 0 &&
			threshold < transaction_mix.delivery_threshold) {
			client_data.transaction = DELIVERY;
			keying_time = key_time.delivery;
			mean_think_time = think_time.delivery;
		} else {
			client_data.transaction = STOCK_LEVEL;
			keying_time = key_time.stock_level;
			mean_think_time = think_time.stock_level;
		}

#ifdef DEBUG
		printf("executing transaction %c\n", 
			transaction_short_name[client_data.transaction]);
		fflush(stdout);
		LOG_ERROR_MESSAGE("executing transaction %c", 
			transaction_short_name[client_data.transaction]);
#endif /* DEBUG */

		/* Generate the input data for the transaction. */
		if (client_data.transaction != STOCK_LEVEL) {
			generate_input_data(client_data.transaction,
					&client_data.transaction_data, tc->w_id);
		} else {
			generate_input_data2(client_data.transaction,
					&client_data.transaction_data, tc->w_id, tc->d_id);
		}

		/* Keying time... */
		pthread_mutex_lock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		++terminal_state[KEYING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		if (time(NULL) < stop_time) {
			sleep(keying_time);
		} else {
			break;
		}
		pthread_mutex_lock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		--terminal_state[KEYING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[KEYING][client_data.transaction]);

		/* Note this thread is executing a transation. */
		pthread_mutex_lock(
				&mutex_terminal_state[EXECUTING][client_data.transaction]);
		++terminal_state[EXECUTING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[EXECUTING][client_data.transaction]);
		/* Execute transaction and record the response time. */
		if (gettimeofday(&rt0, NULL) == -1) {
			perror("gettimeofday");
		}
#ifdef STANDALONE
		memcpy(&node->client_data, &client_data, sizeof(client_data));
/*
		enqueue_transaction(node);
		node = get_node();
		if (node == NULL) {
			LOG_ERROR_MESSAGE("Cannot get a transaction node.\n");
		}
*/
		rc = process_transaction(node->client_data.transaction, &dbc,
				&node->client_data.transaction_data);
		if (rc == ERROR) {
			LOG_ERROR_MESSAGE("process_transaction() error on %s",
					transaction_name[node->client_data.transaction]);
		}
#else /* STANDALONE */
		length = send_transaction_data(sockfd, &client_data);
		length = receive_transaction_data(sockfd, &client_data);
		rc = client_data.status;
#endif /* STANDALONE */
		if (gettimeofday(&rt1, NULL) == -1) {
			perror("gettimeofday");
		}
		response_time = difftimeval(rt1, rt0);
		pthread_mutex_lock(&mutex_mix_log);
		if (rc == OK) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					transaction_short_name[client_data.transaction],
					response_time, (int) pthread_self());
		} else if (rc == STATUS_ROLLBACK) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					toupper(transaction_short_name[client_data.transaction]),
					response_time, (int) pthread_self());
		} else if (rc == ERROR) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					'E', response_time, (int) pthread_self());
		}
		fflush(log_mix);
		pthread_mutex_unlock(&mutex_mix_log);
		pthread_mutex_lock(&mutex_terminal_state[EXECUTING][client_data.transaction]);
		--terminal_state[EXECUTING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[EXECUTING][client_data.transaction]);

		/* Thinking time... */
		pthread_mutex_lock(&mutex_terminal_state[THINKING][client_data.transaction]);
		++terminal_state[THINKING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[THINKING][client_data.transaction]);
		if (time(NULL) < stop_time) {
			thinking_time.tv_nsec = (long) get_think_time(mean_think_time);
			thinking_time.tv_sec = (time_t) (thinking_time.tv_nsec / 1000);
			thinking_time.tv_nsec = (thinking_time.tv_nsec % 1000) * 1000000;
			while (nanosleep(&thinking_time, &rem) == -1) {
				if (errno == EINTR) {
					memcpy(&thinking_time, &rem, sizeof(struct timespec));
				} else {
					LOG_ERROR_MESSAGE(
							"sleep time invalid %d s %ls ns",
							thinking_time.tv_sec,
							thinking_time.tv_nsec);
					break;
				}
			}
		}
		pthread_mutex_lock(&mutex_terminal_state[THINKING][client_data.transaction]);
		--terminal_state[THINKING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[THINKING][client_data.transaction]);
	} while (time(NULL) < stop_time);

#ifdef STANDALONE
	/*recycle_node(node);*/
#endif /* STANDALONE */
	/* Note when each thread has exited. */
	pthread_mutex_lock(&mutex_mix_log);
	fprintf(log_mix, "%d,TERMINATED,%d\n", (int) time(NULL),
			(int) pthread_self());
	fflush(log_mix);
	pthread_mutex_unlock(&mutex_mix_log);
	return NULL; /* keep the compiler quiet */
}
Ejemplo n.º 18
0
void functional_crypto(UNUSED(void **state))
{
  unsigned char nonce[crypto_box_NONCEBYTES];
  unsigned char initiatenonce[crypto_box_NONCEBYTES];
  unsigned char hellopacket[192] = {0};
  unsigned char initiatepacket[256] = {0};
  unsigned char messagepacket[120];
  unsigned char messagepacketout[120] = {0};
  unsigned char allzeroboxed[96] = {0};
  unsigned char initiatebox[160] = {0};
  unsigned char pubkeybox[96] = {0};
  unsigned char lengthbox[40] = {0};
  uint64_t plaintextlen;
  uint64_t readlen;
  outputstream write;

  connect_to_db();

  wrap_crypto_write = false;

  assert_int_equal(0, filesystem_load(".keys/server-long-term.pub",
      serverlongtermpk, sizeof serverlongtermpk));

  cc.nonce = (uint64_t) randommod(281474976710656LL);

  if (!ISODD(cc.nonce)) {
    cc.nonce++;
  }

  cc.receivednonce = 0;
  cc.state = TUNNEL_INITIAL;

  memcpy(nonce, "splonebox-client", 16);
  uint64_pack(nonce + 16, cc.nonce);

  /* pack hello packet */
  memcpy(hellopacket, "oqQN2kaH", 8);
  /* pack compressed nonce */
  memcpy(hellopacket + 104, nonce + 16, 8);

  /* generate client ephemeral keys */
  if (crypto_box_keypair(clientlongtermpk, clientlongtermsk) != 0)
    return;
  /* generate client ephemeral keys */
  if (crypto_box_keypair(clientshorttermpk, clientshorttermsk) != 0)
    return;

  memcpy(hellopacket + 8, clientshorttermpk, 32);

  assert_int_equal(0, crypto_box(allzeroboxed, allzeroboxed, 96, nonce,
      serverlongtermpk, clientshorttermsk));

  memcpy(hellopacket + 112, allzeroboxed + 16, 80);

  crypto_init();

  /* positiv test */
  assert_int_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));

  /* wrong identifier */
  memcpy(hellopacket, "deadbeef", 8);
  assert_int_not_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));
  memcpy(hellopacket, "oqQN2kaH", 8);

  /* wrong nonce */
  cc.receivednonce = cc.nonce + 1;
  assert_int_not_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));
  cc.receivednonce = 0;

  /* wrong pubkey */
  memset(hellopacket + 8, '0', 32);
  assert_int_not_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));
  memcpy(hellopacket + 8, clientshorttermpk, 32);

  assert_int_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));

  /* crypto_recv_initiate() test */

  /* pack initiate packet */
  memcpy(initiatepacket, "oqQN2kaI", 8);
  memcpy(initiatepacket + 8, cookie, 96);
  /* pack compressed nonce */
  memcpy(initiatepacket + 104, nonce + 16, 8);

  memcpy(initiatebox + 32, clientlongtermpk, 32);
  randombytes(initiatebox + 64, 16);
  memcpy(initiatenonce, "splonePV", 8);
  memcpy(initiatenonce + 8, initiatebox + 64, 16);

  memcpy(pubkeybox + 32, clientshorttermpk, 32);
  memcpy(pubkeybox + 64, servershorttermpk, 32);

  assert_int_equal(0, crypto_box(pubkeybox, pubkeybox, 96, initiatenonce,
      serverlongtermpk, clientlongtermsk));

  memcpy(initiatebox + 80, pubkeybox + 16, 80);

  assert_int_equal(0, crypto_box(initiatebox, initiatebox, 160, nonce,
      servershorttermpk, clientshorttermsk));

  memcpy(initiatepacket + 112, initiatebox + 16, 144);

  /* without valid certificate */
  assert_int_not_equal(0, crypto_recv_initiate(&cc, initiatepacket));

  /* all plugins are allowed to connect */
  db_authorized_set_whitelist_all();
  assert_int_equal(0, crypto_recv_initiate(&cc, initiatepacket));

  /* crypto_write() test */
  assert_int_equal(0, crypto_write(&cc, (char*) allzeroboxed,
      sizeof(allzeroboxed), &write));

  /* crypto_read() test */

  /* pack message packet */
  memcpy(messagepacket, "oqQN2kaM", 8);

  /* pack compressed nonce */
  memcpy(nonce, "splonebox-client", 16);
  uint64_pack(nonce + 16, cc.nonce);
  memcpy(messagepacket + 8, nonce + 16, 8);

  uint64_pack(lengthbox + 32, 120);

  assert_int_equal(0, crypto_box(lengthbox, lengthbox, 40, nonce,
      servershorttermpk, clientshorttermsk));

  memcpy(messagepacket + 16, lengthbox + 16, 24);

  uint64_pack(nonce + 16, cc.nonce + 2);

  memset(allzeroboxed, 0, 96);
  assert_int_equal(0, crypto_box_afternm(allzeroboxed, allzeroboxed, 96, nonce,
      cc.clientshortservershort));

  memcpy(messagepacket + 40, allzeroboxed + 16, 80);

  assert_int_equal(0, crypto_verify_header(&cc, messagepacket, &readlen));

  assert_int_equal(0, crypto_read(&cc, messagepacket, (char*)messagepacketout,
      readlen, &plaintextlen));

  db_close();
}
Ejemplo n.º 19
0
/*
 * Get database info via the above QUERY_STAT_DB info.
 * Returns rate info on the various statistics by comparing current
 * values with previous values.
 */
void
get_database_info(struct db_info *db_info, char *conninfo)
{
	struct timeval thistime;
	double		timediff;
	int			i;
	int			rows;
	PGconn	   *pgconn;
	PGresult   *pgresult = NULL;
	struct db_info cur_info;
	static struct timeval lasttime;
	static struct db_info last_db_info;

	/* calculate the time difference since our last check */
	gettimeofday(&thistime, 0);
	if (lasttime.tv_sec)
		timediff = ((thistime.tv_sec - lasttime.tv_sec) +
					(thistime.tv_usec - lasttime.tv_usec) * 1e-6);
	else
		timediff = 0;

	lasttime = thistime;

	rows = 0;
	pgconn = connect_to_db(conninfo);
	if (pgconn != NULL)
	{
		pgresult = PQexec(pgconn, QUERY_STAT_DB);
		if (PQresultStatus(pgresult) == PGRES_TUPLES_OK)
			rows = PQntuples(pgresult);

	}
	if (rows == 0)
	{
		/* Database probably stopped, clear current and last */
		memset(&last_db_info, 0, sizeof(last_db_info));
	}
	memset(&cur_info, 0, sizeof(cur_info));
	for (i = 0; i < rows; i++)
	{
		PQgetvalue(pgresult, i, 2);
		/* Count all databases, even with no active backends */
		cur_info.numDb++;
		cur_info.numXact += atoi(PQgetvalue(pgresult, i, 3));
		cur_info.numRollback += atoi(PQgetvalue(pgresult, i, 4));
		cur_info.numBlockRead += atoi(PQgetvalue(pgresult, i, 5));
		cur_info.numBlockHit += atoi(PQgetvalue(pgresult, i, 6));
		cur_info.numTupleFetched += atoi(PQgetvalue(pgresult, i, 8));
		cur_info.numTupleAltered += atoi(PQgetvalue(pgresult, i, 9)) +
			atoi(PQgetvalue(pgresult, i, 10)) +
			atoi(PQgetvalue(pgresult, i, 11));
		cur_info.numConflict += atoi(PQgetvalue(pgresult, i, 12));
	}
	if (pgresult != NULL)
		PQclear(pgresult);
	PQfinish(pgconn);
	if (timediff <= 0)
	{
		last_db_info = cur_info;
		memset(db_info, 0, sizeof(*db_info));
		return;
	}

	/* Compute the rate information */
	db_info->numDb = cur_info.numDb;
	db_info->numXact = (double)(cur_info.numXact - last_db_info.numXact) / timediff;
	db_info->numRollback = (double)(cur_info.numRollback - last_db_info.numRollback) / timediff;
	db_info->numBlockRead = (double)(cur_info.numBlockRead - last_db_info.numBlockRead) / timediff;
	db_info->numBlockHit = (double)(cur_info.numBlockHit - last_db_info.numBlockHit) / timediff;
	db_info->numTupleFetched = (double)(cur_info.numTupleFetched - last_db_info.numTupleFetched) / timediff;
	db_info->numTupleAltered = (double)(cur_info.numTupleAltered - last_db_info.numTupleAltered) / timediff;
	db_info->numConflict = (double)(cur_info.numConflict - last_db_info.numConflict) / timediff;
	last_db_info = cur_info;
}
Ejemplo n.º 20
0
kitchenFrame::kitchenFrame(wxWindow* parent,wxWindowID id)
{
    vers << AutoVersion::MAJOR << _T(".") << AutoVersion::MINOR << _T(".") << AutoVersion::BUILD;
    readSet();
    //(*Initialize(kitchenFrame)
    wxMenuItem* MenuItem2;
    wxMenuItem* MenuItem1;
    wxFlexGridSizer* FlexGridSizer8;
    wxGridSizer* GridSizer1;
    wxFlexGridSizer* FlexGridSizer1;
    wxFlexGridSizer* FlexGridSizer2;
    wxMenu* Menu1;
    wxGridSizer* GridSizer2;
    wxFlexGridSizer* FlexGridSizer7;
    wxFlexGridSizer* FlexGridSizer4;
    wxFlexGridSizer* FlexGridSizer6;
    wxFlexGridSizer* FlexGridSizer3;
    wxBoxSizer* BoxSizer1;
    wxMenuBar* MenuBar1;
    wxMenu* Menu2;
    wxFlexGridSizer* FlexGridSizer5;

    Create(parent, id, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE, _T("id"));
    GridSizer1 = new wxGridSizer(1, 1, 0, 0);
    Notebook1 = new wxNotebook(this, ID_NOTEBOOK1, wxDefaultPosition, wxDefaultSize, 0, _T("ID_NOTEBOOK1"));
    Panel1 = new wxPanel(Notebook1, ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL1"));
    GridSizer2 = new wxGridSizer(0, 1, 0, 0);
    FlexGridSizer1 = new wxFlexGridSizer(1, 4, 0, 0);
    FlexGridSizer4 = new wxFlexGridSizer(2, 2, 0, 0);
    FlexGridSizer2 = new wxFlexGridSizer(0, 3, 0, 0);
    StaticText1 = new wxStaticText(Panel1, ID_STATICTEXT1, _("Pending items:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT1"));
    wxFont StaticText1Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    StaticText1->SetFont(StaticText1Font);
    FlexGridSizer2->Add(StaticText1, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    Button5 = new wxButton(Panel1, ID_BUTTON5, _("Refresh"), wxDefaultPosition, wxSize(90,50), 0, wxDefaultValidator, _T("ID_BUTTON5"));
    wxFont Button5Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button5->SetFont(Button5Font);
    FlexGridSizer2->Add(Button5, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer4->Add(FlexGridSizer2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    BoxSizer1 = new wxBoxSizer(wxHORIZONTAL);
    ToggleButton1 = new wxToggleButton(Panel1, ID_TOGGLEBUTTON1, _("Qty"), wxDefaultPosition, wxSize(80,50), 0, wxDefaultValidator, _T("ID_TOGGLEBUTTON1"));
    ToggleButton1->SetValue(true);
    wxFont ToggleButton1Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    ToggleButton1->SetFont(ToggleButton1Font);
    BoxSizer1->Add(ToggleButton1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    ToggleButton2 = new wxToggleButton(Panel1, ID_TOGGLEBUTTON2, _("Time"), wxDefaultPosition, wxSize(80,50), 0, wxDefaultValidator, _T("ID_TOGGLEBUTTON2"));
    wxFont ToggleButton2Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    ToggleButton2->SetFont(ToggleButton2Font);
    BoxSizer1->Add(ToggleButton2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer4->Add(BoxSizer1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    ListBox2 = new wxSimpleHtmlListBox(Panel1, ID_HTMLLISTBOX1, wxDefaultPosition, wxSize(250,555), 0, 0, wxSUNKEN_BORDER, wxDefaultValidator, _T("ID_HTMLLISTBOX1"));
    FlexGridSizer4->Add(ListBox2, 1, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    FlexGridSizer7 = new wxFlexGridSizer(30, 1, 0, 0);
    ListBox3 = new wxSimpleHtmlListBox(Panel1, ID_HTMLLISTBOX2, wxDefaultPosition, wxSize(250,435), 0, 0, wxSUNKEN_BORDER, wxDefaultValidator, _T("ID_HTMLLISTBOX2"));
    FlexGridSizer7->Add(ListBox3, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    Button3 = new wxButton(Panel1, ID_BUTTON3, _("UP"), wxDefaultPosition, wxSize(80,50), 0, wxDefaultValidator, _T("ID_BUTTON3"));
    wxFont Button3Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button3->SetFont(Button3Font);
    FlexGridSizer7->Add(Button3, 1, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    Button4 = new wxButton(Panel1, ID_BUTTON4, _("DOWN"), wxDefaultPosition, wxSize(80,50), 0, wxDefaultValidator, _T("ID_BUTTON4"));
    wxFont Button4Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button4->SetFont(Button4Font);
    FlexGridSizer7->Add(Button4, 1, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer4->Add(FlexGridSizer7, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    FlexGridSizer1->Add(FlexGridSizer4, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer5 = new wxFlexGridSizer(3, 1, 0, 0);
    StaticText2 = new wxStaticText(Panel1, ID_STATICTEXT2, _("Selected items info:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2"));
    wxFont StaticText2Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    StaticText2->SetFont(StaticText2Font);
    FlexGridSizer5->Add(StaticText2, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    StaticText9 = new wxStaticText(Panel1, ID_STATICTEXT9, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT9"));
    wxFont StaticText9Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    StaticText9->SetFont(StaticText9Font);
    FlexGridSizer5->Add(StaticText9, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    ListBox4 = new wxSimpleHtmlListBox(Panel1, ID_HTMLLISTBOX3, wxDefaultPosition, wxSize(250,429), 0, 0, wxSUNKEN_BORDER, wxDefaultValidator, _T("ID_HTMLLISTBOX3"));
    FlexGridSizer5->Add(ListBox4, 1, wxLEFT|wxRIGHT|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button1 = new wxButton(Panel1, ID_BUTTON1, _("UP"), wxDefaultPosition, wxSize(80,50), 0, wxDefaultValidator, _T("ID_BUTTON1"));
    wxFont Button1Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button1->SetFont(Button1Font);
    FlexGridSizer5->Add(Button1, 1, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    Button2 = new wxButton(Panel1, ID_BUTTON2, _("DOWN"), wxDefaultPosition, wxSize(80,50), 0, wxDefaultValidator, _T("ID_BUTTON2"));
    wxFont Button2Font(14,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button2->SetFont(Button2Font);
    FlexGridSizer5->Add(Button2, 1, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer1->Add(FlexGridSizer5, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    FlexGridSizer6 = new wxFlexGridSizer(2, 1, 0, 0);
    FlexGridSizer3 = new wxFlexGridSizer(0, 3, 0, 0);
    FlexGridSizer6->Add(FlexGridSizer3, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer8 = new wxFlexGridSizer(3, 1, 0, 0);
    FlexGridSizer8->Add(20,327,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    TextCtrl1 = new wxTextCtrl(Panel1, ID_TEXTCTRL1, wxEmptyString, wxDefaultPosition, wxSize(200,130), wxTE_AUTO_SCROLL|wxTE_MULTILINE|wxTE_RICH2, wxDefaultValidator, _T("ID_TEXTCTRL1"));
    FlexGridSizer8->Add(TextCtrl1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    TextCtrl2 = new wxTextCtrl(Panel1, ID_TEXTCTRL2, wxEmptyString, wxDefaultPosition, wxSize(200,50), wxTE_AUTO_SCROLL|wxTE_MULTILINE, wxDefaultValidator, _T("ID_TEXTCTRL2"));
    FlexGridSizer8->Add(TextCtrl2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button6 = new wxButton(Panel1, ID_BUTTON6, _("Send"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON6"));
    FlexGridSizer8->Add(Button6, 1, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer6->Add(FlexGridSizer8, 1, wxALL|wxALIGN_BOTTOM|wxALIGN_CENTER_HORIZONTAL, 5);
    FlexGridSizer1->Add(FlexGridSizer6, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    GridSizer2->Add(FlexGridSizer1, 1, wxLEFT|wxRIGHT|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Panel1->SetSizer(GridSizer2);
    GridSizer2->Fit(Panel1);
    GridSizer2->SetSizeHints(Panel1);
    Notebook1->AddPage(Panel1, _("Pending items"), false);
    GridSizer1->Add(Notebook1, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    SetSizer(GridSizer1);
    MenuBar1 = new wxMenuBar();
    Menu1 = new wxMenu();
    MenuItem1 = new wxMenuItem(Menu1, idMenuQuit, _("Quit\tAlt-F4"), _("Quit the application"), wxITEM_NORMAL);
    Menu1->Append(MenuItem1);
    MenuBar1->Append(Menu1, _("&File"));
    Menu3 = new wxMenu();
    MenuItem3 = new wxMenuItem(Menu3, ID_MENUITEM1, _("General"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem3);
    MenuBar1->Append(Menu3, _("Settings"));
    Menu2 = new wxMenu();
    MenuItem2 = new wxMenuItem(Menu2, idMenuAbout, _("About\tF1"), _("Show info about this application"), wxITEM_NORMAL);
    Menu2->Append(MenuItem2);
    MenuBar1->Append(Menu2, _("Help"));
    SetMenuBar(MenuBar1);
    StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1"));
    int __wxStatusBarWidths_1[2] = { -10, -10 };
    int __wxStatusBarStyles_1[2] = { wxSB_NORMAL, wxSB_NORMAL };
    StatusBar1->SetFieldsCount(2,__wxStatusBarWidths_1);
    StatusBar1->SetStatusStyles(2,__wxStatusBarStyles_1);
    SetStatusBar(StatusBar1);
    Timer1.SetOwner(this, ID_TIMER1);
    Timer1.Start(60000, false);
    GridSizer1->Fit(this);
    GridSizer1->SetSizeHints(this);

    Connect(ID_BUTTON5,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnButton5Click);
    Connect(ID_TOGGLEBUTTON1,wxEVT_COMMAND_TOGGLEBUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnToggleButton1Toggle);
    Connect(ID_TOGGLEBUTTON2,wxEVT_COMMAND_TOGGLEBUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnToggleButton2Toggle);
    Connect(ID_HTMLLISTBOX1,wxEVT_COMMAND_LISTBOX_SELECTED,(wxObjectEventFunction)&kitchenFrame::OnListBox2Select);
    Connect(ID_HTMLLISTBOX2,wxEVT_COMMAND_LISTBOX_SELECTED,(wxObjectEventFunction)&kitchenFrame::OnListBox3Select);
    Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnButton3Click);
    Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnButton4Click);
    Connect(ID_HTMLLISTBOX3,wxEVT_COMMAND_LISTBOX_SELECTED,(wxObjectEventFunction)&kitchenFrame::OnListBox4Select);
    Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnButton1Click);
    Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnButton2Click);
    Connect(ID_BUTTON6,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&kitchenFrame::OnButton6Click);
    Connect(ID_NOTEBOOK1,wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED,(wxObjectEventFunction)&kitchenFrame::OnNotebook1PageChanged);
    Connect(idMenuQuit,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&kitchenFrame::OnQuit);
    Connect(ID_MENUITEM1,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&kitchenFrame::OnSettingsMenuSelected);
    Connect(idMenuAbout,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&kitchenFrame::OnAbout);
    Connect(ID_TIMER1,wxEVT_TIMER,(wxObjectEventFunction)&kitchenFrame::OnTimer1Trigger);
    //*)
    SetTitle(_T("Estescook ") + vers);
    // Connect(ID_HTMLLISTBOX3,wxEVT_COMMAND_LISTBOX_SELECTED,(wxObjectEventFunction)&kitchenFrame::OnListSelected);
    href = false;


    conn = new mysqlpp::Connection(false);
    connect_to_db();


    SocketClient1 = new wxSocketClient();
    SocketClient1->SetEventHandler(*this, SOCKET_ID);
    SocketClient1->SetNotify(wxSOCKET_CONNECTION_FLAG |
                             wxSOCKET_INPUT_FLAG |
                             wxSOCKET_LOST_FLAG);
    SocketClient1->Notify(true);


    connectToServer();

    fillMain();
    fillPanels();

    GridSizer1->Fit(this);
    GridSizer1->SetSizeHints(this);

}
Ejemplo n.º 21
0
caddr_t
get_process_info(struct system_info *si, struct process_select *sel,
    int compare_index, char *conninfo)
{
	int show_idle, show_system, show_threads, show_uid, show_cmd;
	int total_procs, active_procs;
	struct kinfo_proc2 **prefp, *pp;
	int mib[6];
	size_t size;

	int i;
	PGconn *pgconn;
	PGresult *pgresult = NULL;

	size = (size_t) sizeof(struct kinfo_proc2);
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC2;
	mib[2] = KERN_PROC_PID;
	mib[4] = sizeof(struct kinfo_proc2);
	mib[5] = 1;

	nproc = 0;
	pgconn = connect_to_db(conninfo);
	if (pgconn != NULL)
	{
		pgresult = pg_processes(pgconn);
		nproc = PQntuples(pgresult);
		pbase = (struct kinfo_proc2 *) realloc(pbase,
				sizeof(struct kinfo_proc2 *) * nproc);
	}
	PQfinish(pgconn);

	if (nproc > onproc)
		pref = (struct kinfo_proc2 **)realloc(pref,
		    sizeof(struct kinfo_proc2 *) * (onproc = nproc));
	if (pref == NULL) {
		warnx("Out of memory.");
		quit(23);
	}
	/* get a pointer to the states summary array */
	si->procstates = process_states;

	/* set up flags which define what we are going to select */
	show_idle = sel->idle;
	show_uid = sel->uid != (uid_t)-1;
	show_cmd = sel->command != NULL;

	/* count up process states and get pointers to interesting procs */
	total_procs = 0;
	active_procs = 0;
	memset((char *) process_states, 0, sizeof(process_states));
	prefp = pref;
	i = 0;
	for (pp = pbase; pp < &pbase[nproc]; pp++) {
		mib[3] = atoi(PQgetvalue(pgresult, i, 0));
		if (sysctl(mib, 6, &pbase[i++], &size, NULL, 0) != 0)
		{
			printf("\n\ndoh %d\n", errno);
			perror("\n\ndoh");
			exit(1);
		}

		/*
		 *  Place pointers to each valid proc structure in pref[].
		 *  Process slots that are actually in use have a non-zero
		 *  status field.  Processes with P_SYSTEM set are system
		 *  processes---these get ignored unless show_system is set.
		 */
		if (pp->p_stat != 0 &&
		    (show_system || (pp->p_flag & P_SYSTEM) == 0) &&
		    (show_threads || (pp->p_flag & P_THREAD) == 0)) {
			total_procs++;
			process_states[(unsigned char) pp->p_stat]++;
			if (pp->p_stat != SZOMB &&
			    (show_idle || pp->p_pctcpu != 0 ||
			    pp->p_stat == SRUN) &&
			    (!show_uid || pp->p_ruid == sel->uid) &&
			    (!show_cmd || strstr(pp->p_comm,
				sel->command))) {
				*prefp++ = pp;
				active_procs++;
			}
		}
	}

	/* if requested, sort the "interesting" processes */
	if (compare_index != NULL)
		qsort((char *) pref, active_procs,
		    sizeof(struct kinfo_proc2 *), proc_compares[compare_index]);
	/* remember active and total counts */
	si->p_total = total_procs;
	si->p_active = pref_len = active_procs;

	/* pass back a handle */
	handle.next_proc = pref;
	handle.remaining = active_procs;
	return ((caddr_t) & handle);
}
Ejemplo n.º 22
0
time_loggerFrame::time_loggerFrame(wxWindow* parent,wxWindowID id)
{

readSet();


    std::string version = AutoVersion::FULLVERSION_STRING;
    wxString vers;
    vers << AutoVersion::MAJOR << _T(".") << AutoVersion::MINOR << _T(".") << AutoVersion::BUILD;

    //(*Initialize(time_loggerFrame)
    wxGridSizer* GridSizer1;
    wxFlexGridSizer* FlexGridSizer1;
    wxFlexGridSizer* FlexGridSizer2;
    wxGridSizer* GridSizer6;
    wxFlexGridSizer* FlexGridSizer4;
    wxFlexGridSizer* FlexGridSizer3;
    wxBoxSizer* BoxSizer1;

    Create(parent, wxID_ANY, _("Time Logger"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE, _T("wxID_ANY"));
    {
    	wxIcon FrameIcon;
    	FrameIcon.CopyFromBitmap(wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_NORMAL_FILE")),wxART_OTHER));
    	SetIcon(FrameIcon);
    }
    GridSizer6 = new wxGridSizer(1, 1, 0, 0);
    FlexGridSizer1 = new wxFlexGridSizer(2, 1, 0, 0);
    BoxSizer1 = new wxBoxSizer(wxHORIZONTAL);
    BoxSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText1 = new wxStaticText(this, ID_STATICTEXT1, wxEmptyString, wxDefaultPosition, wxSize(180,90), 0, _T("ID_STATICTEXT1"));
    wxFont StaticText1Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    StaticText1->SetFont(StaticText1Font);
    BoxSizer1->Add(StaticText1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer4 = new wxFlexGridSizer(2, 2, 0, 0);
    FlexGridSizer4->Add(30,20,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText2 = new wxStaticText(this, ID_STATICTEXT2, _("Current time:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2"));
    wxFont StaticText2Font(20,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    StaticText2->SetFont(StaticText2Font);
    FlexGridSizer4->Add(StaticText2, 1, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer4->Add(30,20,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText3 = new wxStaticText(this, ID_STATICTEXT3, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3"));
    wxFont StaticText3Font(24,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    StaticText3->SetFont(StaticText3Font);
    FlexGridSizer4->Add(StaticText3, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    BoxSizer1->Add(FlexGridSizer4, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer1->Add(BoxSizer1, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer2 = new wxFlexGridSizer(1, 2, 0, 0);
    GridSizer1 = new wxGridSizer(3, 4, 10, 10);
    Button1 = new wxButton(this, ID_BUTTON1, _("1"), wxDefaultPosition, wxSize(170,170), 0, wxDefaultValidator, _T("ID_BUTTON1"));
    wxFont Button1Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button1->SetFont(Button1Font);
    GridSizer1->Add(Button1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button2 = new wxButton(this, ID_BUTTON2, _("2"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2"));
    wxFont Button2Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button2->SetFont(Button2Font);
    GridSizer1->Add(Button2, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button3 = new wxButton(this, ID_BUTTON3, _("3"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON3"));
    wxFont Button3Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button3->SetFont(Button3Font);
    GridSizer1->Add(Button3, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    GridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button4 = new wxButton(this, ID_BUTTON4, _("4"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON4"));
    wxFont Button4Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button4->SetFont(Button4Font);
    GridSizer1->Add(Button4, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button5 = new wxButton(this, ID_BUTTON5, _("5"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON5"));
    wxFont Button5Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button5->SetFont(Button5Font);
    GridSizer1->Add(Button5, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button6 = new wxButton(this, ID_BUTTON6, _("6"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON6"));
    wxFont Button6Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button6->SetFont(Button6Font);
    GridSizer1->Add(Button6, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    GridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button7 = new wxButton(this, ID_BUTTON7, _("7"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON7"));
    wxFont Button7Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button7->SetFont(Button7Font);
    GridSizer1->Add(Button7, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button8 = new wxButton(this, ID_BUTTON8, _("8"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON8"));
    wxFont Button8Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button8->SetFont(Button8Font);
    GridSizer1->Add(Button8, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button9 = new wxButton(this, ID_BUTTON9, _("9"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON9"));
    wxFont Button9Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button9->SetFont(Button9Font);
    GridSizer1->Add(Button9, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button13 = new wxButton(this, ID_BUTTON13, _("0"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON13"));
    wxFont Button13Font(56,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button13->SetFont(Button13Font);
    GridSizer1->Add(Button13, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer2->Add(GridSizer1, 1, wxRIGHT|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 20);
    FlexGridSizer3 = new wxFlexGridSizer(5, 1, 0, 0);
    Button10 = new wxButton(this, ID_BUTTON10, _("<--"), wxDefaultPosition, wxSize(170,85), 0, wxDefaultValidator, _T("ID_BUTTON10"));
    wxFont Button10Font(32,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button10->SetFont(Button10Font);
    FlexGridSizer3->Add(Button10, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer3->Add(20,85,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button11 = new wxButton(this, ID_BUTTON11, _("Cancel"), wxDefaultPosition, wxSize(170,85), 0, wxDefaultValidator, _T("ID_BUTTON11"));
    wxFont Button11Font(26,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button11->SetFont(Button11Font);
    FlexGridSizer3->Add(Button11, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer3->Add(20,85,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    Button12 = new wxButton(this, ID_BUTTON12, _("Enter"), wxDefaultPosition, wxSize(170,170), 0, wxDefaultValidator, _T("ID_BUTTON12"));
    wxFont Button12Font(40,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Sans"),wxFONTENCODING_DEFAULT);
    Button12->SetFont(Button12Font);
    FlexGridSizer3->Add(Button12, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer2->Add(FlexGridSizer3, 1, wxLEFT|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 20);
    FlexGridSizer1->Add(FlexGridSizer2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    GridSizer6->Add(FlexGridSizer1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    SetSizer(GridSizer6);
    StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1"));
    int __wxStatusBarWidths_1[1] = { -10 };
    int __wxStatusBarStyles_1[1] = { wxSB_NORMAL };
    StatusBar1->SetFieldsCount(1,__wxStatusBarWidths_1);
    StatusBar1->SetStatusStyles(1,__wxStatusBarStyles_1);
    SetStatusBar(StatusBar1);
    Timer1.SetOwner(this, ID_TIMER1);
    Timer1.Start(100, false);
    GridSizer6->Fit(this);
    GridSizer6->SetSizeHints(this);

    Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton1Click);
    Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton2Click);
    Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton3Click);
    Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton4Click);
    Connect(ID_BUTTON5,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton5Click);
    Connect(ID_BUTTON6,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton6Click);
    Connect(ID_BUTTON7,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton7Click);
    Connect(ID_BUTTON8,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton8Click);
    Connect(ID_BUTTON9,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton9Click);
    Connect(ID_BUTTON13,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton13Click1);
    Connect(ID_BUTTON10,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton12Click);
    Connect(ID_BUTTON11,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton13Click);
    Connect(ID_BUTTON12,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&time_loggerFrame::OnButton11Click);
    Connect(ID_TIMER1,wxEVT_TIMER,(wxObjectEventFunction)&time_loggerFrame::OnTimer1Trigger);
    //*)
SetTitle(_T("Time Logger ") + vers);

conn = new mysqlpp::Connection(false);


connect_to_db();
empId = 0;
}
Ejemplo n.º 23
0
caddr_t
get_process_info(struct system_info * si,
				 struct process_select * sel,
				 int compare_index, char *conninfo, int mode)
{
	struct timeval thistime;
	double		timediff,
				alpha,
				beta;
	struct top_proc *proc;
	pid_t		pid;
	unsigned long now;
	unsigned long elapsed;
	int			i;

	/* calculate the time difference since our last check */
	gettimeofday(&thistime, 0);
	if (lasttime.tv_sec)
	{
		timediff = ((thistime.tv_sec - lasttime.tv_sec) +
					(thistime.tv_usec - lasttime.tv_usec) * 1e-6);
	}
	else
	{
		timediff = 0;
	}
	lasttime = thistime;

	/* round current time to a second */
	now = (unsigned long) thistime.tv_sec;
	if (thistime.tv_usec >= 500000)
	{
		now++;
	}

	/* calculate constants for the exponental average */
	if (timediff > 0.0 && timediff < 30.0)
	{
		alpha = 0.5 * (timediff / 30.0);
		beta = 1.0 - alpha;
	}
	else
	{
		alpha = beta = 0.5;
	}
	timediff *= HZ;				/* convert to ticks */

	/* mark all hash table entries as not seen */
	for (i = 0; i < HASH_SIZE; ++i)
	{
		for (proc = ptable[i]; proc; proc = proc->next)
		{
			proc->state = 0;
		}
	}

	/* read the process information */
	{
		int			total_procs = 0;
		struct top_proc **active;

		int			show_idle = sel->idle;
		int			show_uid = sel->uid != -1;

		int			i;
		int			rows;
		PGconn	   *pgconn;
		PGresult   *pgresult = NULL;

		memset(process_states, 0, sizeof(process_states));

		pgconn = connect_to_db(conninfo);
		if (pgconn != NULL)
		{
			pgresult = pg_processes(pgconn);
			rows = PQntuples(pgresult);
		}
		else
		{
			rows = 0;
		}
		for (i = 0; i < rows; i++)
		{
			char	   *procpid = PQgetvalue(pgresult, i, 0);
			struct top_proc *pp;
			unsigned long otime;

			pid = atoi(procpid);

			/* look up hash table entry */
			proc = pp = ptable[HASH(pid)];
			while (proc && proc->pid != pid)
			{
				proc = proc->next;
			}

			/* if we came up empty, create a new entry */
			if (proc == NULL)
			{
				proc = new_proc();
				proc->pid = pid;
				proc->next = pp;
				ptable[HASH(pid)] = proc;
				proc->time = 0;
				proc->wcpu = 0;
			}

			otime = proc->time;

			read_one_proc_stat(pid, proc, sel);
			if (sel->fullcmd == 2)
				update_procname(proc, PQgetvalue(pgresult, i, 1));

			if (proc->state == 0)
				continue;

			total_procs++;
			process_states[proc->state]++;

			if (timediff > 0.0)
			{
				if ((proc->pcpu = (proc->time - otime) / timediff) < 0.0001)
				{
					proc->pcpu = 0;
				}
				proc->wcpu = proc->pcpu * alpha + proc->wcpu * beta;
			}
			else if ((elapsed = (now - boottime) * HZ - proc->start_time) > 0)
			{
				/*
				 * What's with the noop statement? if ((proc->pcpu =
				 * (double)proc->time / (double)elapsed) < 0.0001) {
				 * proc->pcpu; }
				 */
				proc->wcpu = proc->pcpu;
			}
			else
			{
				proc->wcpu = proc->pcpu = 0.0;
			}
		}
		if (pgresult != NULL)
			PQclear(pgresult);
		PQfinish(pgconn);

		/* make sure we have enough slots for the active procs */
		if (activesize < total_procs)
		{
			pactive = (struct top_proc **) realloc(pactive,
									sizeof(struct top_proc *) * total_procs);
			activesize = total_procs;
		}

		/* set up the active procs and flush dead entries */
		active = pactive;
		for (i = 0; i < HASH_SIZE; i++)
		{
			struct top_proc *last;
			struct top_proc *ptmp;

			last = NULL;
			proc = ptable[i];
			while (proc != NULL)
			{
				if (proc->state == 0)
				{
					ptmp = proc;
					if (last)
					{
						proc = last->next = proc->next;
					}
					else
					{
						proc = ptable[i] = proc->next;
					}
					free_proc(ptmp);
				}
				else
				{
					if ((show_idle || proc->state == 1 || proc->pcpu) &&
						(!show_uid || proc->uid == sel->uid))
					{
						*active++ = proc;
						last = proc;
					}
					proc = proc->next;
				}
			}
		}

		si->p_active = active - pactive;
		si->p_total = total_procs;
		si->procstates = process_states;
	}

	/* if requested, sort the "active" procs */
	if (si->p_active) {
		if (mode == MODE_IO_STATS) {
			qsort(pactive, si->p_active, sizeof(struct top_proc *),
			  		io_compares[compare_index]);
		}
		else
		{
			qsort(pactive, si->p_active, sizeof(struct top_proc *),
			  		proc_compares[compare_index]);
		}
	}

	/* don't even pretend that the return value thing here isn't bogus */
	nextactive = pactive;
	return (caddr_t) 0;
}
Ejemplo n.º 24
0
Archivo: pg.c Proyecto: xrg/pg_top
void
pg_display_table_stats(char *conninfo, int compare_index, int max_topn)
{
	int			i;
	int			rows;
	PGconn	   *pgconn;
	PGresult   *pgresult = NULL;
	static char line[512];

	static struct table_node *head = NULL;
	static struct table_node **procs = NULL;

	int			max_lines;

	/* Get the currently running query. */
	pgconn = connect_to_db(conninfo);
	if (pgconn != NULL)
	{
		pgresult = PQexec(pgconn, SELECT_TABLE_STATS);
		rows = PQntuples(pgresult);
	}
	else
	{
		PQfinish(pgconn);
		return;
	}
	PQfinish(pgconn);

	max_lines = rows < max_topn ? rows : max_topn;

	procs = (struct table_node **) realloc(procs,
										 rows * sizeof(struct table_node *));
	/* Calculate change in values. */
	for (i = 0; i < rows; i++)
	{
		head = upsert_table_stats(head,
								  atoll(PQgetvalue(pgresult, i, 0)),
								  atoll(PQgetvalue(pgresult, i, 2)),
								  atoll(PQgetvalue(pgresult, i, 3)),
								  atoll(PQgetvalue(pgresult, i, 4)),
								  atoll(PQgetvalue(pgresult, i, 5)),
								  atoll(PQgetvalue(pgresult, i, 6)),
								  atoll(PQgetvalue(pgresult, i, 7)),
								  atoll(PQgetvalue(pgresult, i, 8)));
	}

	/* Sort stats. */
	for (i = 0; i < rows; i++)
	{
		procs[i] = get_table_stats(head, atoll(PQgetvalue(pgresult, i, 0)));
		procs[i]->name_index = i;
	}
	qsort(procs, rows, sizeof(struct table_node *),
		  table_compares[compare_index]);

	for (i = rows - 1; i > rows - max_lines - 1; i--)
	{
		if (mode_stats == STATS_DIFF) {
			snprintf(line, sizeof(line),
				 	"%9lld %9lld %9lld %9lld %9lld %9lld %9lld %s",
				 	procs[i]->diff_seq_scan,
				 	procs[i]->diff_seq_tup_read,
				 	procs[i]->diff_idx_scan,
				 	procs[i]->diff_idx_tup_fetch,
				 	procs[i]->diff_n_tup_ins,
				 	procs[i]->diff_n_tup_upd,
				 	procs[i]->diff_n_tup_del,
				 	PQgetvalue(pgresult, procs[i]->name_index, 1));
		}
		else
		{
			snprintf(line, sizeof(line),
				 	"%9lld %9lld %9lld %9lld %9lld %9lld %9lld %s",
				 	procs[i]->total_seq_scan,
				 	procs[i]->total_seq_tup_read,
				 	procs[i]->total_idx_scan,
				 	procs[i]->total_idx_tup_fetch,
				 	procs[i]->total_n_tup_ins,
				 	procs[i]->total_n_tup_upd,
				 	procs[i]->total_n_tup_del,
				 	PQgetvalue(pgresult, procs[i]->name_index, 1));
		}
		u_process(rows - i - 1, line);
	}

	if (pgresult != NULL)
		PQclear(pgresult);
}
Ejemplo n.º 25
0
void
show_explain(char *conninfo, int procpid, int analyze)
{
	int			i,
				j;
	int			rows,
				r;
	char		sql[4096];
	char		info[1024];
	PGconn	   *pgconn;
	PGresult   *pgresult_query = NULL;
	PGresult   *pgresult_explain = NULL;

	sprintf(info,
			"Current query plan for procpid %d:\n\n Statement:\n\n",
			procpid);
	display_pager(info);

	/* Get the currently running query. */
	pgconn = connect_to_db(conninfo);
	if (pgconn != NULL)
	{
		pgresult_query = pg_query(pgconn, procpid);
		rows = PQntuples(pgresult_query);
	}
	else
	{
		rows = 0;
	}
	for (i = 0; i < rows; i++)
	{
		/* Display the query before the query plan. */
		display_pager(PQgetvalue(pgresult_query, i, 0));

		/* Execute the EXPLAIN. */
		if (analyze == EXPLAIN_ANALYZE)
		{
			sprintf(sql, "EXPLAIN ANALYZE\n%s",
					PQgetvalue(pgresult_query, i, 0));
		}
		else
		{
			sprintf(sql, "EXPLAIN\n%s", PQgetvalue(pgresult_query, i, 0));
		}
		PQexec(pgconn, BEGIN);
		pgresult_explain = PQexec(pgconn, sql);
		PQexec(pgconn, ROLLBACK);
		r = PQntuples(pgresult_explain);
		/* This will display an error if the EXPLAIN fails. */
		display_pager("\n\nQuery Plan:\n\n");
		display_pager(PQresultErrorMessage(pgresult_explain));
		for (j = 0; j < r; j++)
		{
			display_pager(PQgetvalue(pgresult_explain, j, 0));
			display_pager("\n");
		}
		if (pgresult_explain != NULL)
			PQclear(pgresult_explain);
	}
	display_pager("\n\n");

	if (pgresult_query != NULL)
		PQclear(pgresult_query);
	PQfinish(pgconn);
}
Ejemplo n.º 26
0
caddr_t
get_process_info(struct system_info * si, struct process_select * sel, int x,
		char *conninfo, int mode)
{
	register int i;
	register int total_procs;
	register int active_procs;
	register struct macos_proc **prefp;
	register struct macos_proc *pp;
	register struct kinfo_proc *pp2;

	/*
	 * these are copied out of sel for speed
	 */

	int			show_idle;
	int			show_system;
	int			show_uid;
	int			show_command;

	/* begin mucking */
	/* kproc_list = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc); */
	PGconn *pgconn;
	PGresult *pgresult = NULL;

	nproc = 0;
	pgconn = connect_to_db(conninfo);
	if (pgconn != NULL)
	{
		pgresult = PQexec(pgconn, QUERY_PROCESSES);
		nproc = PQntuples(pgresult);
		pbase = (struct kinfo_proc *) malloc(sizeof(struct kinfo_proc *));
	}
	PQfinish(pgconn);

	int mib[4];
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PID;

	size_t len = nproc;

	struct kinfo_proc *buffer;
	buffer = (struct kinfo_proc *) malloc( len * sizeof(struct kinfo_proc) );

	for (i = 0; i < nproc ; i++) {
		size_t size = sizeof(struct kinfo_proc);	
		mib[3] = atoi(PQgetvalue(pgresult, i, 0));
		
		if (sysctl(mib, sizeof(mib)/sizeof(int), &buffer[i], &size, NULL,
				0) == -1) {
			perror("sysctl atoi loop");
			return "1";
		}

	}

	kproc_list = buffer;
	len = nproc;
	/* end selena's messing about */

	if (nproc > onproc)
	{
		proc_list = (struct macos_proc *) realloc(proc_list,
				sizeof(struct macos_proc) * nproc);
		proc_ref = (struct macos_proc **) realloc(proc_ref,
				sizeof(struct macos_proc *) * (onproc = nproc));
	}

	if (proc_ref == NULL || proc_list == NULL || kproc_list == NULL)
	{
		puke("error: out of memory (%s)", strerror(errno));
		return (NULL);
	}

	/*
	 * now, our task is to build the array of information we need to function
	 * correctly.  This involves setting a pointer to each real kinfo_proc
	 * structure returned by kvm_getprocs() in addition to getting the mach
	 * information for each of those processes.
	 */

	for (pp2 = kproc_list, i = 0; i < nproc; pp2++, i++)
	{

		/*
		 * first, we set the pointer to the reference in the kproc list.
		 */

		proc_list[i].kproc = pp2;

		/*
		 * then, we load all of the task info for the process
		 */

		if (PP(pp2, p_stat) != SZOMB)
		{
			load_thread_info(&proc_list[i]);
		}
	}

	/* get a pointer to the states summary array */
	si->procstates = process_states;

	/* set up flags which define what we are going to select */
	show_idle = sel->idle;
	show_uid = sel->uid != -1;
	show_command = sel->command != NULL;
	show_fullcmd = sel->fullcmd;

	/* count up process states and get pointers to interesting procs */
	total_procs = 0;
	active_procs = 0;
	memset((char *) process_states, 0, sizeof(process_states));
	prefp = proc_ref;
	for (pp = proc_list, i = 0; i < nproc; pp++, i++)
	{
		/*
		 * Place pointers to each valid proc structure in proc_ref[].  Process
		 * slots that are actually in use have a non-zero status field.
		 * Processes with P_SYSTEM set are system processes---these get
		 * ignored unless show_sysprocs is set.
		 */
		if (MPP(pp, p_stat) != 0 &&
				(show_system || ((MPP(pp, p_flag) & P_SYSTEM) == 0)))
		{
			total_procs++;
			process_states[(unsigned char) MPP(pp, p_stat)]++;
			if ((MPP(pp, p_stat) != SZOMB) &&
					(show_idle || (MPP(pp, p_pctcpu) != 0) ||
					(MPP(pp, p_stat) == SRUN)) &&
					(!show_uid || MEP(pp, e_pcred.p_ruid) == (uid_t) sel->uid))
			{
				*prefp++ = pp;
				active_procs++;
			}
		}
	}

	/*
	 * if requested, sort the "interesting" processes
	 */

	qsort((char *) proc_ref, active_procs, sizeof(struct macos_proc *),
			proc_compare);

	/* remember active and total counts */
	si->p_total = total_procs;
	si->p_active = pref_len = active_procs;

	/* pass back a handle */
	handle.next_proc = proc_ref;
	handle.remaining = active_procs;
	return ((caddr_t) & handle);
}
Ejemplo n.º 27
0
void
show_locks(char *conninfo, int procpid)
{
	int			i,
				j,
				k;
	int			rows;
	char		info[64];
	int			width[5] = {1, 8, 5, 4, 7};
	PGconn	   *pgconn;
	PGresult   *pgresult = NULL;
	char		header_format[1024];
	char		line_format[1024];
	char		prefix[21];		/* Should hold any 64 bit integer. */
	char		line[1024];

	sprintf(info, "Locks held by procpid %d:\n\n", procpid);
	display_pager(info);

	/* Get the locks helf by the process. */
	pgconn = connect_to_db(conninfo);
	if (pgconn == NULL)
	{
		PQfinish(pgconn);
		return;
	}

	pgresult = pg_locks(pgconn, procpid);
	rows = PQntuples(pgresult);

	/* Determine column sizes. */
	sprintf(prefix, "%d", rows);
	width[0] = strlen(prefix);
	for (i = 0; i < rows; i++)
	{
		if (strlen(PQgetvalue(pgresult, i, 0)) > width[1])
			width[1] = strlen(PQgetvalue(pgresult, i, 0));
		if (strlen(PQgetvalue(pgresult, i, 1)) > width[2])
			width[2] = strlen(PQgetvalue(pgresult, i, 1));
		if (strlen(PQgetvalue(pgresult, i, 2)) > width[3])
			width[3] = strlen(PQgetvalue(pgresult, i, 2));
		if (strlen(PQgetvalue(pgresult, i, 3)) > width[4])
			width[4] = strlen(PQgetvalue(pgresult, i, 3));
	}
	sprintf(header_format, "%%-%ds | %%-%ds | %%-%ds | %%-%ds | %%-%ds\n",
			width[0], width[1], width[2], width[3], width[4]);
	sprintf(line_format, "%%%dd | %%-%ds | %%-%ds | %%-%ds | %%-%ds\n",
			width[0], width[1], width[2], width[3], width[4]);

	/* Display the header. */
	sprintf(line, header_format, "", "database", "table", "type", "granted");
	display_pager(line);
	for (i = 0, k = 0; i < 5; i++)
	{
		for (j = 0; j < width[i]; j++, k++)
		{
			line[k] = '-';
		}
		line[k++] = '-';
		line[k++] = '+';
		line[k++] = '-';
	}
	line[k - 3] = '\n';
	line[k - 2] = '\0';
	display_pager(line);

	/* Display data. */
	for (i = 0; i < rows; i++)
	{
		sprintf(line, line_format, i + 1, PQgetvalue(pgresult, i, 0),
				PQgetvalue(pgresult, i, 1), PQgetvalue(pgresult, i, 2),
				PQgetvalue(pgresult, i, 3));
		display_pager(line);
	}
	display_pager("\n");

	PQclear(pgresult);
	PQfinish(pgconn);
}