static int ec_poll(struct acpi_ec *ec) { unsigned long flags; int repeat = 2; /* number of command restarts */ while (repeat--) { unsigned long delay = jiffies + msecs_to_jiffies(ec_delay); do { /* don't sleep with disabled interrupts */ if (EC_FLAGS_MSI || irqs_disabled()) { udelay(ACPI_EC_MSI_UDELAY); if (ec_transaction_done(ec)) return 0; } else { if (wait_event_timeout(ec->wait, ec_transaction_done(ec), msecs_to_jiffies(1))) return 0; } advance_transaction(ec, acpi_ec_read_status(ec)); } while (time_before(jiffies, delay)); if (acpi_ec_read_status(ec) & ACPI_EC_FLAG_IBF) break; pr_debug(PREFIX "controller reset, restart transaction\n"); spin_lock_irqsave(&ec->curr_lock, flags); start_transaction(ec); spin_unlock_irqrestore(&ec->curr_lock, flags); } return -ETIME; }
int main(int argc, char * argv[]) { init_client(); start_transaction(); close_client(); fprintf(stderr, "closed.....\n"); return 0; }
/* * To write a register, start transaction, transfer data to the TPM, deassert * CS when done. * * Returns one to indicate success, zero to indicate failure. */ static int tpm2_write_reg(unsigned reg_number, const void *buffer, size_t bytes) { struct spi_slave *spi_slave = car_get_var_ptr(&g_spi_slave); trace_dump("W", reg_number, bytes, buffer, 0); if (!start_transaction(false, bytes, reg_number)) return 0; write_bytes(buffer, bytes); spi_release_bus(spi_slave); return 1; }
static pid_t child_make(int i, int listenfd) { pid_t pid; if ((pid = fork_wrapper()) > 0) return pid; while(true) { wait_client(listenfd); start_transaction(); } exit(0); }
static void transact_command(ostream &out, istream &in) { int choice ; int transaction ; int result ; do { choice = display_menu(out,in,true,3, "Transactions", "\t1. Start a transaction\n" "\t2. End a transaction\n" "\t3. Abort a transaction\n" ) ; switch (choice) { case 0: // do nothing break ; case 1: transaction = start_transaction() ; if (transaction == -1) out << "Unable to start transaction" << endl ; else out << "Started transaction number " << transaction << endl ; break ; case 2: transaction = get_number(out,in,"Transaction number:",-1, SHRT_MAX) ; result = end_transaction(transaction) ; if (result == -1) out << "Failed while ending transaction, error code = " << Fr_errno << endl ; else out << "Transaction ended successfully" << endl ; break ; case 3: transaction = get_number(out,in,"Transaction number:",-1, SHRT_MAX) ; result = abort_transaction(transaction) ; if (result == -1) { out << "Failed while aborting transaction, error code = " << Fr_errno << endl ; } else out << "Transaction successfully rolled back" << endl ; break ; default: FrMissedCase("transact_command") ; break ; } } while (choice != 0) ; return ; }
/* * To read a register, start transaction, transfer data from the TPM, deassert * CS when done. * * Returns one to indicate success, zero to indicate failure. In case of * failure zero out the user buffer. */ static int tpm2_read_reg(unsigned reg_number, void *buffer, size_t bytes) { struct spi_slave *spi_slave = car_get_var_ptr(&g_spi_slave); if (!start_transaction(true, bytes, reg_number)) { memset(buffer, 0, bytes); return 0; } read_bytes(buffer, bytes); spi_release_bus(spi_slave); trace_dump("R", reg_number, bytes, buffer, 0); return 1; }
void test_trnman_read_from() { TRN *trn[Ntrns]; TrID trid[Ntrns]; int i; start_transaction(0); /* start trn1 */ start_transaction(1); /* start trn2 */ ok_read_from(1, 0, 0); commit(0); /* commit trn1 */ start_transaction(2); /* start trn4 */ abort(2); /* abort trn4 */ start_transaction(3); /* start trn5 */ ok_read_from(3, 0, 1); ok_read_from(3, 1, 0); ok_read_from(3, 2, 0); ok_read_from(3, 3, 1); commit(1); /* commit trn2 */ ok_read_from(3, 1, 0); commit(3); /* commit trn5 */ }
std::string SqliteDao::save() { int ret = 0; start_transaction(); int table_num = table_manager_->get_schema_manager()->get_table_num(); for (int i = 0; i < table_num; i++) { db_mm::TableIndex* table_index = table_manager_->get_table_index(i); db_mm::TableIndex::RowIndexIter row_iter = table_index->iter(); if (!table_index->has_data()) { continue; } db_mm::RowIndex* row_index = NULL; while (0 == row_iter.get_next(row_index) && 0 == ret) { if (db_mm::DELETE_ROW == row_index->get_row_stat()) { ret = delete_data(row_index); } else if (db_mm::UPDATE_ROW == row_index->get_row_stat()) { if (0 == ret && 0 == (ret = delete_data(row_index))) { ret = insert_data(row_index); } } } } if (0 == ret) { commit(); } else { error_msg_ = sqlite3_errmsg(sqlite_); roll_back(); } return error_msg_; }
void remote_execute(PlxConn *plx_conn, PlxFn *plx_fn, FunctionCallInfo fcinfo) { PlxQuery *plx_q = plx_fn->run_query; char **args = NULL; int *arg_lens = NULL; int *arg_fmts = NULL; StringInfo sql; /* memory will be alloced in ExprContext - not necessary to free it */ prepare_execute(plx_fn, fcinfo, &sql, &args, &arg_lens, &arg_fmts); start_transaction(plx_conn); plx_send_query(plx_fn, plx_conn, sql->data, args, plx_q->nargs, arg_lens, arg_fmts); /* code below will be never executed if pg_result is wrong */ plx_result_insert_cache(fcinfo, plx_fn, get_pg_result(plx_fn, plx_conn)); }
Transaction * NetworkQueue::send ( SignalArgs & args, Priority priority ) { Transaction * transaction = nullptr; std::string python_repr=args.to_python_script(); if (python_repr.size()) NScriptEngine::global().get()->append_false_command_to_python_console(python_repr); if( priority == IMMEDIATE ){ ThreadManager::instance().network().send( args ); }else { QString uuid = start_transaction(); transaction = m_new_transactions[uuid]; add_to_transaction( uuid, args ); insert_transaction( uuid, priority ); } return transaction; }
int exec_sql_list_in_transaction ( sqlite3 *db, const char **sqls ) { VERBOSE_PRINTF("exec_sql_list_in_transaction()\n"); int ret = 0; ret = start_transaction(db); if (ret) { return ret; } ret = exec_sql_list(db, sqls); if (ret) { //return ret; } int ret2 = end_transaction(db, ret); if (ret) { return ret; } return ret2; }
static int acpi_ec_transaction_unlocked(struct acpi_ec *ec, struct transaction *t) { unsigned long tmp; int ret = 0; if (EC_FLAGS_MSI) udelay(ACPI_EC_MSI_UDELAY); /* start transaction */ spin_lock_irqsave(&ec->curr_lock, tmp); /* following two actions should be kept atomic */ ec->curr = t; start_transaction(ec); if (ec->curr->command == ACPI_EC_COMMAND_QUERY) clear_bit(EC_FLAGS_QUERY_PENDING, &ec->flags); spin_unlock_irqrestore(&ec->curr_lock, tmp); ret = ec_poll(ec); spin_lock_irqsave(&ec->curr_lock, tmp); ec->curr = NULL; spin_unlock_irqrestore(&ec->curr_lock, tmp); return ret; }
int main(int argc, char** argv) { NDB_INIT(argv[0]); const char *load_default_groups[]= { "mysql_cluster",0 }; load_defaults("my",load_default_groups,&argc,&argv); int ho_error; #ifndef DBUG_OFF opt_debug= "d:t:F:L"; #endif if ((ho_error=handle_options(&argc, &argv, my_long_options, ndb_std_get_one_option))) return NDBT_ProgramExit(NDBT_WRONGARGS); DBUG_ENTER("main"); Ndb_cluster_connection con(opt_connect_str); if(con.connect(12, 5, 1)) { DBUG_RETURN(NDBT_ProgramExit(NDBT_FAILED)); } Ndb ndb(&con,_dbname); ndb.init(); while (ndb.waitUntilReady() != 0); NdbDictionary::Dictionary * dict = ndb.getDictionary(); int no_error= 1; int i; // create all tables Vector<const NdbDictionary::Table*> pTabs; if (argc == 0) { NDBT_Tables::dropAllTables(&ndb); NDBT_Tables::createAllTables(&ndb); for (i= 0; no_error && i < NDBT_Tables::getNumTables(); i++) { const NdbDictionary::Table *pTab= dict->getTable(NDBT_Tables::getTable(i)->getName()); if (pTab == 0) { ndbout << "Failed to create table" << endl; ndbout << dict->getNdbError() << endl; no_error= 0; break; } pTabs.push_back(pTab); } } else { for (i= 0; no_error && argc; argc--, i++) { dict->dropTable(argv[i]); NDBT_Tables::createTable(&ndb, argv[i]); const NdbDictionary::Table *pTab= dict->getTable(argv[i]); if (pTab == 0) { ndbout << "Failed to create table" << endl; ndbout << dict->getNdbError() << endl; no_error= 0; break; } pTabs.push_back(pTab); } } pTabs.push_back(NULL); // create an event for each table for (i= 0; no_error && pTabs[i]; i++) { HugoTransactions ht(*pTabs[i]); if (ht.createEvent(&ndb)){ no_error= 0; break; } } // create an event operation for each event Vector<NdbEventOperation *> pOps; for (i= 0; no_error && pTabs[i]; i++) { char buf[1024]; sprintf(buf, "%s_EVENT", pTabs[i]->getName()); NdbEventOperation *pOp= ndb.createEventOperation(buf, 1000); if ( pOp == NULL ) { no_error= 0; break; } pOps.push_back(pOp); } // get storage for each event operation for (i= 0; no_error && pTabs[i]; i++) { int n_columns= pTabs[i]->getNoOfColumns(); for (int j = 0; j < n_columns; j++) { pOps[i]->getValue(pTabs[i]->getColumn(j)->getName()); pOps[i]->getPreValue(pTabs[i]->getColumn(j)->getName()); } } // start receiving events for (i= 0; no_error && pTabs[i]; i++) { if ( pOps[i]->execute() ) { no_error= 0; break; } } // create a "shadow" table for each table Vector<const NdbDictionary::Table*> pShadowTabs; for (i= 0; no_error && pTabs[i]; i++) { char buf[1024]; sprintf(buf, "%s_SHADOW", pTabs[i]->getName()); dict->dropTable(buf); if (dict->getTable(buf)) { no_error= 0; break; } NdbDictionary::Table table_shadow(*pTabs[i]); table_shadow.setName(buf); dict->createTable(table_shadow); pShadowTabs.push_back(dict->getTable(buf)); if (!pShadowTabs[i]) { no_error= 0; break; } } // create a hugo operation per table Vector<HugoOperations *> hugo_ops; for (i= 0; no_error && pTabs[i]; i++) { hugo_ops.push_back(new HugoOperations(*pTabs[i])); } int n_records= 3; // insert n_records records per table do { if (start_transaction(&ndb, hugo_ops)) { no_error= 0; break; } for (i= 0; no_error && pTabs[i]; i++) { hugo_ops[i]->pkInsertRecord(&ndb, 0, n_records); } if (execute_commit(&ndb, hugo_ops)) { no_error= 0; break; } if(close_transaction(&ndb, hugo_ops)) { no_error= 0; break; } } while(0); // copy events and verify do { if (copy_events(&ndb) < 0) { no_error= 0; break; } if (verify_copy(&ndb, pTabs, pShadowTabs)) { no_error= 0; break; } } while (0); // update n_records-1 records in first table do { if (start_transaction(&ndb, hugo_ops)) { no_error= 0; break; } hugo_ops[0]->pkUpdateRecord(&ndb, n_records-1); if (execute_commit(&ndb, hugo_ops)) { no_error= 0; break; } if(close_transaction(&ndb, hugo_ops)) { no_error= 0; break; } } while(0); // copy events and verify do { if (copy_events(&ndb) < 0) { no_error= 0; break; } if (verify_copy(&ndb, pTabs, pShadowTabs)) { no_error= 0; break; } } while (0); { NdbRestarts restarts; for (int j= 0; j < 10; j++) { // restart a node if (no_error) { int timeout = 240; if (restarts.executeRestart("RestartRandomNodeAbort", timeout)) { no_error= 0; break; } } // update all n_records records on all tables if (start_transaction(&ndb, hugo_ops)) { no_error= 0; break; } for (int r= 0; r < n_records; r++) { for (i= 0; pTabs[i]; i++) { hugo_ops[i]->pkUpdateRecord(&ndb, r); } } if (execute_commit(&ndb, hugo_ops)) { no_error= 0; break; } if(close_transaction(&ndb, hugo_ops)) { no_error= 0; break; } // copy events and verify if (copy_events(&ndb) < 0) { no_error= 0; break; } if (verify_copy(&ndb, pTabs, pShadowTabs)) { no_error= 0; break; } } } // drop the event operations for (i= 0; i < (int)pOps.size(); i++) { if (ndb.dropEventOperation(pOps[i])) { no_error= 0; } } if (no_error) DBUG_RETURN(NDBT_ProgramExit(NDBT_OK)); DBUG_RETURN(NDBT_ProgramExit(NDBT_FAILED)); }
struct btrfs_trans_handle *btrfs_start_ioctl_transaction(struct btrfs_root *r, int num_blocks) { return start_transaction(r, 0, TRANS_USERSPACE); }
void LMDBFileIndex::put_internal(const SIndexKey& key, int64 value, int flags, bool log, bool handle_enosp) { CWData vdata; vdata.addVarInt(value); MDB_val mdb_tkey; mdb_tkey.mv_data=const_cast<void*>(static_cast<const void*>(&key)); mdb_tkey.mv_size=sizeof(SIndexKey); MDB_val mdb_tvalue; mdb_tvalue.mv_data=vdata.getDataPtr(); mdb_tvalue.mv_size=vdata.getDataSize(); int rc = mdb_put(txn, dbi, &mdb_tkey, &mdb_tvalue, flags); if(rc==MDB_MAP_FULL && handle_enosp) { mdb_txn_abort(txn); if(_has_error) { Server->Log("LMDB had error during increase (on put). Aborting...", LL_ERROR); start_transaction(); return; } { read_transaction_lock.reset(); IScopedWriteLock lock(mutex); destroy_env(); map_size*=2; Server->Log("Increased LMDB database size to "+PrettyPrintBytes(map_size)+" (on put)", LL_DEBUG); if(!create_env()) { Server->Log("Error creating env after database file size increase", LL_ERROR); _has_error=true; start_transaction(); return; } } start_transaction(); replay_transaction_log(); put_internal(key, value, flags, false, true); } else if(rc==MDB_BAD_TXN && handle_enosp) { mdb_txn_abort(txn); if(_has_error) { Server->Log("LMDB had error on BAD_TXN (on put). Aborting...", LL_ERROR); start_transaction(); return; } start_transaction(); replay_transaction_log(); put_internal(key, value, flags, false, false); } else if(rc) { Server->Log("LMDB: Failed to put data ("+(std::string)mdb_strerror(rc)+")", LL_ERROR); _has_error=true; } if(!_has_error && log) { STransactionLogItem item = { key, value, flags}; transaction_log.push_back(item); } }
struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root, int num_items) { return start_transaction(root, num_items, TRANS_START); }
struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root, int num_blocks) { return start_transaction(root, 0, TRANS_JOIN); }
void LMDBFileIndex::commit_transaction_internal(bool handle_enosp) { int rc = mdb_txn_commit(txn); if(rc==MDB_MAP_FULL && handle_enosp) { if(_has_error) { Server->Log("LMDB had error during increase (on commit). Aborting...", LL_ERROR); start_transaction(); return; } { read_transaction_lock.reset(); IScopedWriteLock lock(mutex); destroy_env(); map_size*=2; Server->Log("Increased LMDB database size to "+PrettyPrintBytes(map_size)+" (on commit)", LL_DEBUG); if(!create_env()) { Server->Log("Error creating env after database file size increase", LL_ERROR); _has_error=true; start_transaction(); return; } } start_transaction(); replay_transaction_log(); commit_transaction_internal(false); } else if(rc==MDB_BAD_TXN && handle_enosp) { if(_has_error) { Server->Log("LMDB had error on BAD_TXN (on commit). Aborting...", LL_ERROR); start_transaction(); return; } start_transaction(); replay_transaction_log(); commit_transaction_internal(false); } else if(rc) { Server->Log("LMDB: Failed to commit transaction ("+(std::string)mdb_strerror(rc)+")", LL_ERROR); _has_error=true; } read_transaction_lock.reset(); transaction_log.clear(); }
void LMDBFileIndex::del_internal(const SIndexKey& key, bool log, bool handle_enosp) { MDB_val mdb_tkey; mdb_tkey.mv_data=const_cast<void*>(static_cast<const void*>(&key)); mdb_tkey.mv_size=sizeof(SIndexKey); int rc = mdb_del(txn, dbi, &mdb_tkey, NULL); if(rc==MDB_MAP_FULL && handle_enosp) { mdb_txn_abort(txn); if(_has_error) { Server->Log("LMDB had error during increase (on del). Aborting...", LL_ERROR); start_transaction(); return; } { read_transaction_lock.reset(); IScopedWriteLock lock(mutex); destroy_env(); map_size*=2; Server->Log("Increased LMDB database size to "+PrettyPrintBytes(map_size)+" (on delete)", LL_DEBUG); if(!create_env()) { Server->Log("Error creating env after database file size increase", LL_ERROR); _has_error=true; start_transaction(); return; } } start_transaction(); replay_transaction_log(); del(key); } else if(rc==MDB_BAD_TXN && handle_enosp) { mdb_txn_abort(txn); if(_has_error) { Server->Log("LMDB had error on BAD_TXN (on del). Aborting...", LL_ERROR); start_transaction(); return; } start_transaction(); replay_transaction_log(); del_internal(key, true, false); } else if (rc == MDB_NOTFOUND) { FILEENTRY_DEBUG(Server->Log("LMDB: Failed to delete data (" + (std::string)mdb_strerror(rc) + ")", LL_ERROR)); } else if(rc) { Server->Log("LMDB: Failed to delete data ("+(std::string)mdb_strerror(rc)+")", LL_ERROR); _has_error=true; } if(log) { STransactionLogItem item = { key, 0, 0 }; transaction_log.push_back(item); } }
/* ** Logout of the BIDS2 system ** ** Returns - 0 - Could not connect to logout. ** 1 - Logout successful. */ int logout(INT2 reason,struct session * s) { int err; char credentials[16]; time_t logintime; int authsocket; struct transaction t; INT2 transactiontype; s->localaddr.sin_port = htons(0); authsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); err = bind(authsocket,(struct sockaddr *)&s->localaddr,sizeof(struct sockaddr_in)); if(err) { socketerror(s,"Error binding logout auth socket"); closesocket(authsocket); return 0; } err = connect(authsocket,(struct sockaddr *)&s->authhost,sizeof(struct sockaddr_in)); if(err) { socketerror(s,"Error connecting logout auth socket"); closesocket(authsocket); return 0; } /* ** start the negotiation */ start_transaction(&t,T_MSG_LOGOUT_REQ,s->sessionid); add_field_string(s,&t,T_PARAM_USERNAME,s->username); add_field_INT2(s,&t,T_PARAM_CLIENT_VERSION,LOGIN_VERSION * 100); add_field_string(s,&t,T_PARAM_OS_IDENTITY,s->osname); add_field_string(s,&t,T_PARAM_OS_VERSION,s->osrelease); add_field_INT2(s,&t,T_PARAM_REASON_CODE,reason); send_transaction(s,authsocket,&t); transactiontype = receive_transaction(s,authsocket,&t); if(transactiontype != T_MSG_AUTH_RESP) { s->critical("logic error"); } if(!extract_valueINT2(s,&t,T_PARAM_HASH_METHOD,&s->hashmethod)) { s->critical("AUTH: no hashmethod"); } if(!extract_valuestring(s,&t,T_PARAM_NONCE,s->nonce)) { s->critical("Auth: no nonce"); } if(s->hashmethod == T_AUTH_MD5_HASH) { genmd5(s->password,strlen(s->password),s->password); } start_transaction(&t,T_MSG_LOGOUT_AUTH_RESP,s->sessionid); s->timestamp = time(NULL); makecredentials(credentials,s,T_MSG_LOGOUT_AUTH_RESP,s->timestamp); add_field_data(s,&t,T_PARAM_AUTH_CREDENTIALS,credentials,16); add_field_INT4(s,&t,T_PARAM_TIMESTAMP,s->timestamp); send_transaction(s,authsocket,&t); transactiontype = receive_transaction(s,authsocket,&t); if(transactiontype != T_MSG_LOGOUT_RESP) { s->critical("logic error"); } extract_valueINT2(s,&t,T_PARAM_STATUS_CODE,&s->retcode); switch(s->retcode) { case T_STATUS_SUCCESS: case T_STATUS_LOGOUT_SUCCESSFUL_ALREADY_DISCONNECTED: break; case T_STATUS_USERNAME_NOT_FOUND: s->critical("Login failure: username not known"); case T_STATUS_INCORRECT_PASSWORD: s->critical("Login failure: incorrect password"); case T_STATUS_ACCOUNT_DISABLED: s->critical("Login failure: disabled"); case T_STATUS_LOGIN_RETRY_LIMIT: case T_STATUS_USER_DISABLED: case T_STATUS_FAIL_USERNAME_VALIDATE: case T_STATUS_FAIL_PASSWORD_VALIDATE: case T_STATUS_LOGIN_UNKNOWN: s->critical("Login failure: other error"); } extract_valueINT2(s,&t,T_PARAM_LOGOUT_SERVICE_PORT,&s->logoutport); extract_valueINT2(s,&t,T_PARAM_STATUS_SERVICE_PORT,&s->statusport); extract_valuestring(s,&t,T_PARAM_TSMLIST,s->tsmlist); extract_valuestring(s,&t,T_PARAM_RESPONSE_TEXT,s->resptext); logintime = time(NULL); s->debug(0,"Logged out successful at %s",asctime(localtime(&logintime))); closesocket(authsocket); return 1; }
/* ** Login to the Authentication server ** ** Returns - 0 - failed to login for some reason. ** 1 - Logged in successfully */ int login(struct session * s) { int err; char credentials[16]; time_t logintime; int authsocket; struct transaction t; INT2 transactiontype; int addrsize; s->localaddr.sin_port = htons(0); authsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); err = bind(authsocket,(struct sockaddr *)&s->localaddr,sizeof(struct sockaddr_in)); if(err) { socketerror(s,"Error binding auth socket"); closesocket(authsocket); return 0; } err = connect(authsocket,(struct sockaddr *)&s->authhost,sizeof(struct sockaddr_in)); if(err) { socketerror(s,"Cant connect to auth server"); closesocket(authsocket); return 0; } addrsize = sizeof(struct sockaddr_in); err = getsockname(authsocket,(struct sockaddr *)&s->localipaddress,&addrsize); /* ** start the negotiation */ start_transaction(&t,T_MSG_PROTOCOL_NEG_REQ,s->sessionid); add_field_INT2(s,&t,T_PARAM_CLIENT_VERSION,LOGIN_VERSION * 100); add_field_string(s,&t,T_PARAM_OS_IDENTITY,s->osname); add_field_string(s,&t,T_PARAM_OS_VERSION,s->osrelease); add_field_INT2(s,&t,T_PARAM_PROTOCOL_LIST,T_PROTOCOL_CHAL); send_transaction(s,authsocket,&t); transactiontype = receive_transaction(s,authsocket,&t); if(transactiontype != T_MSG_PROTOCOL_NEG_RESP) { s->debug(0,"T_MSG_PROTOCOL_NEG_RESP - error transaction type (%d)",transactiontype); return 0; } extract_valueINT2(s,&t,T_PARAM_STATUS_CODE,&s->retcode); extract_valuestring(s,&t,T_PARAM_LOGIN_SERVER_HOST,s->loginserverhost); extract_valueINT2(s,&t,T_PARAM_PROTOCOL_SELECT,&s->protocol); if(s->protocol != T_PROTOCOL_CHAL) { s->debug(0,"T_MSG_PROTOCOL_NEG_RESP - Unsupported protocol (%d)",s->protocol); return 0; } switch(s->retcode) { case T_STATUS_SUCCESS: case T_STATUS_LOGIN_SUCCESS_SWVER: break; case T_STATUS_LOGIN_FAIL_SWVER: { s->debug(0,"T_MSG_PROTOCOL_NEG_RESP - Login failure: software version"); return 0; } case T_STATUS_LOGIN_FAIL_INV_PROT: { s->debug(0,"T_MSG_PROTOCOL_NEG_RESP - Login failure: invalid protocol"); return 0; } case T_STATUS_LOGIN_UNKNOWN: { s->debug(0,"T_MSG_PROTOCOL_NEG_RESP - Login failure: unknown"); return 0; } } closesocket(authsocket); authsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); err = bind(authsocket,(struct sockaddr *)&s->localaddr,sizeof(struct sockaddr_in)); if(err) { socketerror(s,"Error binding auth socket 2"); closesocket(authsocket); return 0; } err = connect(authsocket,(struct sockaddr *)&s->authhost,sizeof(struct sockaddr_in)); if(err) { socketerror(s,"Error connecting auth socket 2"); closesocket(authsocket); return 0; } start_transaction(&t,T_MSG_LOGIN_REQ,s->sessionid); add_field_string(s,&t,T_PARAM_USERNAME,s->username); add_field_INT2(s,&t,T_PARAM_CLIENT_VERSION,LOGIN_VERSION * 100); add_field_string(s,&t,T_PARAM_OS_IDENTITY,s->osname); add_field_string(s,&t,T_PARAM_OS_VERSION,s->osrelease); add_field_INT2(s,&t,T_PARAM_REASON_CODE,T_LOGIN_REASON_CODE_NORMAL); add_field_INT2(s,&t,T_PARAM_REQ_PORT,s->listenport); send_transaction(s,authsocket,&t); transactiontype = receive_transaction(s,authsocket,&t); if(transactiontype == T_MSG_LOGIN_RESP) goto skippo; if(transactiontype != T_MSG_AUTH_RESP) { s->debug(0,"T_MSG_AUTH_RESP - error transaction type (%d)",transactiontype); return 0; } if(!extract_valueINT2(s,&t,T_PARAM_HASH_METHOD,&s->hashmethod)) { s->debug(0,"T_MSG_AUTH_RESP - no hashmethod provided"); return 0; } if(!extract_valuestring(s,&t,T_PARAM_NONCE,s->nonce)) { s->debug(0,"T_MSG_AUTH_RESP - no nonce supplied"); return 0; } if(s->hashmethod == T_AUTH_MD5_HASH) { genmd5(s->password,strlen(s->password),s->password); } start_transaction(&t,T_MSG_LOGIN_AUTH_REQ,s->sessionid); s->timestamp = time(NULL); makecredentials(credentials,s,T_MSG_LOGIN_AUTH_REQ,s->timestamp); add_field_data(s,&t,T_PARAM_AUTH_CREDENTIALS,credentials,16); add_field_INT4(s,&t,T_PARAM_TIMESTAMP,s->timestamp); send_transaction(s,authsocket,&t); transactiontype = receive_transaction(s,authsocket,&t); skippo: if(transactiontype != T_MSG_LOGIN_RESP) { s->debug(0,"T_MSG_LOGIN_RESP - error transaction type (%d)",transactiontype); return 0; } extract_valueINT2(s,&t,T_PARAM_STATUS_CODE,&s->retcode); switch(s->retcode) { case T_STATUS_SUCCESS: case T_STATUS_LOGIN_SUCCESSFUL_SWVER: case T_STATUS_LOGIN_SUCCESSFUL_ALREADY_LOGGED_IN: break; case T_STATUS_USERNAME_NOT_FOUND: { s->debug(0,"T_MSG_LOGIN_RESP - Login failure: username not known"); return 0; } case T_STATUS_INCORRECT_PASSWORD: { s->debug(0,"T_MSG_LOGIN_RESP - Login failure: incorrect password"); return 0; } case T_STATUS_ACCOUNT_DISABLED: { s->debug(0,"T_MSG_LOGIN_RESP - Login failure: Account disabled"); return 0; } case T_STATUS_LOGIN_RETRY_LIMIT: case T_STATUS_USER_DISABLED: case T_STATUS_FAIL_USERNAME_VALIDATE: case T_STATUS_FAIL_PASSWORD_VALIDATE: case T_STATUS_LOGIN_UNKNOWN: { s->debug(0,"T_MSG_LOGIN_RESP - Login failure: other error"); return 0; } } extract_valueINT2(s,&t,T_PARAM_LOGOUT_SERVICE_PORT,&s->logoutport); extract_valueINT2(s,&t,T_PARAM_STATUS_SERVICE_PORT,&s->statusport); extract_valuestring(s,&t,T_PARAM_TSMLIST,s->tsmlist); extract_valuestring(s,&t,T_PARAM_RESPONSE_TEXT,s->resptext); { int i,n; char * p = s->tsmlist; char t[200]; s->tsmcount = 0; while((n = strcspn(p," ,"))!=0) { strncpy(t,p,n); t[n] = 0; p += n +1; strcpy(s->tsmlist_s[s->tsmcount],t); strcat(s->tsmlist_s[s->tsmcount++],s->authdomain); } for(i=0;i<s->tsmcount;i++) { struct hostent * he; he = gethostbyname(s->tsmlist_s[i]); if(he) { s->tsmlist_in[i].sin_addr.s_addr = *((int*)(he->h_addr_list[0])); } else { s->tsmlist_in[i].sin_addr.s_addr = inet_addr(s->tsmlist_s[i]); } s->debug(1,"Will accept heartbeats from %s = %s\n",s->tsmlist_s[i],inet_ntoa(s->tsmlist_in[i].sin_addr)); } } logintime = time(NULL); s->debug(0,"Logged on as %s - successful at %s",s->username,asctime(localtime(&logintime))); s->sequence = 0; s->lastheartbeat = time(NULL); s->recenthb = 0; closesocket(authsocket); return 1; }
/* ** Handle heartbeats, wait for the following events to happen - ** ** 1. A heartbeat packet arrives, in which case we reply correctly ** 2. A timeout occured (ie no heartbeat arrived within 7 minutes) ** 3. The socket was closed. ** ** Returns - 0 - Heartbeat timeout, and subsequent login failed to connect ** 1 - Socket closed on us, presuming the user wants to shut down. */ int handle_heartbeats(struct session *s) { INT2 transactiontype; struct transaction t; while(1) { transactiontype = receive_udp_transaction(s,s->listensock,&t,&s->fromaddr); if(transactiontype == 0xffff) { s->debug(0,"Timed out waiting for heartbeat - logging on\n"); if(!login(s)) return 0; } else if(transactiontype == 0xfffd) { s->debug(0,"Badly structured packet received - discarding\n"); } else if(transactiontype == 0xfffe) { s->debug(0,"Socket closed - shutting down\n"); return 1; } else if(transactiontype == T_MSG_STATUS_REQ) { char buf[16]; start_transaction(&t,T_MSG_STATUS_RESP,s->sessionid); add_field_INT2(s,&t,T_PARAM_STATUS_CODE,T_STATUS_TRANSACTION_OK); s->sequence++; makecredentials(buf,s,T_MSG_STATUS_RESP,s->sequence); add_field_data(s,&t,T_PARAM_STATUS_AUTH,buf,16); add_field_INT4(s,&t,T_PARAM_SEQNUM,s->sequence); send_udp_transaction(s,&t); s->lastheartbeat = time(NULL); s->debug(1,"Responded to heartbeat at %s",asctime(localtime(&s->lastheartbeat))); } else if(transactiontype == T_MSG_RESTART_REQ) { s->debug(0,"Restart request - unimplemented"); return 0; } else { /* ** Melbourne servers were sending spurious UDP packets after authentication ** This works around it. */ s->debug(0,"Unknown heartbeat message %d ",transactiontype); } } /* ** Should never get here */ return 0; }
void test_binlog(TestConnections* Test) { int i; MYSQL* binlog; Test->repl->connect(); Test->set_timeout(100); Test->try_query(Test->repl->nodes[0], (char *) "SET NAMES utf8mb4"); Test->try_query(Test->repl->nodes[0], (char *) "set autocommit=1"); Test->try_query(Test->repl->nodes[0], (char *) "select USER()"); Test->set_timeout(100); create_t1(Test->repl->nodes[0]); Test->add_result(insert_into_t1(Test->repl->nodes[0], 4), "Data inserting to t1 failed\n"); Test->stop_timeout(); Test->tprintf("Sleeping to let replication happen\n"); sleep(60); for (i = 0; i < Test->repl->N; i++) { Test->tprintf("Checking data from node %d (%s)\n", i, Test->repl->IP[i]); Test->set_timeout(100); Test->add_result(select_from_t1(Test->repl->nodes[i], 4), "Selecting from t1 failed\n"); Test->stop_timeout(); } Test->set_timeout(10); Test->tprintf("First transaction test (with ROLLBACK)\n"); start_transaction(Test); Test->set_timeout(50); Test->tprintf("SELECT * FROM t1 WHERE fl=10, checking inserted values\n"); Test->add_result(execute_query_check_one(Test->repl->nodes[0], (char *) "SELECT * FROM t1 WHERE fl=10", "111"), "SELECT check failed\n"); //Test->add_result(check_sha1(Test), "sha1 check failed\n"); Test->tprintf("ROLLBACK\n"); Test->try_query(Test->repl->nodes[0], (char *) "ROLLBACK"); Test->tprintf("INSERT INTO t1 VALUES(112, 10)\n"); Test->try_query(Test->repl->nodes[0], (char *) "INSERT INTO t1 VALUES(112, 10)"); Test->try_query(Test->repl->nodes[0], (char *) "COMMIT"); Test->stop_timeout(); sleep(20); Test->set_timeout(20); Test->tprintf("SELECT * FROM t1 WHERE fl=10, checking inserted values\n"); Test->add_result(execute_query_check_one(Test->repl->nodes[0], (char *) "SELECT * FROM t1 WHERE fl=10", "112"), "SELECT check failed\n"); Test->tprintf("SELECT * FROM t1 WHERE fl=10, checking inserted values from slave\n"); Test->add_result(execute_query_check_one(Test->repl->nodes[2], (char *) "SELECT * FROM t1 WHERE fl=10", "112"), "SELECT check failed\n"); Test->tprintf("DELETE FROM t1 WHERE fl=10\n"); Test->try_query(Test->repl->nodes[0], (char *) "DELETE FROM t1 WHERE fl=10"); Test->tprintf("Checking t1\n"); Test->add_result(select_from_t1(Test->repl->nodes[0], 4), "SELECT from t1 failed\n"); Test->tprintf("Second transaction test (with COMMIT)\n"); start_transaction(Test); Test->tprintf("COMMIT\n"); Test->try_query(Test->repl->nodes[0], (char *) "COMMIT"); Test->tprintf("SELECT, checking inserted values\n"); Test->add_result(execute_query_check_one(Test->repl->nodes[0], (char *) "SELECT * FROM t1 WHERE fl=10", "111"), "SELECT check failed\n"); Test->tprintf("SELECT, checking inserted values from slave\n"); Test->add_result(execute_query_check_one(Test->repl->nodes[2], (char *) "SELECT * FROM t1 WHERE fl=10", "111"), "SELECT check failed\n"); Test->tprintf("DELETE FROM t1 WHERE fl=10\n"); Test->try_query(Test->repl->nodes[0], (char *) "DELETE FROM t1 WHERE fl=10"); Test->stop_timeout(); Test->set_timeout(50); Test->add_result(check_sha1(Test), "sha1 check failed\n"); Test->repl->close_connections(); Test->stop_timeout(); // test SLAVE STOP/START for (int j = 0; j < 3; j++) { Test->set_timeout(100); Test->repl->connect(); Test->tprintf("Dropping and re-creating t1\n"); Test->try_query(Test->repl->nodes[0], (char *) "DROP TABLE IF EXISTS t1"); create_t1(Test->repl->nodes[0]); Test->tprintf("Connecting to MaxScale binlog router\n"); binlog = open_conn(Test->binlog_port, Test->maxscale_IP, Test->repl->user_name, Test->repl->password, Test->ssl); Test->tprintf("STOP SLAVE against Maxscale binlog\n"); execute_query(binlog, (char *) "STOP SLAVE"); if (j == 1) { Test->tprintf("FLUSH LOGS on master\n"); execute_query(Test->repl->nodes[0], (char *) "FLUSH LOGS"); } Test->add_result(insert_into_t1(Test->repl->nodes[0], 4), "INSERT into t1 failed\n"); Test->tprintf("START SLAVE against Maxscale binlog\n"); Test->try_query(binlog, (char *) "START SLAVE"); Test->tprintf("Sleeping to let replication happen\n"); Test->stop_timeout(); sleep(30); for (i = 0; i < Test->repl->N; i++) { Test->set_timeout(50); Test->tprintf("Checking data from node %d (%s)\n", i, Test->repl->IP[i]); Test->add_result(select_from_t1(Test->repl->nodes[i], 4), "SELECT from t1 failed\n"); } Test->set_timeout(100); Test->add_result(check_sha1(Test), "sha1 check failed\n"); Test->repl->close_connections(); Test->stop_timeout(); } }
struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root, int num_blocks) { return start_transaction(root, num_blocks, 0); }
// --- main -------------------------------------------------------------------- int mainloop (int argc, char *argv []) { FILE *fp = NULL; FILE *tempfp = NULL; sql_stmt_t *stmts = NULL; trace_t *t = NULL; bool_t only_q = FALSE; bool_t append = FALSE; bool_t only_r = FALSE; bool_t dbf_overwrite = FALSE; char *filename = NULL; char *folder = "."; char *dt = NULL; char *dt_filename = NULL; unsigned long partition_interval = PARTITION_INTERVAL_SECS; unsigned long partition_start = 0; int opt_idx = 0; int c = 0; int rc = 0; // command line option parsing struct option long_opts [] = { {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {"append", no_argument, NULL, 'a'}, {"show_schema", no_argument, NULL, 's'}, {"queries_only", no_argument, NULL, 'q'}, {"replies_only", no_argument, NULL, 'r'}, {"database", required_argument, NULL, 'd'}, {"db_overwrite", no_argument, NULL, 'o'}, {"interval", required_argument, NULL, 'i'}, {"db_folder", required_argument, NULL, 'f'}, { NULL, 0, NULL, 0 } }; while ((c = getopt_long (argc, argv, "hvasqrd:n:oi:f:", long_opts, &opt_idx)) != -1) { switch (c) { case 'v': fprintf (stdout, "%s\n", DNS2SQLITE_VERSION); // VERSION defined in dns2sqlite.h exit (0); break; case 's': fprintf (stdout, "%s\n", g_tabledefs); // VERSION defined in dns2sqlite.h exit (0); break; case 'a': append = TRUE; break; case 'q': only_q = TRUE; break; case 'r': only_r = TRUE; break; case 'd': filename = optarg; break; case 'o': dbf_overwrite = TRUE; break; case 'i': partition_interval = strtoul (optarg, NULL, NUM_BASE); partition_interval = (partition_interval < 1 ? 1 : partition_interval) * 60; break; case 'f': folder = optarg; break; default: fprintf (stderr, "Unknown option: %c\n", c); // FALL THRU case 'h': usage (argv [0]); return 0; } } argc -= optind; argv += optind; // handle dangling command line arguments // N.B. this does not work if a pipe and a file is used at the same time. // If files are given then they should be processed before the pipe is read // from stdin. That is, while argc > 0 open each file and go to the main // loop. When argc = 0 then open stdin and go to the main loop: // // while (argc > 0) { // fp = fopen (argv [argc -1], "r"); // if (fp == NULL) {return FAILURE} // else {read_file (fp, ...);} // fclose (fp); // argc--; // } // fp = stdin; switch (argc) { case 0: fp = stdin; break; case 1: fp = fopen (argv [argc -1], "r"); if (fp == NULL) { perror (argv [argc -1]); return 1; } break; default: usage (argv [0]); return 1; } if (filename == NULL) { fprintf (stderr, "Error: No database specified \n"); } // main loop // This should at least be moved into its own function. while ((t = parse_line (fp)) != NULL) { partition_start = p_start (partition_start, t->s, partition_interval); if ((unsigned long) t->s >= (partition_start + partition_interval)) { rc = commit ((stmts + COMMIT)->pstmt); close_db (G_DB); G_DB = NULL; rc = chdir (".."); if (rc == -1) { perror (NULL); return FAILURE; } partition_start += partition_interval; } // check if database is open if (!isdbopen (G_DB)) { // create directory name if (dt) XFREE(dt); dt = sec_to_datetime_str (partition_start); if (!dt) return FAILURE; // generate path if (dt_filename) XFREE(dt_filename); dt_filename = make_dt_filename (dt, filename); if (dt_filename == NULL) { XFREE(dt); return FAILURE; } // create directory if (make_db_dir (dt, folder) != SUCCESS) { XFREE(dt); XFREE(dt_filename); return FAILURE; } XFREE(dt); if (dbf_overwrite) { rc = unlink(dt_filename); if (rc==0) d2log (LOG_ERR|LOG_USER, "Unlinked file %s (due to overwrite flag).",dt_filename); else { rc = errno; if (rc != ENOENT) { d2log (LOG_ERR|LOG_USER, "Failed to unlink %s (overwrite) file code %d.",dt_filename,rc); XFREE(dt); XFREE(dt_filename); return FAILURE; } } } else { if (append == FALSE) { // simplistic test whether the database file exists tempfp = fopen (dt_filename, "r"); if (tempfp) { d2log (LOG_ERR|LOG_USER, "Error: Database file %s exists ! ( use -a to append or -o owerwrite ).",dt_filename); fclose (tempfp); return FAILURE; } } } if (!open_db (dt_filename, &G_DB, append)) { d2log (LOG_ERR|LOG_USER, "Failed to create new db %s.",dt_filename); XFREE(dt_filename); return FAILURE; } if (!prepare_stmts (G_DB, &stmts)) { d2log (LOG_ERR|LOG_USER, "Failed to prepare sql statements for db: %s.",dt_filename); close_db (G_DB); return FAILURE; } rc = start_transaction ((stmts + BEGIN_TRANS)->pstmt); } if (!store_to_db (G_DB, stmts, t, only_q, only_r)) { d2log (LOG_ERR|LOG_USER, "Failed to store data to db.\n"); } trace_free (t); } // clean up before exit fclose (fp); rc = commit ((stmts + COMMIT)->pstmt); close_db (G_DB); }
/* * Called at inode eviction from icache */ void ext3_evict_inode (struct inode *inode) { struct ext3_inode_info *ei = EXT3_I(inode); struct ext3_block_alloc_info *rsv; handle_t *handle; int want_delete = 0; trace_ext3_evict_inode(inode); if (!inode->i_nlink && !is_bad_inode(inode)) { dquot_initialize(inode); want_delete = 1; } /* * When journalling data dirty buffers are tracked only in the journal. * So although mm thinks everything is clean and ready for reaping the * inode might still have some pages to write in the running * transaction or waiting to be checkpointed. Thus calling * journal_invalidatepage() (via truncate_inode_pages()) to discard * these buffers can cause data loss. Also even if we did not discard * these buffers, we would have no way to find them after the inode * is reaped and thus user could see stale data if he tries to read * them before the transaction is checkpointed. So be careful and * force everything to disk here... We use ei->i_datasync_tid to * store the newest transaction containing inode's data. * * Note that directories do not have this problem because they don't * use page cache. * * The s_journal check handles the case when ext3_get_journal() fails * and puts the journal inode. */ if (inode->i_nlink && ext3_should_journal_data(inode) && EXT3_SB(inode->i_sb)->s_journal && (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) && inode->i_ino != EXT3_JOURNAL_INO) { tid_t commit_tid = atomic_read(&ei->i_datasync_tid); journal_t *journal = EXT3_SB(inode->i_sb)->s_journal; log_start_commit(journal, commit_tid); log_wait_commit(journal, commit_tid); filemap_write_and_wait(&inode->i_data); } truncate_inode_pages(&inode->i_data, 0); ext3_discard_reservation(inode); rsv = ei->i_block_alloc_info; ei->i_block_alloc_info = NULL; if (unlikely(rsv)) kfree(rsv); if (!want_delete) goto no_delete; handle = start_transaction(inode); if (IS_ERR(handle)) { /* * If we're going to skip the normal cleanup, we still need to * make sure that the in-core orphan linked list is properly * cleaned up. */ ext3_orphan_del(NULL, inode); goto no_delete; } if (IS_SYNC(inode)) handle->h_sync = 1; inode->i_size = 0; if (inode->i_blocks) ext3_truncate(inode); /* * Kill off the orphan record created when the inode lost the last * link. Note that ext3_orphan_del() has to be able to cope with the * deletion of a non-existent orphan - ext3_truncate() could * have removed the record. */ ext3_orphan_del(handle, inode); ei->i_dtime = get_seconds(); /* * One subtle ordering requirement: if anything has gone wrong * (transaction abort, IO errors, whatever), then we can still * do these next steps (the fs will already have been marked as * having errors), but we can't free the inode if the mark_dirty * fails. */ if (ext3_mark_inode_dirty(handle, inode)) { /* If that failed, just dquot_drop() and be done with that */ dquot_drop(inode); clear_inode(inode); } else { ext3_xattr_delete_inode(handle, inode); dquot_free_inode(inode); dquot_drop(inode); clear_inode(inode); ext3_free_inode(handle, inode); } ext3_journal_stop(handle); return; no_delete: clear_inode(inode); dquot_drop(inode); }
struct btrfs_trans_handle *btrfs_start_ioctl_transaction(struct btrfs_root *r, int num_blocks) { return start_transaction(r, num_blocks, 2); }
int main ( int argc, char **argv ) { int ret = check_args(argc, argv); if (ret) { printf("invalid argument error!\n"); return -1; } if (new_db) { unlink(db_name); } soft_heap_limit = sqlite3_soft_heap_limit64(soft_heap_limit); if ( soft_heap_limit < 0 ) { ret = soft_heap_limit; printf("sqlite3_soft_heap_limit() error: %x", ret); } else { printf("sqlite3_soft_heap_limit64(): prev: %ld (byte) is set to: %lld (byte).\n", soft_heap_limit, sqlite3_soft_heap_limit64(-1)); } sqlite3 *db = NULL; ret = sqlite3_open_v2 (db_name, &db, SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE, NULL); if ( ret != SQLITE_OK ) { printf ( "Can't open database: %s\n", sqlite3_errmsg ( db ) ); return -1; } if (new_db) { // create table, transaction is useful for speed optimization printf("== execute sql_create_table ==\n"); exec_sql_list_in_transaction(db, sql_create_table); } else { printf("== use existing db: %s ==\n", db_name); } int sql_count = 0; int trans_count = 0; uint64_t total_time = 0; int64_t max_highwater = 0; uint64_t total_highwater = 0; do { uint64_t start_time = sceKernelGetProcessTime(); ret = start_transaction(db); if (ret) { printf("start_transaction() err: %x\n", ret); break; } int trans_sql_count = 0; trans_count++; do { fill_sql(sql_count); ret = exec_sql(db, sql_buf); if (ret) { break; } sql_count++; trans_sql_count++; } while (sql_count < total_sql_num && trans_sql_count < max_sql_in_trans); ret = end_transaction(db, ret); if (ret) { printf("end_transaction() err: %x\n", ret); break; } uint64_t end_time = sceKernelGetProcessTime(); total_time += end_time - start_time; printf("[%d] th transaction is end. operated sql num: %d, time: %lu (us)", trans_count, sql_count, end_time - start_time); printf("\t: sqlite3_memory_used(): %lld", sqlite3_memory_used()); int64_t highwater = sqlite3_memory_highwater(true); if (max_highwater < highwater) { max_highwater = highwater; } total_highwater += highwater; printf("\t: sqlite3_memory_highwater(true): %ld\n", highwater); } while (sql_count < total_sql_num); printf("operated sql count: %d, transaction count: %d\n", sql_count, trans_count); printf("total elapsed time: %lu (us)\n", total_time); if (trans_count != 0) { printf("maximum memory highwater: %ld, average high water / transaction: %lu\n", max_highwater, total_highwater / trans_count); } /* // select const char *sql_select[] = { "SELECT * FROM tbl1;", // select all "SELECT id, c1_int FROM tbl1 WHERE 1 < id;", // select 1 < id NULL, // terminater }; printf("\n== execute sql_select ==\n"); exec_sql(db, sql_select); */ sqlite3_close ( db ); return 0; }