Пример #1
0
void IridiumSBD::start_sbd_session(void)
{
	if ((_state != SATCOM_STATE_STANDBY) || (_new_state != SATCOM_STATE_STANDBY)) {
		VERBOSE_INFO("CANNOT ENTER SBD SESSION STATE");
		return;

	} else {
		VERBOSE_INFO("STARTING SBD SESSION");
	}

	if (!is_modem_ready()) {
		VERBOSE_INFO("SBD SESSION: MODEM NOT READY!");
		return;
	}

	if (_ring_pending) {
		write_at("AT+SBDIXA");

	} else {
		write_at("AT+SBDIX");
	}

	_new_state = SATCOM_STATE_SBDSESSION;

	pthread_mutex_lock(&_tx_buf_mutex);

	_session_start_time = hrt_absolute_time();
}
Пример #2
0
void IridiumSBD::csq_loop(void)
{
	int res = read_at_command();

	if (res == SATCOM_RESULT_NA) {
		return;
	}

	if (res != SATCOM_RESULT_OK) {
		VERBOSE_INFO("UPDATE SIGNAL QUALITY: ERROR");

		_new_state = SATCOM_STATE_STANDBY;
		return;
	}

	if (strncmp((const char *)_rx_command_buf, "+CSQ:", 5)) {
		VERBOSE_INFO("UPDATE SIGNAL QUALITY: WRONG ANSWER:");
		VERBOSE_INFO("%s", _rx_command_buf);

		_new_state = SATCOM_STATE_STANDBY;
		return;
	}

	_signal_quality = _rx_command_buf[5] - 48;

	VERBOSE_INFO("SIGNAL QUALITY: %d", _signal_quality);

	_new_state = SATCOM_STATE_STANDBY;
}
Пример #3
0
void IridiumSBD::read_rx_buf(void)
{
	if (!is_modem_ready()) {
		VERBOSE_INFO("READ SBD: MODEM NOT READY!");
		return;
	}

	pthread_mutex_lock(&_rx_buf_mutex);


	write_at("AT+SBDRB");

	if (read_at_msg() != SATCOM_RESULT_OK) {
		VERBOSE_INFO("READ SBD: MODEM NOT RESPONDING!");
		_rx_msg_read_idx = _rx_msg_end_idx;
		pthread_mutex_unlock(&_rx_buf_mutex);
		return;
	}

	int data_len = (_rx_msg_buf[0] << 8) + _rx_msg_buf[1];

	// rx_buf contains 2 byte length, data, 2 byte checksum and /r/n delimiter
	if (data_len != _rx_msg_end_idx - 6) {
		PX4_ERR("READ SBD: WRONG DATA LENGTH");
		_rx_msg_read_idx = _rx_msg_end_idx;
		pthread_mutex_unlock(&_rx_buf_mutex);
		return;
	}

	int checksum = 0;

	for (int i = 2; i < data_len + 2; i++) {
		checksum += _rx_msg_buf[i];
	}

	if ((checksum / 256 != _rx_msg_buf[_rx_msg_end_idx - 4]) || ((checksum & 255) != _rx_msg_buf[_rx_msg_end_idx - 3])) {
		PX4_ERR("READ SBD: WRONG DATA CHECKSUM");
		_rx_msg_read_idx = _rx_msg_end_idx;
		pthread_mutex_unlock(&_rx_buf_mutex);
		return;
	}

	_rx_msg_read_idx = 2;	// ignore the length
	_rx_msg_end_idx -= 4;	// ignore the checksum and delimiter
	_rx_read_pending = false;

	pthread_mutex_unlock(&_rx_buf_mutex);
	VERBOSE_INFO("READ SBD: SUCCESS, LEN: %d", data_len);
}
Пример #4
0
void IridiumSBD::write_at(const char *command)
{
	VERBOSE_INFO("WRITING AT COMMAND: %s", command);

	::write(uart_fd, command, strlen(command));
	::write(uart_fd, "\r", 1);
}
Пример #5
0
ssize_t IridiumSBD::write(struct file *filp, const char *buffer, size_t buflen)
{
	// general check if the incoming message would be too large (the buffer should not reset in that case)
	if ((ssize_t)buflen > SATCOM_TX_BUF_LEN) {
		return PX4_ERROR;
	}

	pthread_mutex_lock(&_tx_buf_mutex);

	// parsing the size of the message to write
	if (!_writing_mavlink_packet) {
		if (buflen < 3) {
			_packet_length = buflen;

		} else if ((unsigned char)buffer[0] == 253 && (buflen == 10)) { // mavlink 2
			const uint8_t payload_len = buffer[1];
			const uint8_t incompat_flags = buffer[2];
			_packet_length = payload_len + 12;
			_writing_mavlink_packet = true;

			if (incompat_flags & 0x1) { //signing
				_packet_length += 13;
			}

		} else if ((unsigned char)buffer[0] == 254 && (buflen == 6)) { // mavlink 1
			const uint8_t payload_len = buffer[1];
			_packet_length = payload_len + 8;
			_writing_mavlink_packet = true;

		} else {
			_packet_length = buflen;
		}
	}

	// check if there is enough space to write the message
	if (SATCOM_TX_BUF_LEN - _tx_buf_write_idx - _packet_length < 0) {
		_tx_buf_write_idx = 0;
		++_num_tx_buf_reset;
	}

	// keep track of the remaining packet length and if the full message is written
	_packet_length -= buflen;

	if (_packet_length == 0) {
		_writing_mavlink_packet = false;
	}

	VERBOSE_INFO("WRITE: LEN %d, TX WRITTEN: %d", buflen, _tx_buf_write_idx);

	memcpy(_tx_buf + _tx_buf_write_idx, buffer, buflen);

	_tx_buf_write_idx += buflen;
	_last_write_time = hrt_absolute_time();
	_tx_buf_write_pending = true;

	pthread_mutex_unlock(&_tx_buf_mutex);

	return buflen;
}
Пример #6
0
static range_obj_t *gen_pop_tree(unsigned int level, range_obj_t* rootObj, unsigned int rdn, unsigned int base,
	unsigned int reminder, SaImmAttrNameT rdnAttName)
{
	int ix;
	range_obj_t *rangeObj = calloc(1, sizeof(range_obj_t));
	unsigned int partition;

	if (level > 2) {
		fprintf(stderr, "error - Level > 2 !!!!\n");
		exit(EXIT_FAILURE);
	}

	if (level == 0) {
		assert(!rootObj && !rdn && base==1);
		strncpy((char *) rangeObj->parentDn.value, rdnAttName, SA_MAX_NAME_LENGTH);
		strncat((char *) rangeObj->parentDn.value, "=", SA_MAX_NAME_LENGTH);
		strncat((char *) rangeObj->parentDn.value, "0", SA_MAX_NAME_LENGTH);
		rangeObj->parentDn.length = strlen((char *) rangeObj->parentDn.value);
	} else {
		rangeObj->parentDn.length = snprintf((char *) rangeObj->parentDn.value,
			sizeof(rangeObj->parentDn.value), "%s=%u,%s",
			rdnAttName, rdn, (char *) rootObj->parentDn.value);
	}

	rangeObj->botRdn = base;

	--reminder;

	if (reminder < 100) {
		rangeObj->topRdn = base + reminder;
		reminder = 0;
	} else {
		rangeObj->topRdn = base + 99;
		reminder -= 100;
	}

	VERBOSE_INFO("Generated level %u rangeObj(%u) %u<-->%u %s\n", level, rdn, rangeObj->botRdn, rangeObj->topRdn,
		rangeObj->parentDn.value);

	partition = (reminder > 10001) ? 10001 : 100;

	ix=0;
	while (reminder && (ix < 100)) {

		unsigned int subreminder = (reminder < partition)?reminder:partition;
		rangeObj->sublevel[ix] = gen_pop_tree(level + 1, rangeObj, /* rdn: */ base + ix, 
			/*new base:*/ base + 100 + (ix)*partition, subreminder, rdnAttName);
		reminder -= subreminder;
		++ix;
	}

	if (reminder) {
		fprintf(stderr, "error - Returning with nonzero reminder r:%u ix:%u\n", reminder, ix);
		abort();
	}

	return rangeObj;
}
Пример #7
0
bool IridiumSBD::clear_mo_buffer()
{
	write_at("AT+SBDD0");

	if (read_at_command() != SATCOM_RESULT_OK || _rx_command_buf[0] != '0') {
		VERBOSE_INFO("CLEAR MO BUFFER: ERROR");
		return false;
	}

	return true;
}
Пример #8
0
void IridiumSBD::start_csq(void)
{
	if ((_state != SATCOM_STATE_STANDBY) || (_new_state != SATCOM_STATE_STANDBY)) {
		VERBOSE_INFO("CANNOT ENTER CSQ STATE");
		return;

	} else {
		VERBOSE_INFO("UPDATING SIGNAL QUALITY");
	}

	_last_signal_check = hrt_absolute_time();

	if (!is_modem_ready()) {
		VERBOSE_INFO("UPDATE SIGNAL QUALITY: MODEM NOT READY!");
		return;
	}

	write_at("AT+CSQ");
	_new_state = SATCOM_STATE_CSQ;
}
Пример #9
0
satcom_uart_status IridiumSBD::open_uart(char *uart_name)
{
	VERBOSE_INFO("opening Iridium SBD modem UART: %s", uart_name);

	uart_fd = ::open(uart_name, O_RDWR | O_BINARY);

	if (uart_fd < 0) {
		VERBOSE_INFO("UART open failed!");
		return SATCOM_UART_OPEN_FAIL;
	}

	// set the UART speed to 115200
	struct termios uart_config;
	tcgetattr(uart_fd, &uart_config);
	cfsetspeed(&uart_config, 115200);
	tcsetattr(uart_fd, TCSANOW, &uart_config);

	VERBOSE_INFO("UART opened");

	return SATCOM_UART_OK;
}
Пример #10
0
void IridiumSBD::write_tx_buf()
{
	if (!is_modem_ready()) {
		VERBOSE_INFO("WRITE SBD: MODEM NOT READY!");
		return;
	}

	pthread_mutex_lock(&_tx_buf_mutex);

	char command[13];
	sprintf(command, "AT+SBDWB=%d", _tx_buf_write_idx);
	write_at(command);

	if (read_at_command() != SATCOM_RESULT_READY) {
		VERBOSE_INFO("WRITE SBD: MODEM NOT RESPONDING!");
		pthread_mutex_unlock(&_tx_buf_mutex);
		return;
	}

	int sum = 0;

	int written = 0;

	while (written != _tx_buf_write_idx) {
		written += ::write(uart_fd, _tx_buf + written, _tx_buf_write_idx - written);
	}

	for (int i = 0; i < _tx_buf_write_idx; i++) {
		sum += _tx_buf[i];
	}

	uint8_t checksum[2] = {(uint8_t)(sum / 256), (uint8_t)(sum & 255)};
	::write(uart_fd, checksum, 2);


	VERBOSE_INFO("SEND SBD: CHECKSUM %d %d", checksum[0], checksum[1]);

	if (read_at_command(250) != SATCOM_RESULT_OK) {
		VERBOSE_INFO("WRITE SBD: ERROR WHILE WRITING DATA TO MODEM!");

		pthread_mutex_unlock(&_tx_buf_mutex);
		return;
	}

	if (_rx_command_buf[0] != '0') {

		VERBOSE_INFO("WRITE SBD: ERROR WHILE WRITING DATA TO MODEM! (%d)", _rx_command_buf[0] - '0');

		pthread_mutex_unlock(&_tx_buf_mutex);
		return;
	}

	VERBOSE_INFO("WRITE SBD: DATA WRITTEN TO MODEM");

	_tx_buf_write_pending = false;

	pthread_mutex_unlock(&_tx_buf_mutex);

	_tx_session_pending = true;
}
Пример #11
0
static void generate_pop(range_obj_t* rootObj, SaImmCcbHandleT ccbHandle, const SaImmClassNameT className,
	SaImmAttrNameT rdnAttName, SaImmValueTypeT rdnAttType, SaImmAdminOwnerHandleT ownerHandle)
{
	SaAisErrorT err = SA_AIS_OK;
	unsigned int ix;
	unsigned int rdn = rootObj->botRdn;
	SaNameT rdnAttrVal;
	unsigned int retries = 0;
	const SaNameT* objectNames[] = {&(rootObj->parentDn), NULL};

	for (ix = 0; ix < 100 && rdn <= rootObj->topRdn; ++ix, ++rdn) {
		rdnAttrVal.length = snprintf((char *) rdnAttrVal.value,
			sizeof(rdnAttrVal.value), "%s=%u", rdnAttName, rdn);

		ccb_create_obj(&rootObj->parentDn, &rdnAttrVal, ccbHandle, className, rdnAttName, rdnAttType);
	}

	do {
		err = saImmOmCcbApply(ccbHandle);
		if(err == SA_AIS_ERR_TRY_AGAIN) {
			usleep(250 * 1000);
		}
	} while ((err == SA_AIS_ERR_TRY_AGAIN) && (retries < 15));

	if (err != SA_AIS_OK) {
		fprintf(stderr, "error - Failed to apply ccb for parent:%s range %u<->%u, error:%s\n",
			(char *) rootObj->parentDn.value, rootObj->botRdn, rootObj->topRdn, saf_error(err));
		exit(1);
	}

	VERBOSE_INFO("successfull Apply for parent %s range %u<->%u\n", 
		(char *) rootObj->parentDn.value, rootObj->botRdn, rootObj->topRdn);

	for (ix = 0; ix < 100 && rootObj->sublevel[ix]; ++ix) {
		generate_pop(rootObj->sublevel[ix], ccbHandle, className, rdnAttName, rdnAttType, ownerHandle);
	}

	err = saImmOmAdminOwnerRelease(ownerHandle, objectNames, SA_IMM_ONE);
	if (err != SA_AIS_OK) {
		fprintf(stderr, "error - Failed to release admo - ignoring\n");
	}
}
Пример #12
0
ssize_t IridiumSBD::read(struct file *filp, char *buffer, size_t buflen)
{
	pthread_mutex_lock(&_rx_buf_mutex);
	VERBOSE_INFO("READ: LEN %d, RX: %d RX END: %d", buflen, _rx_msg_read_idx, _rx_msg_end_idx);

	if (_rx_msg_read_idx < _rx_msg_end_idx) {
		size_t bytes_to_copy = _rx_msg_end_idx - _rx_msg_read_idx;

		if (bytes_to_copy > buflen) {
			bytes_to_copy = buflen;
		}

		memcpy(buffer, &_rx_msg_buf[_rx_msg_read_idx], bytes_to_copy);

		_rx_msg_read_idx += bytes_to_copy;

		pthread_mutex_unlock(&_rx_buf_mutex);
		return bytes_to_copy;

	} else {
		pthread_mutex_unlock(&_rx_buf_mutex);
		return -EAGAIN;
	}
}
Пример #13
0
DropIndexProcessor::DDLResult DropIndexProcessor::processPackage(ddlpackage::DropIndexStatement& dropIndexStmt)
{
    SUMMARY_INFO("DropIndexProcessor::processPackage");

    boost::shared_ptr<erydbSystemCatalog> sysCatalogPtr = erydbSystemCatalog::makeerydbSystemCatalog( dropIndexStmt.fSessionID );
    erydbSystemCatalog::IndexName indexName;
    erydbSystemCatalog::IndexOID indexOID;

    BRM::TxnID txnID;
	txnID.id= fTxnid.id;
	txnID.valid= fTxnid.valid;
	
    DDLResult result;
    result.result = NO_ERROR;

    int err = 0;

    VERBOSE_INFO(dropIndexStmt);

	SQLLogger logger(dropIndexStmt.fSql, fDDLLoggingId, dropIndexStmt.fSessionID, txnID.id);

	indexName.schema = dropIndexStmt.fIndexName->fSchema;
    indexName.index  = dropIndexStmt.fIndexName->fName;
    //Look up table name from indexname. Oracle will error out if same constraintname or indexname exists.
    erydbSystemCatalog::TableName tableName = sysCatalogPtr->lookupTableForIndex (dropIndexStmt.fIndexName->fName, dropIndexStmt.fIndexName->fSchema );
    indexName.table = tableName.table;
    indexOID = sysCatalogPtr->lookupIndexNbr(indexName);
    
    VERBOSE_INFO("Removing the SYSINDEX meta data");
    removeSysIndexMetaData(dropIndexStmt.fSessionID, txnID.id, result, *dropIndexStmt.fIndexName);
    if (result.result != NO_ERROR)
    {
        DETAIL_INFO("writeSysIndexMetaData failed");
        goto rollback;
    }

    VERBOSE_INFO("Removing the SYSINDEXCOL meta data");
    removeSysIndexColMetaData(dropIndexStmt.fSessionID, txnID.id, result, *dropIndexStmt.fIndexName);
    if (result.result != NO_ERROR)
    {
        DETAIL_INFO("writeSysIndexMetaData failed");
        goto rollback;
    }


    VERBOSE_INFO("Removing the index files");
    err = fWriteEngine.dropIndex(txnID.id, indexOID.objnum,indexOID.listOID);
    if (err)
    {
        DETAIL_INFO("WriteEngine dropIndex failed");
        goto rollback;
    }

    // Log the DDL statement
    logging::logDDL(dropIndexStmt.fSessionID, txnID.id, dropIndexStmt.fSql, dropIndexStmt.fOwner);

    // register the changes
    err = fWriteEngine.commit( txnID.id );
    if (err)
    {
        DETAIL_INFO("Failed to commit the drop index transaction");
        goto rollback;
    }
    fSessionManager.committed(txnID);
    //fObjectIDManager.returnOID(indexOID.objnum);
    //fObjectIDManager.returnOID(indexOID.listOID);
    return result;

rollback:
    fWriteEngine.rollbackTran(txnID.id, dropIndexStmt.fSessionID);
    fSessionManager.rolledback(txnID);
    return result;
}
Пример #14
0
satcom_result_code IridiumSBD::read_at(uint8_t *rx_buf, int *rx_len, int16_t timeout)
{
	struct pollfd fds[1];
	fds[0].fd = uart_fd;
	fds[0].events = POLLIN;

	uint8_t buf = 0;
	int last_rn_idx = 0;
	int rx_buf_pos = 0;
	*rx_len = 0;

	while (1) {
		if (::poll(&fds[0], 1, timeout) > 0) {
			if (::read(uart_fd, &buf, 1) > 0) {
				if (rx_buf_pos == 0 && (buf == '\r' || buf == '\n')) {
					// ignore the leading \r\n
					continue;
				}

				rx_buf[rx_buf_pos++] = buf;

				if (rx_buf[rx_buf_pos - 1] == '\n' && rx_buf[rx_buf_pos - 2] == '\r') {
					// found the \r\n delimiter
					if (rx_buf_pos == last_rn_idx + 2) {
						//if (verbose) { PX4_INFO("second in a row, ignore it");}
						; // second in a row, ignore it

					} else if (!strncmp((const char *)&rx_buf[last_rn_idx], "OK\r\n", 4)) {
						rx_buf[*rx_len] = 0; 	// null terminator after the information response for printing purposes
						return SATCOM_RESULT_OK;

					} else if (!strncmp((const char *)&rx_buf[last_rn_idx], "ERROR\r\n", 7)) {
						return SATCOM_RESULT_ERROR;

					} else if (!strncmp((const char *)&rx_buf[last_rn_idx], "SBDRING\r\n", 9)) {
						_ring_pending = true;
						_rx_session_pending = true;

						VERBOSE_INFO("GET SBDRING");

						return SATCOM_RESULT_SBDRING;

					} else if (!strncmp((const char *)&rx_buf[last_rn_idx], "READY\r\n", 7)) {
						return SATCOM_RESULT_READY;

					} else if (!strncmp((const char *)&rx_buf[last_rn_idx], "HARDWARE FAILURE", 16)) {
						PX4_WARN("HARDWARE FAILURE!");
						return SATCOM_RESULT_HWFAIL;

					} else {
						*rx_len = rx_buf_pos;	// that was the information response, result code incoming
					}

					last_rn_idx = rx_buf_pos;
				}
			}

		} else {
			break;
		}
	}

	return SATCOM_RESULT_NA;
}
Пример #15
0
static int populate_imm(const SaImmClassNameT className, 
	unsigned int pop, SaImmAdminOwnerHandleT ownerHandle, SaImmHandleT immHandle)
{
	SaAisErrorT error;
	int i;
	int rc = EXIT_FAILURE;
	SaImmCcbHandleT ccbHandle;
	SaImmClassCategoryT classCategory;
	SaImmAttrDefinitionT_2 **attrDefinitions;
	SaImmAttrDefinitionT_2 *att;
	SaImmAttrNameT rdnAttName = NULL;
	SaImmValueTypeT rdnAttType = SA_IMM_ATTR_SAANYT;
	range_obj_t *rootObj = NULL;

	if ((error = saImmOmClassDescriptionGet_2(immHandle, className, &classCategory, &attrDefinitions)) != SA_AIS_OK) {
		fprintf(stderr, "error - saImmOmClassDescriptionGet_2 FAILED: %s\n", saf_error(error));
		goto done;
	}

	if (classCategory == SA_IMM_CLASS_RUNTIME) {
		fprintf(stderr, "error - Class %s is a runtime class\n", className);
		goto done;		
	}

	for (i = 0, att = attrDefinitions[i]; att != NULL; att = attrDefinitions[++i]) {
		if (att->attrFlags & SA_IMM_ATTR_RDN) {
			rdnAttName = att->attrName;
			rdnAttType = att->attrValueType;
		} else if (att->attrFlags & SA_IMM_ATTR_INITIALIZED) {
			fprintf(stderr, "error - Attribute %s has INITIALIZED flag, cant handle\n", att->attrName);
			goto done;
		}
		VERBOSE_INFO("attrName: %s\n", att->attrName);
	}

	if (!rdnAttName) {
		fprintf(stderr, "error - Could not find any RDN attribure\n");
		goto done;
	}

	VERBOSE_INFO("Rdn attrName:%s type:%s\n", rdnAttName, (rdnAttType==SA_IMM_ATTR_SASTRINGT)?"SA_STRINGT":
		(rdnAttType==SA_IMM_ATTR_SANAMET)?"SA_NAMET":"WRONG");

	if ((error = saImmOmCcbInitialize(ownerHandle, (ccb_safe ? SA_IMM_CCB_REGISTERED_OI : 0x0), &ccbHandle))
		!= SA_AIS_OK) {
		fprintf(stderr, "error - saImmOmCcbInitialize FAILED: %s\n", saf_error(error));
		goto done;
	}

	VERBOSE_INFO("className: %s po:%u\n", className, pop);

	rootObj = gen_pop_tree(0, NULL, 0, 1, pop, rdnAttName);

	ccb_create_obj(NULL, &rootObj->parentDn, ccbHandle, className, rdnAttName, rdnAttType);

	generate_pop(rootObj, ccbHandle, className, rdnAttName, rdnAttType, ownerHandle);

	if ((error = saImmOmCcbFinalize(ccbHandle)) != SA_AIS_OK) {
		fprintf(stderr, "error - saImmOmCcbFinalize FAILED: %s\n", saf_error(error));
		goto done;
	}

	rc = 0;

done:
	return rc;
}
Пример #16
0
	DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpackage::DropPartitionStatement& dropPartitionStmt)
	{
		SUMMARY_INFO("DropPartitionProcessor::processPackage");

		DDLResult result;
		result.result = NO_ERROR;   
		std::string err;
		VERBOSE_INFO(dropPartitionStmt);

		// Commit current transaction.
		// all DDL statements cause an implicit commit
		VERBOSE_INFO("Getting current txnID");
		
		int rc = 0;
		rc = fDbrm->isReadWrite();
		BRM::TxnID txnID;
		txnID.id= fTxnid.id;
		txnID.valid= fTxnid.valid;
		if (rc != 0 )
		{
			logging::Message::Args args;
			logging::Message message(9);
			args.add("Unable to execute the statement due to DBRM is read only");
			message.format(args);
			result.result = DROP_ERROR;	
			result.message = message;
			fSessionManager.rolledback(txnID);
			return result;
		}

	
		std::vector <CalpontSystemCatalog::OID> oidList;
		CalpontSystemCatalog::RIDList tableColRidList;
		CalpontSystemCatalog::DictOIDList dictOIDList;
		execplan::CalpontSystemCatalog::ROPair roPair;
		uint32_t processID = 0;
		u_int64_t uniqueID = 0;
		uint32_t sessionID = dropPartitionStmt.fSessionID;
		std::string  processName("DDLProc");
		u_int64_t uniqueId = 0;
		
		//Bug 5070. Added exception handling
		try {
			uniqueId = fDbrm->getUnique64();
		}
		catch (std::exception& ex)
		{
			logging::Message::Args args;
			logging::Message message(9);
			args.add(ex.what());
			message.format(args);
			result.result = ALTER_ERROR;	
			result.message = message;
			fSessionManager.rolledback(txnID);
			return result;
		}
		catch ( ... )
		{
			logging::Message::Args args;
			logging::Message message(9);
			args.add("Unknown error occured while getting unique number.");
			message.format(args);
			result.result = ALTER_ERROR;	
			result.message = message;
			fSessionManager.rolledback(txnID);
			return result;
		}
		
		string stmt = dropPartitionStmt.fSql + "|" + dropPartitionStmt.fTableName->fSchema +"|";
		SQLLogger logger(stmt, fDDLLoggingId, sessionID, txnID.id);

		try 
		{
			//check table lock
			CalpontSystemCatalog *systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropPartitionStmt.fSessionID);
			systemCatalogPtr->identity(CalpontSystemCatalog::EC);
			systemCatalogPtr->sessionID(dropPartitionStmt.fSessionID);
			CalpontSystemCatalog::TableName tableName;
			tableName.schema = dropPartitionStmt.fTableName->fSchema;
			tableName.table = dropPartitionStmt.fTableName->fName;
			roPair = systemCatalogPtr->tableRID( tableName );
			//@Bug 3054 check for system catalog
			if ( roPair.objnum < 3000 )
			{
				throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog.");
			}
			int i = 0;
			processID = ::getpid();
			oam::OamCache * oamcache = OamCache::makeOamCache();
			std::vector<int> pmList = oamcache->getModuleIds();
			std::vector<uint> pms;
			for (unsigned i=0; i < pmList.size(); i++)
			{
				pms.push_back((uint)pmList[i]);
			}
				
			try {
				uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING );
			}
			catch (std::exception&)
			{
				result.result = DROP_ERROR;
				result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE);
				// no need to release lock. dbrm un-hold the lock
				fSessionManager.rolledback(txnID);
				return result;
			}
			
			if ( uniqueID  == 0 )
			{
				int waitPeriod = 10;
				int sleepTime = 100; // sleep 100 milliseconds between checks
				int numTries = 10;  // try 10 times per second
				waitPeriod = Config::getWaitPeriod();
				numTries = 	waitPeriod * 10;
				struct timespec rm_ts;

				rm_ts.tv_sec = sleepTime/1000;
				rm_ts.tv_nsec = sleepTime%1000 *1000000;

				for (; i < numTries; i++)
				{
#ifdef _MSC_VER
					Sleep(rm_ts.tv_sec * 1000);
#else
					struct timespec abs_ts;
					do
					{
						abs_ts.tv_sec = rm_ts.tv_sec;
						abs_ts.tv_nsec = rm_ts.tv_nsec;
					}
					while(nanosleep(&abs_ts,&rm_ts) < 0);
#endif
					// reset
					sessionID = dropPartitionStmt.fSessionID;
					txnID.id= fTxnid.id;
					txnID.valid= fTxnid.valid;
					processID = ::getpid();
					processName = "DDLProc";
					try 
					{
						uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING );
					}
					catch (std::exception&)
					{
						result.result = DROP_ERROR;
						result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE);
						fSessionManager.rolledback(txnID);
						return result;
					}

					if (uniqueID > 0)
						break;
				}

				if (i >= numTries) //error out
				{
					result.result = DROP_ERROR;
					logging::Message::Args args;
					args.add(processName);
					args.add((uint64_t)processID);
					args.add((uint64_t)sessionID);
					result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args));
					fSessionManager.rolledback(txnID);
					return result;
				}
			}

			// 1. Get the OIDs for the columns
			// 2. Get the OIDs for the dictionaries
			// 3. Save the OIDs to a log file
			// 4. Disable the extents from extentmap for the partition     	
			// 5. Remove the column and dictionary  files for the partition
			// 6. Flush PrimProc Cache 
			// 7. Remove the extents from extentmap for the partition

			CalpontSystemCatalog::TableName userTableName;
			userTableName.schema = dropPartitionStmt.fTableName->fSchema;
			userTableName.table = dropPartitionStmt.fTableName->fName;
		
			tableColRidList = systemCatalogPtr->columnRIDs( userTableName );
		
			dictOIDList = systemCatalogPtr->dictOIDs( userTableName );

			//Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format
			for ( unsigned i=0; i < tableColRidList.size(); i++ )
			{
				if ( tableColRidList[i].objnum > 3000 )
					oidList.push_back( tableColRidList[i].objnum );
			}
			for ( unsigned i=0; i < dictOIDList.size(); i++ )
			{
				if (  dictOIDList[i].dictOID > 3000 )
					oidList.push_back( dictOIDList[i].dictOID );
			}
		
			//Mark the partition disabled from extent map
			string emsg;
			rc = fDbrm->markPartitionForDeletion( oidList, dropPartitionStmt.fPartitions, emsg);
			if (rc != 0 && rc !=BRM::ERR_PARTITION_DISABLED &&
				  rc != BRM::ERR_INVALID_OP_LAST_PARTITION &&
				  rc != BRM::ERR_NOT_EXIST_PARTITION)
			{
				throw std::runtime_error(emsg);
			}
			
			set<BRM::LogicalPartition> markedPartitions;
			set<BRM::LogicalPartition> outOfServicePartitions;
			
			// only log partitions that are successfully marked disabled.
			rc = fDbrm->getOutOfServicePartitions(oidList[0], outOfServicePartitions);
			
			if (rc != 0)
			{
				string errorMsg;
				BRM::errString(rc, errorMsg);
				ostringstream oss;
				oss << "getOutOfServicePartitions failed  due to " << errorMsg;
				     throw std::runtime_error(oss.str());
			}

			set<BRM::LogicalPartition>::iterator it;
			for (it = dropPartitionStmt.fPartitions.begin(); it != dropPartitionStmt.fPartitions.end(); ++it)
			{
				if (outOfServicePartitions.find(*it) != outOfServicePartitions.end())
					markedPartitions.insert(*it);
			}
			
			//Save the oids to a file
			createWritePartitionLogFile( roPair.objnum, markedPartitions, oidList, uniqueId);

			VERBOSE_INFO("Removing files");
			removePartitionFiles( oidList, markedPartitions, uniqueId );
			//Flush PrimProc cache for those lbids
			rc = cacheutils::flushPartition( oidList, markedPartitions );
			
			//Remove the partition from extent map
			emsg.clear();
			rc = fDbrm->deletePartition( oidList, dropPartitionStmt.fPartitions, emsg);
			if ( rc != 0 )
				throw std::runtime_error(emsg);
		}
		catch (exception& ex)
		{
			cerr << "DropPartitionProcessor::processPackage: " << ex.what() << endl;

			logging::Message::Args args;
			logging::Message message(ex.what());

			if (rc == BRM::ERR_TABLE_NOT_LOCKED)
				result.result = USER_ERROR;
			else if (rc == BRM::ERR_NOT_EXIST_PARTITION || rc == BRM::ERR_INVALID_OP_LAST_PARTITION) 
				result.result = PARTITION_WARNING;
			else if (rc == BRM::ERR_NO_PARTITION_PERFORMED)
				result.result = WARN_NO_PARTITION;
			else
				result.result = DROP_ERROR;
			result.message = message;
			try {
				fDbrm->releaseTableLock(uniqueID);
			} catch (std::exception&)
			{
				result.result = DROP_ERROR;
				result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE);
			}
			fSessionManager.rolledback(txnID);
			return result;
		}
		catch (...)
		{
			cerr << "DropPartitionProcessor::processPackage: caught unknown exception!" << endl;

			logging::Message::Args args;
			logging::Message message(1);
			args.add("Drop partition failed: ");
			args.add( "encountered unkown exception" );
			args.add("");
			args.add("");
		 	message.format( args );
		
			result.result = DROP_ERROR;
			result.message = message;
			try {
				fDbrm->releaseTableLock(uniqueID);
			} catch (std::exception&)
			{
				result.result = DROP_ERROR;
				result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE);
			}
			fSessionManager.rolledback(txnID);
			return result;
		}
		// Log the DDL statement
		logging::logDDL(dropPartitionStmt.fSessionID, txnID.id, dropPartitionStmt.fSql, dropPartitionStmt.fOwner);
		//Remove the log file
		//release the transaction
		try {
			fDbrm->releaseTableLock(uniqueID);
			deleteLogFile(DROPPART_LOG, roPair.objnum, uniqueId);
		} catch (std::exception&)
		{
			result.result = DROP_ERROR;
			result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE);
			fSessionManager.rolledback(txnID);
			return result;
		}
		fSessionManager.committed(txnID);
		return result;
	}
