MojErr MovePopEmailsCommand::GetUidCacheResponse() { try { m_commandResult->CheckException(); std::set<std::string>::iterator itr = m_inboxEmailsMoved.begin(); while (itr != m_inboxEmailsMoved.end()) { std::string uid = *itr; m_uidCache.GetDeletedEmailsCache().AddToPendingDeletedEmailCache(uid); itr++; } m_uidCache.GetDeletedEmailsCache().SetChanged(true); SaveUidCache(); } catch(const std::exception& e) { MojLogError(m_log, "Failed to sync folder: %s", e.what()); Failure(e); } catch(...) { MojLogError(m_log, "Uncaught exception %s", __PRETTY_FUNCTION__); MailException exc("Unable to get old emails cache", __FILE__, __LINE__); Failure(exc); } return MojErrNone; }
/* * Result of query for buddy with given username and serviceName * * If the buddy is found, we can send no matter what. If buddy is not found, we need to check if this service allows sending IM messages * to non buddies (gtalk does not allow this, aol does) */ MojErr SendOneMessageHandler::findBuddyResult(MojObject& result, MojErr findErr) { if (findErr) { MojString error; MojErrToString(findErr, error); MojLogError(IMServiceApp::s_log, _T("findBuddyResult: error %d - %s"), findErr, error.data()); // not much we can do here... failMessage(ERROR_SEND_GENERIC_ERROR); } else { // log the results MojString mojStringJson; result.toJson(mojStringJson); MojLogDebug(IMServiceApp::s_log, _T("findBuddyResult result: %s"), mojStringJson.data()); // "results" in result MojObject results; result.get(_T("results"), results); // check to see if array is empty - there should really always be 0 or 1 item here if (!results.empty()){ // buddy is on the list - send to the transport MojLogInfo(IMServiceApp::s_log, _T("findBuddyResult - user is on buddy list. No need to check account template.")); sendToTransport(); } else { MojLogInfo(IMServiceApp::s_log, _T("findBuddyResult - no buddy found. Need to check account template if this is allowed")); // check palm://com.palm.service.accounts/listAccountTemplates {"capability":"MESSAGING"} to get a list of account templates that support messaging. // If the account template includes "chatWithNonBuddies":false, it should fail to send. MojLogInfo(IMServiceApp::s_log, "Issuing listAccountTemplates request to com.palm.service.accounts"); // parameters: {“capability”:”MESSAGING”} MojObject params; params.putString("capability", "MESSAGING"); // Get a request object from the service MojRefCountedPtr<MojServiceRequest> req; MojErr err = m_service->createRequest(req); if (!err) { err = req->send(m_listAccountSlot, "com.palm.service.accounts", "listAccountTemplates", params); } if (err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("findBuddyResult failed to send request to accounts: error %d - %s"), err, error.data()); // not much we can do here...don't leave message still pending failMessage(ERROR_SEND_GENERIC_ERROR); } } } return MojErrNone; }
bool ControlGroup::WriteControlFile(const std::string& controlFile, const char *buf, size_t count, std::list<int>::iterator current) { int fd = open(controlFile.c_str(), O_WRONLY); if (fd < 0) { MojLogError(s_log, _T("Failed to open control file `%s': %s"), controlFile.c_str(), strerror(errno)); return false; } ssize_t ret = write(fd, buf, count); if (ret < 0) { // If the process does not exist, cgroups will return ESRCH (no such process) if(errno == ESRCH) { MojLogWarning(s_log, _T("Process '%s' to be written to file '%s' doesn't exist"), buf, controlFile.c_str()); close(fd); m_processIds.erase(current); return true; } MojLogError(s_log, _T("Failed to write control file `%s': %s"), controlFile.c_str(), strerror(errno)); close(fd); return false; } else if ((size_t)ret != count) { MojLogError(s_log, _T("Short write updating control file `%s'"), controlFile.c_str()); close(fd); return false; } close(fd); return true; }
MojErr InsertEmailsCommand::ReserverEmailIdsResponse(MojObject& response, MojErr err) { try { ErrorToException(err); MojLogDebug(m_log, "Got reserver ids response: %s", AsJsonString(response).c_str()); MojObject idArray; err = response.getRequired("ids", idArray); ErrorToException(err); for (int ndx = 0; ndx < (int)m_emails->size(); ndx++) { MojObject id; idArray.at(ndx, id); PopEmail::PopEmailPtr emailPtr = m_emails->at(ndx); MojLogDebug(m_log, "Assigning id '%s' to email '%s'", AsJsonString(id).c_str(), emailPtr->GetServerUID().c_str()); emailPtr->SetId(id); } SaveEmails(); } catch (const std::exception& e) { MojLogError(m_log, "Exception in reserving email ID: '%s'", e.what()); Failure(e); } catch (...) { MojLogError(m_log, "Unknown exception in reserving email ID"); Failure(MailException("Unknown exception in reserving email ID", __FILE__, __LINE__)); } return MojErrNone; }
/* * Fail the message in the DB * This is the result of an internal error that should not happen - we just need to get back to a consistent state */ MojErr SendOneMessageHandler::failMessage(const MojChar *errorString) { // permanent error - no retry option MojObject propObject; propObject.putString(MOJDB_STATUS, IMMessage::statusStrings[Undeliverable]); // set the error category string for the UI propObject.putString(MOJDB_ERROR_CATEGORY,errorString); MojLogError(IMServiceApp::s_log, _T("failMessage error: %s"), errorString); // id to update propObject.putString(MOJDB_ID, m_currentMsgdbId); // set server timestamp to current time. MojInt64 now = time (NULL); propObject.put(MOJDB_SERVER_TIMESTAMP, now); // save the new fields - call merge // MojErr merge(Signal::SlotRef handler, const MojObject& obj, MojUInt32 flags = MojDb::FlagNone); MojErr err = m_dbClient.merge(this->m_imSaveMessageSlot, propObject); if (err) { MojLogError(IMServiceApp::s_log, _T("call to merge message into DB failed. err %d, DB id %s: "), err, m_currentMsgdbId.data() ); // call to save failed - not much we can do here... m_outgoingIMHandler->messageFinished(); } return MojErrNone; }
MojErr OnEnabledHandler::getAccountInfoResult(MojObject& payload, MojErr resultErr) { MojLogTrace(IMServiceApp::s_log); IMServiceHandler::logMojObjectJsonString(_T("OnEnabledHandler::getAccountInfoResult payload: %s"), payload); if (resultErr != MojErrNone) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler getAccountInfo result error %d"), resultErr); return resultErr; } MojObject result; MojErr err = payload.getRequired("result", result); if (err != MojErrNone || result.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult result empty or error %d"), err); return err; } err = result.getRequired("_id", m_accountId); if (err != MojErrNone || m_accountId.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult accountId empty or error %d"), err); return err; } err = result.getRequired("username", m_username); if (err != MojErrNone || m_username.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult username empty or error %d"), err); return err; } { MojObject capabilities; MojObject messagingObject; result.get("capabilityProviders", capabilities); getMessagingCapabilityObject(capabilities, messagingObject); err = messagingObject.getRequired("serviceName", m_serviceName); if (m_serviceName.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult serviceName empty")); return err; } } if (m_enable) { MojDbQuery query; query.from("com.palm.config.libpurple:1"); query.where("accountId", MojDbQuery::OpEq, m_accountId); query.limit(1); err = m_dbClient.find(m_getAccountConfigSlot, query); } else { err = accountDisabled(); } return err; }
// Expected responses // {"activityId":78,"returnValue":true} // {"activityId":78,"event":"start","returnValue":true} <-- this occurs when the timeout fires // Error in case there is already an activity for the given serviceName // {"errorCode":17,"errorText":"Activity with that name already exists","returnValue":false} MojErr ConnectionState::ConnectionChangedScheduler::scheduleActivityResult(MojObject& result, MojErr err) { // log the parameters IMServiceHandler::logMojObjectJsonString(_T("ConnectionChangedScheduler::scheduleActivityResult: %s"), result); if (MojErrNone != err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("ConnectionChangedScheduler::scheduleActivityResult failed: error %d - %s"), err, error.data()); // we created this slot with unlimited responses, so we have to explicitly cancel it, unless there is another activity of this name already, in which case // we get here again if (MojErrExists != err) { // err 17 = "Activity with that name already exists" m_scheduleActivitySlot.cancel(); } } else { MojString event; if (result.getRequired(_T("event"), event) == MojErrNone) { MojLogInfo(IMServiceApp::s_log, _T("ConnectionChangedScheduler::scheduleActivityResult event=%s"), event.data()); if (event == "start") { MojInt64 activityId = 0; MojObject dummy; m_loginState->handleConnectionChanged(dummy); bool found = result.get("activityId", activityId); if (found && activityId > 0) { MojRefCountedPtr<MojServiceRequest> req; err = m_service->createRequest(req); MojObject completeParams; completeParams.put(_T("activityId"), activityId); err = req->send(m_activityCompleteSlot, "com.palm.activitymanager", "complete", completeParams, 1); } else { MojLogError(IMServiceApp::s_log,_T("ConnectionChangedScheduler::scheduleActivityResult - missing activityId")); } if (activityId <= 0 || err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("ConnectionChangedScheduler::scheduleActivityResult send request failed: error %d - %s"), err, error.data()); // we created this slot with unlimited responses, so we have to explicitly cancel m_scheduleActivitySlot.cancel(); } } } // if there is no event we get here again } return MojErrNone; }
/* * Send the messages off to libpurple transport */ MojErr SendOneMessageHandler::sendToTransport() { MojErr err = MojErrNone; // can't log message text in production MojLogInfo (IMServiceApp::s_log, "sending message to transport. id: %s, serviceName: %s, username: %s, usernameTo: %s", m_currentMsgdbId.data(), m_serviceName.data(), m_username.data(), m_usernameTo.data()); // Note, libpurple does not return errors on send - adapter only checks that the parameters are valid and that the user is logged in // otherwise assume success... LibpurpleAdapter::SendResult retVal = LibpurpleAdapter::sendMessage(m_serviceName.data(), m_username.data(), m_usernameTo.data(), m_messageText.data()); // Now save the status MojObject propObject; if (LibpurpleAdapter::SENT == retVal) { // successful send propObject.putString(MOJDB_STATUS, IMMessage::statusStrings[Successful]); MojLogInfo(IMServiceApp::s_log, _T("LibpurpleAdapter::sendToTransport succeeded")); } else if (LibpurpleAdapter::USER_NOT_LOGGED_IN == retVal) { // user not logged in - put in queued state propObject.putString(MOJDB_STATUS, IMMessage::statusStrings[WaitingForConnection]); MojLogError(IMServiceApp::s_log, _T("LibpurpleAdapter::sendToTransport - user not logged in. waiting for connection")); } else { // permanent error - no retry option propObject.putString(MOJDB_STATUS, IMMessage::statusStrings[Undeliverable]); // set the error category string for the UI const MojChar* errorCategory = transportErrorToCategory(retVal); propObject.putString(MOJDB_ERROR_CATEGORY, errorCategory); MojLogError(IMServiceApp::s_log, _T("LibpurpleAdapter::sendToTransport failed. error %d, category %s"), retVal, errorCategory); } // id to update propObject.putString(MOJDB_ID, m_currentMsgdbId); // set server timestamp to current time. MojInt64 now = time (NULL); propObject.put(MOJDB_SERVER_TIMESTAMP, now); // save the new fields - call merge // MojErr merge(Signal::SlotRef handler, const MojObject& obj, MojUInt32 flags = MojDb::FlagNone); err = m_dbClient.merge(this->m_imSaveMessageSlot, propObject); if (err) { MojLogError(IMServiceApp::s_log, _T("call to merge message into DB failed. err %d, DB id %s: "), err, m_currentMsgdbId.data() ); // request to save failed - not much we can do here... m_outgoingIMHandler->messageFinished(); } return MojErrNone; }
// This defines a new cache type and will cause a new CFileCache // object to be instantiated. The typeName must be unique. The sum // of the cache loWatermarks must be less than the total cache space // available or the cache type creation will fail. bool CFileCacheSet::DefineType(std::string& msgText, const std::string& typeName, CCacheParamValues* params, bool dirType) { MojLogTrace(s_log); msgText = "DefineType: "; bool retVal = false; CFileCache* fileCache = GetFileCacheForType(typeName); if (fileCache == NULL) { CFileCache* newType = new CFileCache(this, typeName); if (newType != NULL) { if (newType->Configure(params, dirType)) { m_cacheSet.insert(std::map<const std::string, CFileCache*>::value_type(typeName, newType)); retVal = true; msgText += "Created type '" + typeName + "'."; MojLogInfo(s_log, _T("%s"), msgText.c_str()); } else { delete newType; msgText += "Failed to configure '" + typeName + "'."; MojLogError(s_log, _T("%s"), msgText.c_str()); } } else { msgText += "Failed to allocate '" + typeName + "'."; MojLogCritical(s_log, _T("%s"),msgText.c_str()); } } else { msgText += "Type '" + typeName + "'" + " already exists."; MojLogWarning(s_log, _T("%s"), msgText.c_str()); } return retVal; }
void PopSession::CommandComplete(Command* command) { m_requestManager->UnregisterCommand(command); m_commandManager->CommandComplete(command); if ((m_state == State_OkToSync || m_state == State_CancelPendingCommands) && m_commandManager->GetPendingCommandCount() == 0 && m_commandManager->GetActiveCommandCount() == 0) { // no commands to run // complete sync session if (m_syncSession.get() && (m_syncSession->IsActive() || m_syncSession->IsStarting())) { MojLogInfo(m_log, "Requesting to stop sync session"); if (m_accountError.errorCode != MailError::NONE) { MojLogError(m_log, "in session, account error: [%d]%s", m_accountError.errorCode, m_accountError.errorText.c_str()); } m_syncSession->SetAccountError(m_accountError); m_syncSession->RequestStop(); } // apply pending account changes ApplyAccountUpdates(); // set the state so that we can log out the current session m_state = State_LogOut; LogOut(); } }
CFileCacheSet::CFileCacheSet(bool init) : m_totalCacheSpace(0) { MojLogTrace(s_log); if (init) { // Read the configuration file to get the system wide settings ReadConfig(s_configFile); // Make sure the cache directory exists and set the correct // directory permissions int retVal = ::mkdir(m_baseDirName.c_str(), s_dirPerms); if (retVal != 0 && errno != EEXIST) { int savedErrno = errno; MojLogError(s_log, _T("CFileCacheSet: Failed to create cache directory '%s' (%s)."), m_baseDirName.c_str(), ::strerror(savedErrno)); exit(-1); } } // This provides a pseudo-random seed.and either reads the last // saved sequence number (and bumps the value by the write // interval) or else initializes the sequence number to 1. srand48((long) ::time(0)); ReadSequenceNumber(); }
MojErr TrimFolderEmailsCommand::DeleteLocalEmailsResponse(MojObject& response, MojErr err) { try { ErrorToException(err); Complete(); } catch(const std::exception& e) { MojLogError(m_log, "Unable to delete local emails: %s", e.what()); Failure(e); } catch(...) { MojLogError(m_log, "Uncaught exception %s", __PRETTY_FUNCTION__); MailException exc("Unable to delete local emails", __FILE__, __LINE__); Failure(exc); } return MojErrNone; }
MojErr MovePopEmailsCommand::SaveUidCacheResponse() { try { m_commandResult->CheckException(); Complete(); } catch(const std::exception& e) { MojLogError(m_log, "Failed to sync folder: %s", e.what()); Failure(e); } catch(...) { MojLogError(m_log, "Uncaught exception %s", __PRETTY_FUNCTION__); MailException exc("Unable to get old emails cache", __FILE__, __LINE__); Failure(exc); } return MojErrNone; }
MojErr ScheduleRetryCommand::CancelActivitiesDone() { try { m_deleteActivitiesCommand->GetResult()->CheckException(); UpdateAccount(); } catch (const std::exception& e) { MojLogError(m_log, "Exception in cancel activities done: '%s'", e.what()); Failure(e); } catch (...) { MojLogError(m_log, "Unknown exception in cancel activities done"); Failure(MailException("Unknown exception in cancel activities done", __FILE__, __LINE__)); } return MojErrNone; }
/* * New incoming IM message */ bool IMServiceHandler::incomingIM(const char* serviceName, const char* username, const char* usernameFrom, const char* message) { MojLogTrace(IMServiceApp::s_log); // log the parameters // don't log the message text MojLogInfo (IMServiceApp::s_log, _T("incomingIM - IM received. serviceName: %s username: %s usernameFrom: %s"), serviceName, username, usernameFrom); // no error - process the IM MojRefCountedPtr<IMMessage> imMessage(new IMMessage); // set the message fields based on the incoming parameters MojErr err = imMessage->initFromCallback(serviceName, username, usernameFrom, message); if (!err) { // handle the message MojRefCountedPtr<IncomingIMHandler> incomingIMHandler(new IncomingIMHandler(m_service)); err = incomingIMHandler->saveNewIMMessage(imMessage); } if (err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("incomingIM failed: %d - %s"), err, error.data()); MojErrCheck(err); return false; } return true; }
MojErr ScheduleRetryCommand::UpdateAccountResponse(MojObject& response, MojErr err) { try { ErrorToException(err); Complete(); } catch (const std::exception& e) { MojLogError(m_log, "Exception in update account response: '%s'", e.what()); Failure(e); } catch (...) { MojLogError(m_log, "Unknown exception in update account response"); Failure(MailException("Unknown exception in update account response", __FILE__, __LINE__)); } return MojErrNone; }
/* * Result of query for loginState entry with given username and serviceName when removing a buddy * * Remove buddy from buddyStatus and contact DB */ MojErr SendOneMessageHandler::findAccountIdResult(MojObject& result, MojErr findErr) { if (findErr) { MojString error; MojErrToString(findErr, error); MojLogError(IMServiceApp::s_log, _T("findAccountIdResult failed: error %d - %s"), findErr, error.data()); // not much we can do here... failMessage(ERROR_SEND_GENERIC_ERROR); } else { // parse out the accountId readAccountIdFromResults(result); if (!m_accountId.empty()){ // construct our where clause - find by username, accountId and servicename MojDbQuery query; query.where("username", MojDbQuery::OpEq, m_usernameTo); query.where("accountId", MojDbQuery::OpEq, m_accountId); query.from(IM_BUDDYSTATUS_KIND); MojObject queryObject; query.toObject(queryObject); IMServiceHandler::logMojObjectJsonString(_T("findAccountIdResult - buddyStatus query: %s"), queryObject); // call find //virtual MojErr find(Signal::SlotRef handler, const MojDbQuery& query, // bool watch = false, bool returnCount = false) = 0; MojErr err = m_tempdbClient.find(this->m_findBuddySlot, query, /* watch */ false ); if (err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("findAccountIdResult dbClient.find() failed: error %d - %s"), err, error.data()); failMessage(ERROR_SEND_GENERIC_ERROR); } } else { MojLogError(IMServiceApp::s_log, _T("findAccountIdResult: no matching loginState record found for %s"), m_serviceName.data()); // tell the outgoing Command handler we are done failMessage(ERROR_SEND_GENERIC_ERROR); } } return MojErrNone; }
MojErr OnEnabledHandler::getAccountInfoResult(MojObject& payload, MojErr resultErr) { MojLogTrace(IMServiceApp::s_log); IMServiceHandler::logMojObjectJsonString(_T("OnEnabledHandler::getAccountInfoResult payload: %s"), payload); if (resultErr != MojErrNone) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler getAccountInfo result error %d"), resultErr); return resultErr; } MojObject result; MojErr err = payload.getRequired("result", result); if (err != MojErrNone || result.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult result empty or error %d"), err); return err; } MojString accountId; err = result.getRequired("_id", accountId); if (err != MojErrNone || accountId.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult accountId empty or error %d"), err); return err; } MojString username; err = result.getRequired("username", username); if (err != MojErrNone || username.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult username empty or error %d"), err); return err; } MojString serviceName; getServiceNameFromCapabilityId(serviceName); if (serviceName.empty()) { MojLogError(IMServiceApp::s_log, _T("OnEnabledHandler::getAccountInfoResult serviceName empty")); return err; } if (m_enable) { err = accountEnabled(accountId, serviceName, username); } else { err = accountDisabled(accountId, serviceName, username); } return err; }
/* * Result of query for loginState entry with given username and serviceName when adding a buddy * * Save buddy in buddyStatus and contact DB */ MojErr SendOneCommandHandler::findAccountIdForAddResult(MojObject& result, MojErr findErr) { if (findErr) { MojString error; MojErrToString(findErr, error); MojLogError(IMServiceApp::s_log, _T("findAccountIdResult failed: error %d - %s"), findErr, error.data()); } else { // parse out the accountId readAccountIdFromResults(result); if (!m_accountId.empty()){ MojObject buddyStatus; buddyStatus.putString("_kind", IM_BUDDYSTATUS_KIND); buddyStatus.put("accountId", m_accountId); buddyStatus.put("username", m_buddyName); buddyStatus.put("serviceName", m_serviceName); // log it MojString json; buddyStatus.toJson(json); MojLogInfo(IMServiceApp::s_log, _T("saving buddy status to db: %s"), json.data()); // save it // the save generates a call to the save result handler MojErr err = m_tempdbClient.put(m_addBuddySlot, buddyStatus); if (err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("findAccountIdResult: dbClient.put() failed: error %d - %s"), err, error.data()); // tell the outgoing Command handler we are done m_outgoingIMHandler->messageFinished(); } } else { MojLogError(IMServiceApp::s_log, _T("findAccountIdResult: no matching loginState record found for %s %s"), m_username.data(), m_serviceName.data()); // tell the outgoing Command handler we are done m_outgoingIMHandler->messageFinished(); } } return MojErrNone; }
MojErr ScheduleRetryCommand::ScheduleRetryResponse(MojObject& response, MojErr err) { try { MojLogInfo(m_log, "Retry activity creation: %s", AsJsonString(response).c_str()); ErrorToException(err); CancelActivities(); } catch (const std::exception& e) { MojLogError(m_log, "Exception in schedule retry response: '%s'", e.what()); Failure(e); } catch (...) { MojLogError(m_log, "Unknown exception in schedule retry response"); Failure(MailException("Unknown exception in schedule retry response", __FILE__, __LINE__)); } return MojErrNone; }
MojErr ServiceApp::open() { Gio::init(); MojErr err = Base::open(); MojErrCheck(err); err = m_service.open(ServiceName); MojErrCheck(err); err = m_service.attach(m_reactor.impl()); MojErrCheck(err); m_handler.reset(new CategoryHandler(m_fileCacheSet)); MojAllocCheck(m_handler.get()); err = m_handler->RegisterMethods(); MojErrCheck(err); err = m_service.addCategory(MojLunaService::DefaultCategory, m_handler.get()); MojErrCheck(err); #if !defined(TARGET_DESKTOP) char* upstartJob = ::getenv("UPSTART_JOB"); if (upstartJob) { char* upstartEvent = g_strdup_printf("%s emit %s-ready", (gchar *)s_InitctlCommand.c_str(), upstartJob); if (upstartEvent) { int retVal = ::system(upstartEvent); if (retVal == -1) { MojLogError(s_globalLogger, _T("ServiceApp: Failed to emit upstart event")); } g_free(upstartEvent); } else { MojLogError(s_globalLogger, _T("ServiceApp: Failed to allocate memory for upstart emit")); } } #endif // #if !defined(TARGET_DESKTOP) return MojErrNone; }
boost::shared_ptr<Requirement> PowerdProxy::InstantiateRequirement( boost::shared_ptr<Activity> activity, const std::string& name, const MojObject& value) { MojLogTrace(s_log); MojLogInfo(s_log, _T("Instantiating [Requirement %s] for [Activity %llu]"), name.c_str(), activity->GetId()); if (name == "charging") { if ((value.type() != MojObject::TypeBool) || !value.boolValue()) { throw std::runtime_error("A \"charging\" requirement must specify " "'true' if present"); } boost::shared_ptr<ListedRequirement> req = boost::make_shared<BasicCoreListedRequirement>( activity, m_chargingRequirementCore, m_chargingRequirementCore->IsMet()); m_chargingRequirements.push_back(*req); return req; } else if (name == "docked") { if ((value.type() != MojObject::TypeBool) || !value.boolValue()) { throw std::runtime_error("A \"docked\" requirement must specify " "'true' if present"); } boost::shared_ptr<ListedRequirement> req = boost::make_shared<BasicCoreListedRequirement>( activity, m_dockedRequirementCore, m_dockedRequirementCore->IsMet()); m_dockedRequirements.push_back(*req); return req; } else if (name == "battery") { if ((value.type() != MojObject::TypeInt) || (value.intValue() < 0) || (value.intValue() > 100)) { throw std::runtime_error("A \"battery\" requirement must specify " "a value between 0 and 100"); } MojInt64 percent = value.intValue(); boost::shared_ptr<BatteryRequirement> req = boost::make_shared<BatteryRequirement>(activity, percent, boost::dynamic_pointer_cast<PowerdProxy, RequirementManager>(shared_from_this()), (m_batteryPercent >= percent)); m_batteryRequirements.insert(*req); return req; } else { MojLogError(s_log, _T("[Manager %s] does not know how to instantiate " "[Requirement %s] for [Activity %llu]"), GetName().c_str(), name.c_str(), activity->GetId()); throw std::runtime_error("Attempt to instantiate unknown requirement"); } }
void SmtpAccountEnableCommand::Failure(const std::exception& e) { if(m_msg.get()) m_msg->replyError(MojErrInternal, e.what()); MojLogError(m_log, "error enabling SMTP for account %s: %s", AsJsonString(m_client.GetAccountId()).c_str(), e.what()); SmtpCommand::Failure(e); }
/* * Result of query for loginState entry with given username and serviceName when removing a buddy * * Remove buddy from buddyStatus and contact DB */ MojErr SendOneCommandHandler::findAccountIdForRemoveResult(MojObject& result, MojErr findErr) { if (findErr) { MojString error; MojErrToString(findErr, error); MojLogError(IMServiceApp::s_log, _T("findAccountIdResult failed: error %d - %s"), findErr, error.data()); } else { // parse out the accountId readAccountIdFromResults(result); if (!m_accountId.empty()){ // construct our where clause - find by username, accountId and servicename MojDbQuery query; query.where("username", MojDbQuery::OpEq, m_buddyName); query.where("accountId", MojDbQuery::OpEq, m_accountId); query.from(IM_BUDDYSTATUS_KIND); // call del // virtual MojErr del(Signal::SlotRef handler, const MojDbQuery& query, // MojUInt32 flags = MojDb::FlagNone); MojErr err = m_tempdbClient.del(m_removeBuddySlot, query); if (err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("removeBuddy: dbClient.del() failed: error %d - %s"), err, error.data()); // tell the outgoing Command handler we are done m_outgoingIMHandler->messageFinished(); } } else { MojLogError(IMServiceApp::s_log, _T("findAccountIdResult: no matching loginState record found for %s %s"), m_username.data(), m_serviceName.data()); // tell the outgoing Command handler we are done m_outgoingIMHandler->messageFinished(); } } return MojErrNone; }
MojErr LogoutCommand::HandleResponse(const std::string& line) { if (m_status != Status_Ok) { MojLogError(m_log, "Error response in logging out pop session: %s", line.c_str()); } m_session.LogoutDone(); Complete(); return MojErrNone; }
/* places all processes of current container into either the focused * * cgroup or to the sub-cgroup of the given priority */ void ControlGroup::SetPriority(ActivityPriority_t priority, bool focused) { bool success = true; char buf[8]; size_t length; std::list<int>::iterator pid, nextPid; MojLogTrace(s_log); MojLogInfo(s_log, _T("Setting priority of [Container %s] to [%s,%s]"), m_name.c_str(), ActivityPriorityNames[priority], focused ? "focused" : "unfocused"); const char* shares[] = { "none", /* ActivityPriorityNone */ "lowest", /* ActivityPriorityLowest */ "low", /* ActivityPriorityLow */ "normal", /* ActivityPriorityNormal */ "high", /* ActivityPriorityHigh */ "highest" /* ActivityPriorityHighest */ }; std::string controlFile; if (focused) { controlFile = GetRoot() + "/focused/tasks"; } else { controlFile = GetRoot() + "/unfocused/" + shares[priority] + "/tasks"; } pid = m_processIds.begin(); while(pid!= m_processIds.end()) { nextPid = pid; nextPid++; length = snprintf(buf, 8, "%d", (int)*pid); success = success && WriteControlFile(controlFile, buf, length, pid); // Fix for roadrunner if(pid == m_processIds.begin() && !success && !focused) { controlFile = GetRoot() + "/unfocused/tasks"; success = success || WriteControlFile(controlFile, buf, length, pid); } pid = nextPid; } if (success) { m_currentPriority = priority; m_focused = focused; } else { MojLogError(s_log, _T("Failed to change priority of [Container %s] " "to [%s,%s]"), m_name.c_str(), ActivityPriorityNames[priority], focused ? "focused" : "unfocused"); } }
/* * Parse the account id from the results object for the accountId query * saved in m_accountId member variable * */ MojErr SendOneMessageHandler::readAccountIdFromResults(MojObject& result) { // log the results MojString mojStringJson; result.toJson(mojStringJson); MojLogDebug(IMServiceApp::s_log, _T("readAccountIdFromResults result: %s"), mojStringJson.data()); // "results" in result MojObject results; result.get(_T("results"), results); // check to see if array is empty - there should really always be 1 item here if (!results.empty()){ // get the db id of the buddy MojObject loginState; MojObject::ConstArrayIterator itr = results.arrayBegin(); bool foundOne = false; while (itr != results.arrayEnd()) { if (foundOne) { MojLogError(IMServiceApp::s_log, _T("readAccountIdFromResults: found more than one ImLoginState with same username/serviceName - using the first one")); break; } loginState = *itr; foundOne = true; itr++; } // create the DB object MojErr err = loginState.getRequired("accountId", m_accountId); if (err) { MojLogError(IMServiceApp::s_log, _T("readAccountIdFromResults: missing accountId in loginState entry")); } MojLogInfo(IMServiceApp::s_log, _T("readAccountIdFromResults - accountId: %s. "), m_accountId.data()); } else { MojLogError(IMServiceApp::s_log, _T("readAccountIdFromResults: no matching loginState record found for %s"), m_serviceName.data()); } return MojErrNone; }
void PopSession::SetError(MailError::ErrorCode errCode, const std::string& errMsg) { if (errCode != MailError::NONE) { MojLogError(m_log, "------ Setting account error: [%d]%s", (int)errCode, errMsg.c_str()); } m_accountError.errorCode = errCode; m_accountError.errorText = errMsg; if (m_syncSession.get() && (m_syncSession->IsActive() || m_syncSession->IsStarting())) { m_syncSession->SetAccountError(m_accountError); } }
/* * Callback for DB delete results * deleted buddyStatus record */ MojErr SendOneCommandHandler::removeBuddyResult(MojObject& result, MojErr delErr) { MojLogTrace(IMServiceApp::s_log); if (delErr) { MojString error; MojErrToString(delErr, error); MojLogError(IMServiceApp::s_log, _T("removeBuddyResult failed. error %d - %s"), delErr, error.data()); } else { MojString json; result.toJson(json); MojLogInfo(IMServiceApp::s_log, _T("removeBuddyResult response: %s"), json.data()); } // now delete from contacts DB //construct our where clause - find by username and servicename MojDbQuery query; MojErr err; err = createContactQuery(query); if (err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("removeBuddyResult: createContactsQuery failed: error %d - %s"), err, error.data()); } // call del // virtual MojErr del(Signal::SlotRef handler, const MojDbQuery& query, // MojUInt32 flags = MojDb::FlagNone); err = m_dbClient.del(this->m_removeContactSlot, query); if (err) { MojString error; MojErrToString(err, error); MojLogError(IMServiceApp::s_log, _T("removeBuddyResult: dbClient.del() failed: error %d - %s"), err, error.data()); // tell the outgoing Command handler we are done m_outgoingIMHandler->messageFinished(); } return MojErrNone; }
void ConnectCommand::ConnectFailure(const exception& e) { CommandTraceFunction(); MojLogError(m_log, "error connecting to server: %s", e.what()); if(m_connection.get()) { m_connection->Shutdown(); } m_session.ConnectFailure(e); Failure(e); }