Пример #17
0
void IridiumSBD::main_loop(int argc, char *argv[])
{
	CDev::init();

	pthread_mutex_init(&_tx_buf_mutex, NULL);
	pthread_mutex_init(&_rx_buf_mutex, NULL);

	int arg_i = 3;
	int arg_uart_name = 0;

	while (arg_i < argc) {
		if (!strcmp(argv[arg_i], "-d")) {
			arg_i++;
			arg_uart_name = arg_i;

		} else if (!strcmp(argv[arg_i], "-v")) {
			PX4_WARN("verbose mode ON");
			_verbose = true;
		}

		arg_i++;
	}

	if (arg_uart_name == 0) {
		PX4_WARN("no Iridium SBD modem UART port provided!");
		_task_should_exit = true;
		return;
	}

	if (open_uart(argv[arg_uart_name]) != SATCOM_UART_OK) {
		PX4_WARN("failed to open UART port!");
		_task_should_exit = true;
		return;
	}

	// disable flow control
	write_at("AT&K0");

	if (read_at_command() != SATCOM_RESULT_OK) {
		PX4_WARN("modem not responding");
		_task_should_exit = true;
		return;
	}

	// disable command echo
	write_at("ATE0");

	if (read_at_command() != SATCOM_RESULT_OK) {
		PX4_WARN("modem not responding");
		_task_should_exit = true;
		return;
	}

	param_t param_pointer;

	param_pointer = param_find("ISBD_READ_INT");
	param_get(param_pointer, &_param_read_interval_s);

	param_pointer = param_find("ISBD_SBD_TIMEOUT");
	param_get(param_pointer, &_param_session_timeout_s);

	if (_param_session_timeout_s < 0) {
		_param_session_timeout_s = 60;
	}

	param_pointer = param_find("ISBD_STACK_TIME");
	param_get(param_pointer, &_param_stacking_time_ms);

	if (_param_stacking_time_ms < 0) {
		_param_stacking_time_ms = 0;
	}

	VERBOSE_INFO("read interval: %d s", _param_read_interval_s);
	VERBOSE_INFO("SBD session timeout: %d s", _param_session_timeout_s);
	VERBOSE_INFO("SBD stack time: %d ms", _param_stacking_time_ms);

	while (!_task_should_exit) {
		switch (_state) {
		case SATCOM_STATE_STANDBY:
			standby_loop();
			break;

		case SATCOM_STATE_CSQ:
			csq_loop();
			break;

		case SATCOM_STATE_SBDSESSION:
			sbdsession_loop();
			break;

		case SATCOM_STATE_TEST:
			test_loop();
			break;
		}

		if (_new_state != _state) {
			VERBOSE_INFO("SWITCHING STATE FROM %s TO %s", satcom_state_string[_state], satcom_state_string[_new_state]);
			_state = _new_state;
			publish_iridium_status();

		} else {
			publish_iridium_status();
			usleep(100000);	// 100ms
		}
	}
}
Пример #18
0
void IridiumSBD::sbdsession_loop(void)
{
	int res = read_at_command();

	if (res == SATCOM_RESULT_NA) {
		if ((_param_session_timeout_s > 0)
		    && (((hrt_absolute_time() - _session_start_time))
			> (uint64_t)_param_session_timeout_s * 1000000)) {

			PX4_WARN("SBD SESSION: TIMEOUT!");
			++_failed_sbd_sessions;
			_new_state = SATCOM_STATE_STANDBY;
			pthread_mutex_unlock(&_tx_buf_mutex);
		}

		return;
	}

	if (res != SATCOM_RESULT_OK) {
		VERBOSE_INFO("SBD SESSION: ERROR. RESULT: %d", res);

		++_failed_sbd_sessions;
		_new_state = SATCOM_STATE_STANDBY;
		pthread_mutex_unlock(&_tx_buf_mutex);
		return;
	}

	if (strncmp((const char *)_rx_command_buf, "+SBDIX:", 7)) {

		VERBOSE_INFO("SBD SESSION: WRONG ANSWER: %s", _rx_command_buf);

		_new_state = SATCOM_STATE_STANDBY;
		++_failed_sbd_sessions;
		pthread_mutex_unlock(&_tx_buf_mutex);
		return;
	}

	int mo_status, mt_status, mt_len, mt_queued;
	const char *p = (const char *)_rx_command_buf + 7;
	char **rx_buf_parse = (char **)&p;

	mo_status = strtol(*rx_buf_parse, rx_buf_parse, 10);
	(*rx_buf_parse)++;
	strtol(*rx_buf_parse, rx_buf_parse, 10); // MOMSN, ignore it
	(*rx_buf_parse)++;
	mt_status = strtol(*rx_buf_parse, rx_buf_parse, 10);
	(*rx_buf_parse)++;
	strtol(*rx_buf_parse, rx_buf_parse, 10); // MTMSN, ignore it
	(*rx_buf_parse)++;
	mt_len = strtol(*rx_buf_parse, rx_buf_parse, 10);
	(*rx_buf_parse)++;
	mt_queued = strtol(*rx_buf_parse, rx_buf_parse, 10);

	VERBOSE_INFO("MO ST: %d, MT ST: %d, MT LEN: %d, MT QUEUED: %d", mo_status, mt_status, mt_len, mt_queued);
	VERBOSE_INFO("SBD session duration: %.2f", (hrt_absolute_time() - _session_start_time) / 1000000.0);

	switch (mo_status) {
	case 0:
	case 2:
	case 3:
	case 4:
		VERBOSE_INFO("SBD SESSION: SUCCESS (%d)", mo_status);

		_ring_pending = false;
		_tx_session_pending = false;
		_last_read_time = hrt_absolute_time();
		_last_heartbeat = _last_read_time;
		++_successful_sbd_sessions;

		if (mt_queued > 0) {
			_rx_session_pending = true;

		} else {
			_rx_session_pending = false;

		}

		if (mt_len > 0) {
			_rx_read_pending = true;
		}

		// after a successful session reset the tx buffer
		_tx_buf_write_idx = 0;
		break;

	case 1:
		VERBOSE_INFO("SBD SESSION: MO SUCCESS, MT FAIL");
		_last_heartbeat = hrt_absolute_time();

		// after a successful session reset the tx buffer
		_tx_buf_write_idx = 0;
		++_successful_sbd_sessions;

		_tx_session_pending = false;
		break;

	case 32:
		VERBOSE_INFO("SBD SESSION: NO NETWORK SIGNAL");

		++_failed_sbd_sessions;
		_signal_quality = 0;
		break;

	default:
		++_failed_sbd_sessions;
		VERBOSE_INFO("SBD SESSION: FAILED (%d)", mo_status);
	}

	_new_state = SATCOM_STATE_STANDBY;
	pthread_mutex_unlock(&_tx_buf_mutex);
}