InternalProviders, and ManagementAgent source code.
void CachingConnectionFactoryObj::initializeBean(
const IBean::Cargs& ctorArgs,
const IBean::Cprops& properties) {
- CAF_CM_FUNCNAME_VALIDATE("initializeBean");
+ CAF_CM_FUNCNAME("initializeBean");
CAF_CM_PRECOND_ISNOTINITIALIZED(_factory);
CAF_CM_VALIDATE_STL_EMPTY(ctorArgs);
const std::string persistenceDir = AppConfigUtils::getRequiredString(
"persistence_dir");
- const SmartPtrCPersistenceProtocolDoc persistenceProtocol = CPersistenceUtils::loadPersistenceProtocol(
- persistenceDir);
+ const SmartPtrCPersistenceProtocolDoc persistenceProtocol =
+ CPersistenceUtils::loadPersistenceProtocol(persistenceDir);
+
+ if (persistenceProtocol.IsNull()) {
+ CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, ERROR_INVALID_STATE,
+ "Persistence protocol is empty... Comm must be configured - %s",
+ persistenceDir.c_str());
+ }
UriUtils::SUriRecord uri;
UriUtils::parseUriString(persistenceProtocol->getUri(), uri);
}
SmartPtrIIntMessage AmqpMessageListenerSource::doReceive(const int32 timeout) {
- CAF_CM_FUNCNAME_VALIDATE("doReceive");
+ CAF_CM_FUNCNAME("doReceive");
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
gpointer data = NULL;
if (timeout < 0) {
// blocking
- data = g_async_queue_pop(_messageQueue);
+ CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG,
+ "Infinite blocking is not supported for a polled channel: %s", _id.c_str());
+ //data = g_async_queue_pop(_messageQueue);
} else if (timeout == 0) {
// immediate
data = g_async_queue_try_pop(_messageQueue);
} else {
// timed
- gint64 microTimeout = timeout * 1000;
+ guint64 microTimeout = static_cast<guint64>(timeout) * 1000;
data = g_async_queue_timeout_pop(_messageQueue, microTimeout);
}
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_ASSERT(_isRunning);
- gint64 microTimeout = timeout * 1000;
+ guint64 microTimeout = static_cast<guint64>(timeout) * 1000;
gpointer data = g_async_queue_timeout_pop(_deliveryQueue, microTimeout);
checkShutdown();
SmartPtrCIntegrationAppContext intAppContext;
try {
CLoggingUtils::setStartupConfigFile(
- AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile));
- CLoggingUtils::setLogDir(
+ AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile),
AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir));
uint32 intStartupTimeout = AppConfigUtils::getOptionalUint32(
CWinService::initialize(_gAmqpListenerWorker);
CWinService::execute(argc, argv);
#else
- Cdeqstr parts = CStringUtils::split(argv[0], G_DIR_SEPARATOR);
+ const std::string procPath = argv[0];
+ Cdeqstr parts = CStringUtils::split(procPath, G_DIR_SEPARATOR);
std::string procName = "CommAmqpListener";
if (parts.size()) {
procName = parts.back();
CDaemonUtils::MakeDaemon(
argc,
argv,
- procName.c_str(),
+ procPath,
+ procName,
TermHandler,
_gDaemonized,
_gSysLogInfos);
CLoggingUtils::setStartupConfigFile(
- AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile));
- CLoggingUtils::setLogDir(
+ AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile),
AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir));
_gAmqpListenerWorker->doWork();
void initialize(
const std::string& protocolName = std::string(),
const std::string& uri = std::string(),
+ const std::string& uriAmqp = std::string(),
+ const std::string& uriTunnel = std::string(),
const std::string& tlsCert = std::string(),
const std::string& tlsProtocol = std::string(),
const Cdeqstr& tlsCipherCollection = Cdeqstr(),
if (! _isInitialized) {
_protocolName = protocolName;
_uri = uri;
+ _uriAmqp = uriAmqp;
+ _uriTunnel = uriTunnel;
_tlsCert = tlsCert;
_tlsProtocol = tlsProtocol;
_tlsCipherCollection = tlsCipherCollection;
return _uri;
}
+ /// Accessor for the UriAmqp
+ std::string getUriAmqp() const {
+ return _uriAmqp;
+ }
+
+ /// Accessor for the UriTunnel
+ std::string getUriTunnel() const {
+ return _uriTunnel;
+ }
+
/// Accessor for the TlsCert
std::string getTlsCert() const {
return _tlsCert;
private:
std::string _protocolName;
std::string _uri;
+ std::string _uriAmqp;
+ std::string _uriTunnel;
std::string _tlsCert;
std::string _tlsProtocol;
Cdeqstr _tlsCipherCollection;
return rc;
}
+int32 AppConfigUtils::getRequiredInt32(
+ const std::string& parameterName) {
+ int32 rc;
+ getAppConfig()->getGlobalInt32(parameterName, rc, IConfigParams::PARAM_REQUIRED);
+ return rc;
+}
+
bool AppConfigUtils::getRequiredBoolean(
const std::string& parameterName) {
bool rc;
return rc;
}
+int32 AppConfigUtils::getOptionalInt32(
+ const std::string& parameterName) {
+ int32 rc = 0;
+ getAppConfig()->getGlobalInt32(parameterName, rc, IConfigParams::PARAM_OPTIONAL);
+ return rc;
+}
+
bool AppConfigUtils::getOptionalBoolean(
const std::string& parameterName) {
bool rc = false;
return rc;
}
+int32 AppConfigUtils::getRequiredInt32(
+ const std::string& sectionName,
+ const std::string& parameterName) {
+ int32 rc;
+ getAppConfig()->getInt32(sectionName, parameterName, rc, IConfigParams::PARAM_REQUIRED);
+ return rc;
+}
+
bool AppConfigUtils::getRequiredBoolean(
const std::string& sectionName,
const std::string& parameterName) {
return rc;
}
+int32 AppConfigUtils::getOptionalInt32(
+ const std::string& sectionName,
+ const std::string& parameterName) {
+ int32 rc = 0;
+ getAppConfig()->getInt32(sectionName, parameterName, rc, IConfigParams::PARAM_OPTIONAL);
+ return rc;
+}
+
bool AppConfigUtils::getOptionalBoolean(
const std::string& sectionName,
const std::string& parameterName) {
std::string COMMONAGGREGATOR_LINKAGE getRequiredString(const std::string& parameterName);
uint32 COMMONAGGREGATOR_LINKAGE getRequiredUint32(const std::string& parameterName);
+ int32 COMMONAGGREGATOR_LINKAGE getRequiredInt32(const std::string& parameterName);
bool COMMONAGGREGATOR_LINKAGE getRequiredBoolean(const std::string& parameterName);
std::string COMMONAGGREGATOR_LINKAGE getOptionalString(const std::string& parameterName);
uint32 COMMONAGGREGATOR_LINKAGE getOptionalUint32(const std::string& parameterName);
+ int32 COMMONAGGREGATOR_LINKAGE getOptionalInt32(const std::string& parameterName);
bool COMMONAGGREGATOR_LINKAGE getOptionalBoolean(const std::string& parameterName);
std::string COMMONAGGREGATOR_LINKAGE getRequiredString(
uint32 COMMONAGGREGATOR_LINKAGE getRequiredUint32(
const std::string& sectionName,
const std::string& parameterName);
+ int32 COMMONAGGREGATOR_LINKAGE getRequiredInt32(
+ const std::string& sectionName,
+ const std::string& parameterName);
bool COMMONAGGREGATOR_LINKAGE getRequiredBoolean(
const std::string& sectionName,
const std::string& parameterName);
uint32 COMMONAGGREGATOR_LINKAGE getOptionalUint32(
const std::string& sectionName,
const std::string& parameterName);
+ int32 COMMONAGGREGATOR_LINKAGE getOptionalInt32(
+ const std::string& sectionName,
+ const std::string& parameterName);
bool COMMONAGGREGATOR_LINKAGE getOptionalBoolean(
const std::string& sectionName,
const std::string& parameterName);
parameterName.c_str(),
IConfigParams::PARAM_OPTIONAL);
if (param) {
- if (g_variant_is_of_type(param, G_VARIANT_TYPE_UINT32)) {
- value = g_variant_get_uint32(param);
+ if (g_variant_is_of_type(param, G_VARIANT_TYPE_INT32)) {
+ value = static_cast<uint32>(g_variant_get_int32(param));
paramFound = true;
} else {
std::string valueStr;
return paramFound;
}
+bool CAppConfig::getInt32(
+ const std::string& sectionName,
+ const std::string& parameterName,
+ int32& value,
+ const IConfigParams::EParamDisposition disposition) {
+ CAF_CM_FUNCNAME("getInt32");
+ CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
+ CAF_CM_VALIDATE_STRING(sectionName);
+ CAF_CM_VALIDATE_STRING(parameterName);
+
+ bool paramFound = false;
+
+ SmartPtrIConfigParams params = getParameters(sectionName);
+ GVariant* param = params->lookup(
+ parameterName.c_str(),
+ IConfigParams::PARAM_OPTIONAL);
+ if (param) {
+ if (g_variant_is_of_type(param, G_VARIANT_TYPE_INT32)) {
+ value = g_variant_get_int32(param);
+ paramFound = true;
+ } else {
+ std::string valueStr;
+ getString(sectionName, parameterName, valueStr, disposition);
+ value = CStringConv::fromString<int32>(valueStr);
+ }
+ } else {
+ if (IConfigParams::PARAM_REQUIRED == disposition) {
+ CAF_CM_EXCEPTION_VA2(ERROR_TAG_NOT_FOUND,
+ "Required config parameter [%s] is missing from section [%s]",
+ parameterName.c_str(),
+ sectionName.c_str());
+ }
+ }
+
+ return paramFound;
+}
+
bool CAppConfig::getBoolean(
const std::string& sectionName,
const std::string& parameterName,
return getUint32(_sGlobalsSectionName, parameterName, value, disposition);
}
+bool CAppConfig::getGlobalInt32(
+ const std::string& parameterName,
+ int32& value,
+ const IConfigParams::EParamDisposition disposition) {
+ return getInt32(_sGlobalsSectionName, parameterName, value, disposition);
+}
+
bool CAppConfig::getGlobalBoolean(
const std::string& parameterName,
bool& value,
CAF_CM_VALIDATE_STRING(parameterName);
SmartPtrIConfigParams params = getParameters(sectionName);
- params->insert(g_strdup(parameterName.c_str()), g_variant_new_uint32(
+ params->insert(g_strdup(parameterName.c_str()), g_variant_new_int32(
+ value));
+}
+
+void CAppConfig::setInt32(
+ const std::string& sectionName,
+ const std::string& parameterName,
+ const int32& value) {
+ CAF_CM_FUNCNAME_VALIDATE("setInt32");
+ CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
+ CAF_CM_VALIDATE_STRING(sectionName);
+ CAF_CM_VALIDATE_STRING(parameterName);
+
+ SmartPtrIConfigParams params = getParameters(sectionName);
+ params->insert(g_strdup(parameterName.c_str()), g_variant_new_int32(
value));
}
setUint32(_sGlobalsSectionName, parameterName, value);
}
+void CAppConfig::setGlobalInt32(
+ const std::string& parameterName,
+ const int32& value) {
+ setInt32(_sGlobalsSectionName, parameterName, value);
+}
+
void CAppConfig::setGlobalBoolean(
const std::string& parameterName,
const bool& value) {
if (!resolved) {
try {
- uint32 uval = 0;
- getUint32(
+ int32 uval = 0;
+ getInt32(
section,
varName,
uval,
IConfigParams::PARAM_REQUIRED);
- configVal = CStringConv::toString<uint32>(uval);
+ configVal = CStringConv::toString<int32>(uval);
resolved = true;
} catch (CCafException *ex) {
if (ex->getError() == DISP_E_TYPEMISMATCH) {
for (gsize idx = 0; idx < numKeys; idx++) {
// There is no way to tell if a value is an integer or string.
- // We want to insert the value as either string or uint32 so
+ // We want to insert the value as either string or int32 so
// try to read the value as an integer. If it cannot be read
// as an integer then insert it as a string.
gint iValue = g_key_file_get_integer(
keys[idx],
&configError);
if (!configError) {
- configParams->insert(g_strdup(keys[idx]), g_variant_new_uint32(
+ configParams->insert(g_strdup(keys[idx]), g_variant_new_int32(
iValue));
if (isGlobals) {
GVariant* thread_stack_size_kb = globals->lookup(
_sAppConfigGlobalThreadStackSizeKb,
IConfigParams::PARAM_REQUIRED);
- CAF_CM_ASSERT(g_variant_is_of_type(thread_stack_size_kb, G_VARIANT_TYPE_UINT32));
+ CAF_CM_ASSERT(g_variant_is_of_type(thread_stack_size_kb, G_VARIANT_TYPE_INT32));
}
std::string CAppConfig::calcConfigPath(
const IConfigParams::EParamDisposition disposition =
IConfigParams::PARAM_REQUIRED);
+ bool
+ getInt32(
+ const std::string& sectionName,
+ const std::string& parameterName,
+ int32& value,
+ const IConfigParams::EParamDisposition disposition =
+ IConfigParams::PARAM_REQUIRED);
+
bool
getBoolean(
const std::string& sectionName,
const IConfigParams::EParamDisposition disposition =
IConfigParams::PARAM_REQUIRED);
+ bool
+ getGlobalInt32(
+ const std::string& parameterName,
+ int32& value,
+ const IConfigParams::EParamDisposition disposition =
+ IConfigParams::PARAM_REQUIRED);
+
bool
getGlobalBoolean(
const std::string& parameterName,
const std::string& parameterName,
const uint32& value);
+ void setInt32(const std::string& sectionName,
+ const std::string& parameterName,
+ const int32& value);
+
void setBoolean(const std::string& sectionName,
const std::string& parameterName,
const bool& value);
void setGlobalUint32(const std::string& parameterName,
const uint32& value);
+ void setGlobalInt32(const std::string& parameterName,
+ const int32& value);
+
void setGlobalBoolean(const std::string& parameterName,
const bool& value);
void CApplicationContext::initialize() {
CAF_CM_FUNCNAME_VALIDATE("initialize");
+ CAF_CM_PRECOND_ISNOTINITIALIZED(m_isInitialized);
- CAF_CM_ENTER {
- CAF_CM_PRECOND_ISNOTINITIALIZED(m_isInitialized);
+ const std::string beanConfigFile = getDefaultBeanConfigFile();
- const std::string beanConfigFile = getDefaultBeanConfigFile();
+ Cdeqstr filenameCollection;
+ filenameCollection.push_front(beanConfigFile);
- Cdeqstr filenameCollection;
- filenameCollection.push_front(beanConfigFile);
-
- initialize(filenameCollection);
- }
- CAF_CM_EXIT;
+ initialize(filenameCollection);
}
void CApplicationContext::initialize(const Cdeqstr& filenameCollection) {
CAF_CM_FUNCNAME("initialize");
+ CAF_CM_PRECOND_ISNOTINITIALIZED(m_isInitialized);
+ CAF_CM_VALIDATE_STL(filenameCollection);
- CAF_CM_ENTER {
- CAF_CM_PRECOND_ISNOTINITIALIZED(m_isInitialized);
- CAF_CM_VALIDATE_STL(filenameCollection);
+ for (TConstIterator<Cdeqstr> filenameIter(filenameCollection);
+ filenameIter; filenameIter++) {
+ const std::string beanConfigFile = *filenameIter;
- for (TConstIterator<Cdeqstr> filenameIter(filenameCollection);
- filenameIter; filenameIter++) {
- const std::string beanConfigFile = *filenameIter;
+ parseBeanConfig(
+ beanConfigFile,
+ _beanCollection);
+ }
- parseBeanConfig(
- beanConfigFile,
- _beanCollection);
- }
+ CBeanGraph beanGraph;
+ createBeanGraph(
+ _beanCollection,
+ beanGraph,
+ _beanTopologySort);
- CBeanGraph beanGraph;
- createBeanGraph(
+ try {
+ initializeBeans(
_beanCollection,
- beanGraph,
_beanTopologySort);
+ } CAF_CM_CATCH_ALL;
+ if (CAF_CM_ISEXCEPTION) {
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CCafException *ex = CAF_CM_GETEXCEPTION;
+ ex->AddRef();
+ CAF_CM_CLEAREXCEPTION;
try {
- initializeBeans(
- _beanCollection,
- _beanTopologySort);
+ terminateBeans(_beanTopologySort);
} CAF_CM_CATCH_ALL;
- if (CAF_CM_ISEXCEPTION) {
- CAF_CM_LOG_CRIT_CAFEXCEPTION;
- CCafException *ex = CAF_CM_GETEXCEPTION;
- ex->AddRef();
- CAF_CM_CLEAREXCEPTION;
- try {
- terminateBeans(_beanTopologySort);
- } CAF_CM_CATCH_ALL;
- CAF_CM_LOG_CRIT_CAFEXCEPTION;
- CAF_CM_CLEAREXCEPTION;
- _beanTopologySort.clear();
- _beanCollection.clear();
- CAF_CM_GETEXCEPTION = ex;
- CAF_CM_THROWEXCEPTION;
- }
- m_isInitialized = true;
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CAF_CM_CLEAREXCEPTION;
+ _beanTopologySort.clear();
+ _beanCollection.clear();
+ CAF_CM_GETEXCEPTION = ex;
+ CAF_CM_THROWEXCEPTION;
}
- CAF_CM_EXIT;
+
+ m_isInitialized = true;
}
void CApplicationContext::terminate() {
CAF_CM_FUNCNAME_VALIDATE("terminate");
+ CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized);
- CAF_CM_ENTER {
- CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized);
- terminateBeans(_beanTopologySort);
- _beanTopologySort.clear();
- _beanCollection.clear();
- _filenameCollection.clear();
- }
- CAF_CM_EXIT;
+ terminateBeans(_beanTopologySort);
+ _beanTopologySort.clear();
+ _beanCollection.clear();
+ _filenameCollection.clear();
}
IAppContext::SmartPtrCBeans CApplicationContext::getBeans() const {
CAF_CM_FUNCNAME_VALIDATE("getBeans");
+ CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized);
SmartPtrCBeans beans;
beans.CreateInstance();
-
- CAF_CM_ENTER {
- CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized);
-
- for (TSmartConstMapIterator<CBeanCollection> beanIter(_beanCollection);
- beanIter; beanIter++) {
- beans->insert(CBeans::value_type(
- beanIter.getKey().c_str(),
- beanIter->_bean));
- }
+ for (TSmartConstMapIterator<CBeanCollection> beanIter(_beanCollection);
+ beanIter; beanIter++) {
+ beans->insert(CBeans::value_type(
+ beanIter.getKey().c_str(),
+ beanIter->_bean));
}
- CAF_CM_EXIT;
return beans;
}
SmartPtrIBean CApplicationContext::getBean(const std::string& beanId) const {
CAF_CM_FUNCNAME("getBean");
-
- SmartPtrIBean rc;
-
- CAF_CM_ENTER {
- CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized);
- CAF_CM_VALIDATE_STRING(beanId);
-
- CBeanCollection::const_iterator iter = _beanCollection.find(beanId);
- if (iter == _beanCollection.end()) {
- CAF_CM_EXCEPTIONEX_VA1(
- NoSuchElementException,
- 0,
- "Bean not found - %s",
- beanId.c_str());
- }
-
- CAF_CM_LOG_DEBUG_VA1(
- "Bean Found - %s",
+ CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized);
+ CAF_CM_VALIDATE_STRING(beanId);
+
+ CBeanCollection::const_iterator iter = _beanCollection.find(beanId);
+ if (iter == _beanCollection.end()) {
+ CAF_CM_EXCEPTIONEX_VA1(
+ NoSuchElementException,
+ 0,
+ "Bean not found - %s",
beanId.c_str());
- rc = iter->second->_bean;
}
- CAF_CM_EXIT;
- return rc;
+ CAF_CM_LOG_DEBUG_VA1(
+ "Bean Found - %s",
+ beanId.c_str());
+ return iter->second->_bean;
}
std::string CApplicationContext::getDefaultBeanConfigFile() const {
-
CAF_CM_FUNCNAME("parseBeanConfig");
- std::string beanConfigFile;
-
- CAF_CM_ENTER {
- // Get the bean config file
- beanConfigFile = AppConfigUtils::getRequiredString("bean_config_file");
- if (!FileSystemUtils::doesFileExist(beanConfigFile)) {
- CAF_CM_EXCEPTIONEX_VA1(
- FileNotFoundException,
- 0,
- "The bean config file [%s] does not exist.",
- beanConfigFile.c_str());
- }
+ // Get the bean config file
+ const std::string beanConfigFile =
+ AppConfigUtils::getRequiredString("bean_config_file");
+ if (!FileSystemUtils::doesFileExist(beanConfigFile)) {
+ CAF_CM_EXCEPTIONEX_VA1(
+ FileNotFoundException,
+ 0,
+ "The bean config file [%s] does not exist.",
+ beanConfigFile.c_str());
}
- CAF_CM_EXIT;
return beanConfigFile;
}
void CApplicationContext::parseBeanConfig(
const std::string& beanConfigFile,
CBeanCollection& beanCollection) const {
-
CAF_CM_FUNCNAME("parseBeanConfig");
-
- CAF_CM_ENTER {
- CAF_CM_VALIDATE_STRING(beanConfigFile);
-
- CAF_CM_LOG_DEBUG_VA1("Parsing bean config file %s", beanConfigFile.c_str());
-
- // We will look up class references early in the process to fail as early
- // as possible and to make logging better.
- // Parse the bean config file
- CXmlElement::SmartPtrCElementCollection rootElements =
- CXmlUtils::parseFile(beanConfigFile, "caf:beans")->getAllChildren();
- for (TSmartConstMultimapIterator<CXmlElement::CElementCollection> rootChild(*rootElements);
- rootChild;
- rootChild++) {
-
- // if the child is a bean...
- if (rootChild->getName() == "bean") {
- // Syntactic sugar
- const SmartPtrCXmlElement beanElement = *rootChild;
-
- // Bean attributes
- const std::string beanId = beanElement->findRequiredAttribute("id");
- CAF_CM_LOG_DEBUG_VA1("Parsing bean [id=%s]", beanId.c_str());
- const std::string beanClass = beanElement->findRequiredAttribute("class");
- CAF_CM_LOG_DEBUG_VA2(
- "Checking bean class [id=%s][class=%s]",
+ CAF_CM_VALIDATE_STRING(beanConfigFile);
+ CAF_CM_LOG_DEBUG_VA1("Parsing bean config file %s", beanConfigFile.c_str());
+
+ // We will look up class references early in the process to fail as early
+ // as possible and to make logging better.
+ // Parse the bean config file
+ CXmlElement::SmartPtrCElementCollection rootElements =
+ CXmlUtils::parseFile(beanConfigFile, "caf:beans")->getAllChildren();
+ for (TSmartConstMultimapIterator<CXmlElement::CElementCollection> rootChild(*rootElements);
+ rootChild;
+ rootChild++) {
+
+ // if the child is a bean...
+ if (rootChild->getName() == "bean") {
+ // Syntactic sugar
+ const SmartPtrCXmlElement beanElement = *rootChild;
+
+ // Bean attributes
+ const std::string beanId = beanElement->findRequiredAttribute("id");
+ CAF_CM_LOG_DEBUG_VA1("Parsing bean [id=%s]", beanId.c_str());
+ const std::string beanClass = beanElement->findRequiredAttribute("class");
+ CAF_CM_LOG_DEBUG_VA2(
+ "Checking bean class [id=%s][class=%s]",
+ beanId.c_str(),
+ beanClass.c_str());
+ if (!CEcmSubSystemRegistry::IsRegistered(beanClass)) {
+ CAF_CM_EXCEPTIONEX_VA3(
+ NoSuchElementException,
+ 0,
+ "Bean class %s is not registered. Fix the AppConfig file. "
+ "[bean id=%s][bean_config_file=%s]",
+ beanClass.c_str(),
beanId.c_str(),
- beanClass.c_str());
- if (!CEcmSubSystemRegistry::IsRegistered(beanClass)) {
- CAF_CM_EXCEPTIONEX_VA3(
- NoSuchElementException,
- 0,
- "Bean class %s is not registered. Fix the AppConfig file. "
- "[bean id=%s][bean_config_file=%s]",
- beanClass.c_str(),
- beanId.c_str(),
- beanConfigFile.c_str());
- }
+ beanConfigFile.c_str());
+ }
- // get optional constructor args and properties
- CBeanCtorArgCollection beanCtorArgs;
- Cmapstrstr beanProperties;
- CAF_CM_LOG_DEBUG_VA1("Parsing bean ctor args and properties [id=%s]", beanId.c_str());
- CXmlElement::SmartPtrCElementCollection beanElements = beanElement->getAllChildren();
- for (TSmartConstMultimapIterator<CXmlElement::CElementCollection> beanChild(*beanElements);
- beanChild;
- beanChild++) {
- if (beanChild->getName() == "property") {
- // Syntactic sugar
- const SmartPtrCXmlElement propArgElement = *beanChild;
-
- // property attributes
- const std::string name = propArgElement->findRequiredAttribute("name");
- const std::string value = propArgElement->findRequiredAttribute("value");
- if (!beanProperties.insert(std::make_pair(name, value)).second) {
- CAF_CM_EXCEPTIONEX_VA3(
- DuplicateElementException,
- 0,
- "Bean property name is duplicated. "
- "[bean id=%s][property name=%s][bean_config_file=%s]",
- beanId.c_str(),
- name.c_str(),
- beanConfigFile.c_str());
- }
+ // get optional constructor args and properties
+ CBeanCtorArgCollection beanCtorArgs;
+ Cmapstrstr beanProperties;
+ CAF_CM_LOG_DEBUG_VA1("Parsing bean ctor args and properties [id=%s]", beanId.c_str());
+ CXmlElement::SmartPtrCElementCollection beanElements = beanElement->getAllChildren();
+ for (TSmartConstMultimapIterator<CXmlElement::CElementCollection> beanChild(*beanElements);
+ beanChild;
+ beanChild++) {
+ if (beanChild->getName() == "property") {
+ // Syntactic sugar
+ const SmartPtrCXmlElement propArgElement = *beanChild;
+
+ // property attributes
+ const std::string name = propArgElement->findRequiredAttribute("name");
+ const std::string value = propArgElement->findRequiredAttribute("value");
+ if (!beanProperties.insert(std::make_pair(name, value)).second) {
+ CAF_CM_EXCEPTIONEX_VA3(
+ DuplicateElementException,
+ 0,
+ "Bean property name is duplicated. "
+ "[bean id=%s][property name=%s][bean_config_file=%s]",
+ beanId.c_str(),
+ name.c_str(),
+ beanConfigFile.c_str());
}
- else if (beanChild->getName() == "constructor-arg") {
- // Syntactic sugar
- const SmartPtrCXmlElement ctorArgElement = *beanChild;
-
- // ctor attributes
- const uint32 ctorArgIndex = CStringConv::fromString<uint32>(ctorArgElement->findRequiredAttribute("index"));
- CBeanCtorArg::ARG_TYPE ctorArgType = CBeanCtorArg::NOT_SET;
- std::string ctorArgValue = ctorArgElement->findOptionalAttribute("value");
+ }
+ else if (beanChild->getName() == "constructor-arg") {
+ // Syntactic sugar
+ const SmartPtrCXmlElement ctorArgElement = *beanChild;
+
+ // ctor attributes
+ const uint32 ctorArgIndex = CStringConv::fromString<uint32>(ctorArgElement->findRequiredAttribute("index"));
+ CBeanCtorArg::ARG_TYPE ctorArgType = CBeanCtorArg::NOT_SET;
+ std::string ctorArgValue = ctorArgElement->findOptionalAttribute("value");
+ if (ctorArgValue.length() > 0) {
+ ctorArgType = CBeanCtorArg::VALUE;
+ } else {
+ ctorArgValue = ctorArgElement->findOptionalAttribute("ref");
if (ctorArgValue.length() > 0) {
- ctorArgType = CBeanCtorArg::VALUE;
+ ctorArgType = CBeanCtorArg::REFERENCE;
} else {
- ctorArgValue = ctorArgElement->findOptionalAttribute("ref");
- if (ctorArgValue.length() > 0) {
- ctorArgType = CBeanCtorArg::REFERENCE;
- } else {
- CAF_CM_EXCEPTIONEX_VA2(
- InvalidArgumentException,
- 0,
- "Bean constructor argument must be of type value or ref and cannot be empty. "
- "[bean id=%s][bean_config_file=%s]",
- beanId.c_str(),
- beanConfigFile.c_str());
- }
- }
-
- if (!beanCtorArgs.insert(
- CBeanCtorArgCollection::value_type(
- ctorArgIndex,
- CBeanCtorArg(ctorArgType, ctorArgValue))).second) {
- CAF_CM_EXCEPTIONEX_VA3(
- DuplicateElementException,
+ CAF_CM_EXCEPTIONEX_VA2(
+ InvalidArgumentException,
0,
- "Bean has a duplicate constructor-arg index. "
- "[bean id=%s][bean_config_file=%s][arg-index=%d]",
+ "Bean constructor argument must be of type value or ref and cannot be empty. "
+ "[bean id=%s][bean_config_file=%s]",
beanId.c_str(),
- beanConfigFile.c_str(),
- ctorArgIndex);
+ beanConfigFile.c_str());
}
- CAF_CM_LOG_DEBUG_VA4(
- "Bean ctor arg parsed [id=%s][arg-index=%d][arg-type=%s][arg-value=%s]",
- beanId.c_str(),
- ctorArgIndex,
- (CBeanCtorArg::VALUE == ctorArgType ? "VALUE" : "REFERENCE"),
- ctorArgValue.c_str());
}
- }
- // Add the bean definition to the collection
- SmartPtrCBeanNode beanNode;
- beanNode.CreateInstance();
- beanNode->_id = beanId;
- beanNode->_class = beanClass;
- beanNode->_ctorArgs = beanCtorArgs;
- beanNode->_properties = beanProperties;
-
- if (!beanCollection.insert(
- CBeanCollection::value_type(
- beanId,
- beanNode)).second) {
- CAF_CM_EXCEPTIONEX_VA3(
- DuplicateElementException,
- 0,
- "Duplicate bean definition detected. "
- "[bean id=%s][bean class=%s][bean_config_file=%s]",
+ if (!beanCtorArgs.insert(
+ CBeanCtorArgCollection::value_type(
+ ctorArgIndex,
+ CBeanCtorArg(ctorArgType, ctorArgValue))).second) {
+ CAF_CM_EXCEPTIONEX_VA3(
+ DuplicateElementException,
+ 0,
+ "Bean has a duplicate constructor-arg index. "
+ "[bean id=%s][bean_config_file=%s][arg-index=%d]",
+ beanId.c_str(),
+ beanConfigFile.c_str(),
+ ctorArgIndex);
+ }
+ CAF_CM_LOG_DEBUG_VA4(
+ "Bean ctor arg parsed [id=%s][arg-index=%d][arg-type=%s][arg-value=%s]",
beanId.c_str(),
- beanNode->_class.c_str(),
- beanConfigFile.c_str());
+ ctorArgIndex,
+ (CBeanCtorArg::VALUE == ctorArgType ? "VALUE" : "REFERENCE"),
+ ctorArgValue.c_str());
}
}
- }
- CAF_CM_LOG_DEBUG_VA2(
- "Bean configuration file defined %d beans. "
- "[file=%s]",
- beanCollection.size(),
- beanConfigFile.c_str());
+ // Add the bean definition to the collection
+ SmartPtrCBeanNode beanNode;
+ beanNode.CreateInstance();
+ beanNode->_id = beanId;
+ beanNode->_class = beanClass;
+ beanNode->_ctorArgs = beanCtorArgs;
+ beanNode->_properties = beanProperties;
+
+ if (!beanCollection.insert(
+ CBeanCollection::value_type(
+ beanId,
+ beanNode)).second) {
+ CAF_CM_EXCEPTIONEX_VA3(
+ DuplicateElementException,
+ 0,
+ "Duplicate bean definition detected. "
+ "[bean id=%s][bean class=%s][bean_config_file=%s]",
+ beanId.c_str(),
+ beanNode->_class.c_str(),
+ beanConfigFile.c_str());
+ }
+ }
}
- CAF_CM_EXIT;
+
+ CAF_CM_LOG_DEBUG_VA2(
+ "Bean configuration file defined %d beans. "
+ "[file=%s]",
+ beanCollection.size(),
+ beanConfigFile.c_str());
}
void CApplicationContext::createBeanGraph(
CBeanGraph::ClistVertexEdges& beanTopologySort) const {
CAF_CM_FUNCNAME("createBeanGraph");
- CAF_CM_ENTER {
- // Iterate the bean collection and create the beans. They will not be initialized.
- // Two name sets will be built: bean names and contstructor-arg ref names.
- // These two sets will be compared to ensure that all referenced beans exist.
- Csetstr beanNames;
- Csetstr beanCtorRefNames;
- for (TSmartMapIterator<CBeanCollection> beanIter(beanCollection);
- beanIter;
- beanIter++) {
-
- // Create the bean and add it to the collection
- CAF_CM_LOG_DEBUG_VA2(
- "Creating bean [id=%s][class=%s]",
- beanIter.getKey().c_str(),
- beanIter->_class.c_str());
- beanIter->_bean.CreateInstance(beanIter->_class.c_str());
-
- // Add the bean id to the beanNames set
- if (!beanNames.insert(beanIter->_id).second) {
- CAF_CM_LOG_DEBUG_VA1(
- "Internal logic error: duplicate bean detected. "
- "[id=%s]",
- beanIter->_id.c_str());
- }
+ // Iterate the bean collection and create the beans. They will not be initialized.
+ // Two name sets will be built: bean names and contstructor-arg ref names.
+ // These two sets will be compared to ensure that all referenced beans exist.
+ Csetstr beanNames;
+ Csetstr beanCtorRefNames;
+ for (TSmartMapIterator<CBeanCollection> beanIter(beanCollection);
+ beanIter;
+ beanIter++) {
- // Add ref constructor args to the ctor ref name set
- for (TConstMapIterator<CBeanCtorArgCollection> beanCtorArg(beanIter->_ctorArgs);
- beanCtorArg;
- beanCtorArg++) {
- if (CBeanCtorArg::REFERENCE == beanCtorArg->_type) {
- beanCtorRefNames.insert(beanCtorArg->_value);
- }
- }
+ // Create the bean and add it to the collection
+ CAF_CM_LOG_DEBUG_VA2(
+ "Creating bean [id=%s][class=%s]",
+ beanIter.getKey().c_str(),
+ beanIter->_class.c_str());
+ beanIter->_bean.CreateInstance(beanIter->_class.c_str());
+
+ // Add the bean id to the beanNames set
+ if (!beanNames.insert(beanIter->_id).second) {
+ CAF_CM_LOG_DEBUG_VA1(
+ "Internal logic error: duplicate bean detected. "
+ "[id=%s]",
+ beanIter->_id.c_str());
}
- // Make sure that all beans referenced as ctor args exist
- Csetstr beanNameDiff;
- std::set_difference(
- beanCtorRefNames.begin(),
- beanCtorRefNames.end(),
- beanNames.begin(),
- beanNames.end(),
- std::inserter(beanNameDiff, beanNameDiff.end()));
-
- if (beanNameDiff.size()) {
- for (TConstIterator<Csetstr> missingName(beanNameDiff);
- missingName;
- missingName++) {
- CAF_CM_LOG_ERROR_VA1(
- "No bean definition exists for constructor-arg referenced bean '%s'",
- missingName->c_str());
+ // Add ref constructor args to the ctor ref name set
+ for (TConstMapIterator<CBeanCtorArgCollection> beanCtorArg(beanIter->_ctorArgs);
+ beanCtorArg;
+ beanCtorArg++) {
+ if (CBeanCtorArg::REFERENCE == beanCtorArg->_type) {
+ beanCtorRefNames.insert(beanCtorArg->_value);
}
- CAF_CM_EXCEPTIONEX_VA0(
- NoSuchElementException,
- 0,
- "One or more bean constructor-args references beans that are not defined.");
}
+ }
- // Create a graph node for each bean
- for (TSmartConstMapIterator<CBeanCollection> beanIter(beanCollection);
- beanIter;
- beanIter++) {
- beanGraph.addVertex(*beanIter);
+ // Make sure that all beans referenced as ctor args exist
+ Csetstr beanNameDiff;
+ std::set_difference(
+ beanCtorRefNames.begin(),
+ beanCtorRefNames.end(),
+ beanNames.begin(),
+ beanNames.end(),
+ std::inserter(beanNameDiff, beanNameDiff.end()));
+
+ if (beanNameDiff.size()) {
+ for (TConstIterator<Csetstr> missingName(beanNameDiff);
+ missingName;
+ missingName++) {
+ CAF_CM_LOG_ERROR_VA1(
+ "No bean definition exists for constructor-arg referenced bean '%s'",
+ missingName->c_str());
}
+ CAF_CM_EXCEPTIONEX_VA0(
+ NoSuchElementException,
+ 0,
+ "One or more bean constructor-args references beans that are not defined.");
+ }
- // Okay. Now connect the vertices according the constructor-arg references.
- // The resulting graph will give us the initialization/tear-down order.
- for (TSmartConstMapIterator<CBeanCollection> beanIter(beanCollection);
- beanIter;
- beanIter++) {
- for (TConstMapIterator<CBeanCtorArgCollection> ctorArg(beanIter->_ctorArgs);
- ctorArg;
- ctorArg++) {
- if (CBeanCtorArg::REFERENCE == ctorArg->_type) {
- CBeanCollection::const_iterator ctorBean = beanCollection.find(ctorArg->_value);
- if (beanCollection.end() == ctorBean) {
- CAF_CM_EXCEPTIONEX_VA1(
- NoSuchElementException,
- 0,
- "Internal error: constructor-arg referenced bean '%s' is missing",
- ctorArg->_value.c_str());
- }
- beanGraph.addEdge(ctorBean->second, *beanIter);
+ // Create a graph node for each bean
+ for (TSmartConstMapIterator<CBeanCollection> beanIter(beanCollection);
+ beanIter;
+ beanIter++) {
+ beanGraph.addVertex(*beanIter);
+ }
+
+ // Okay. Now connect the vertices according the constructor-arg references.
+ // The resulting graph will give us the initialization/tear-down order.
+ for (TSmartConstMapIterator<CBeanCollection> beanIter(beanCollection);
+ beanIter;
+ beanIter++) {
+ for (TConstMapIterator<CBeanCtorArgCollection> ctorArg(beanIter->_ctorArgs);
+ ctorArg;
+ ctorArg++) {
+ if (CBeanCtorArg::REFERENCE == ctorArg->_type) {
+ CBeanCollection::const_iterator ctorBean = beanCollection.find(ctorArg->_value);
+ if (beanCollection.end() == ctorBean) {
+ CAF_CM_EXCEPTIONEX_VA1(
+ NoSuchElementException,
+ 0,
+ "Internal error: constructor-arg referenced bean '%s' is missing",
+ ctorArg->_value.c_str());
}
+ beanGraph.addEdge(ctorBean->second, *beanIter);
}
}
+ }
- // And finally - compute the bean topology sort order
- beanTopologySort = beanGraph.topologySort();
+ // And finally - compute the bean topology sort order
+ beanTopologySort = beanGraph.topologySort();
- // Debugging - you will thank me for this later
- CAF_CM_LOG_DEBUG_VA0("BEGIN: Bean initialization order")
- for (TSmartConstIterator<CBeanGraph::ClistVertexEdges> beanNode(beanTopologySort);
- beanNode;
- beanNode++) {
- CAF_CM_LOG_DEBUG_VA1("bean id=%s", beanNode->_id.c_str());
- }
- CAF_CM_LOG_DEBUG_VA0("END: Bean initialization order")
+ // Debugging - you will thank me for this later
+ CAF_CM_LOG_DEBUG_VA0("BEGIN: Bean initialization order")
+ for (TSmartConstIterator<CBeanGraph::ClistVertexEdges> beanNode(beanTopologySort);
+ beanNode;
+ beanNode++) {
+ CAF_CM_LOG_DEBUG_VA1("bean id=%s", beanNode->_id.c_str());
}
- CAF_CM_EXIT;
+ CAF_CM_LOG_DEBUG_VA0("END: Bean initialization order")
}
void CApplicationContext::initializeBeans(
CBeanGraph::ClistVertexEdges& beanTopologySort) const {
CAF_CM_FUNCNAME("initializeBeans");
- CAF_CM_ENTER {
- for (TSmartIterator<CBeanGraph::ClistVertexEdges> beanNode(beanTopologySort);
- beanNode;
- beanNode++) {
- CAF_CM_LOG_DEBUG_VA1("Initializing bean %s", beanNode->_id.c_str());
+ for (TSmartIterator<CBeanGraph::ClistVertexEdges> beanNode(beanTopologySort);
+ beanNode;
+ beanNode++) {
+ CAF_CM_LOG_DEBUG_VA1("Initializing bean %s", beanNode->_id.c_str());
- // The bean should not have been initialized
- if (beanNode->_isInitialized) {
- CAF_CM_EXCEPTIONEX_VA1(
- IllegalStateException,
- 0,
- "Internal error: Bean [%s] has already been initialized.",
- beanNode->_id.c_str());
- }
+ // The bean should not have been initialized
+ if (beanNode->_isInitialized) {
+ CAF_CM_EXCEPTIONEX_VA1(
+ IllegalStateException,
+ 0,
+ "Internal error: Bean [%s] has already been initialized.",
+ beanNode->_id.c_str());
+ }
- // Iterate the contructor-args and build a collection to
- // pass to the bean initializer
- IBean::Cargs beanInitArgs;
- for (TConstMapIterator<CBeanCtorArgCollection> ctorArg(beanNode->_ctorArgs);
- ctorArg;
- ctorArg++) {
- switch (ctorArg->_type) {
+ // Iterate the contructor-args and build a collection to
+ // pass to the bean initializer
+ IBean::Cargs beanInitArgs;
+ for (TConstMapIterator<CBeanCtorArgCollection> ctorArg(beanNode->_ctorArgs);
+ ctorArg;
+ ctorArg++) {
+ switch (ctorArg->_type) {
case CBeanCtorArg::REFERENCE: {
CBeanCollection::const_iterator bean = beanCollection.find(ctorArg->_value);
if (!bean->second->_isInitialized) {
"[bean id=%s][constructor-arg index=%d]",
beanNode->_id.c_str(),
ctorArg.getKey());
- }
}
+ }
- // Iterate the bean properties and resolve value references
- SmartPtrIAppConfig appConfig = getAppConfig();
- Cmapstrstr properties = beanNode->_properties;
-
- for (TMapIterator<Cmapstrstr> property(properties);
- property;
- property++) {
- *property = appConfig->resolveValue(*property);
- }
+ // Iterate the bean properties and resolve value references
+ SmartPtrIAppConfig appConfig = getAppConfig();
+ Cmapstrstr properties = beanNode->_properties;
- // Initialize the bean
- beanNode->_bean->initializeBean(beanInitArgs, properties);
- beanNode->_isInitialized = true;
+ for (TMapIterator<Cmapstrstr> property(properties);
+ property;
+ property++) {
+ *property = appConfig->resolveValue(*property);
}
+
+ // Initialize the bean
+ beanNode->_bean->initializeBean(beanInitArgs, properties);
+ beanNode->_isInitialized = true;
}
- CAF_CM_EXIT;
}
void CApplicationContext::terminateBeans(CBeanGraph::ClistVertexEdges& beanTopologySort) const {
CAF_CM_FUNCNAME("terminateBeans");
- CAF_CM_ENTER {
- // Important! Iterate in reverse order of initialization
- // Some beans may not be initialized because of exceptions during init process
- for (CBeanGraph::ClistVertexEdges::reverse_iterator beanNode = beanTopologySort.rbegin();
- beanNode != beanTopologySort.rend();
- beanNode++) {
- if ((*beanNode)->_isInitialized) {
- CAF_CM_LOG_DEBUG_VA1(
- "Terminating bean %s",
- (*beanNode)->_id.c_str());
- try {
- (*beanNode)->_bean->terminateBean();
- }
- CAF_CM_CATCH_ALL;
- CAF_CM_LOG_CRIT_CAFEXCEPTION;
- CAF_CM_CLEAREXCEPTION;
- } else {
- CAF_CM_LOG_DEBUG_VA1(
- "Skipping termination of uninitialized bean %s",
- (*beanNode)->_id.c_str());
+ // Important! Iterate in reverse order of initialization
+ // Some beans may not be initialized because of exceptions during init process
+ for (CBeanGraph::ClistVertexEdges::reverse_iterator beanNode = beanTopologySort.rbegin();
+ beanNode != beanTopologySort.rend();
+ beanNode++) {
+ if ((*beanNode)->_isInitialized) {
+ CAF_CM_LOG_DEBUG_VA1(
+ "Terminating bean %s",
+ (*beanNode)->_id.c_str());
+ try {
+ (*beanNode)->_bean->terminateBean();
}
+ CAF_CM_CATCH_ALL;
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CAF_CM_CLEAREXCEPTION;
+ } else {
+ CAF_CM_LOG_DEBUG_VA1(
+ "Skipping termination of uninitialized bean %s",
+ (*beanNode)->_id.c_str());
}
}
- CAF_CM_EXIT;
}
void CDaemonUtils::MakeDaemon(
int32 argc,
char** argv,
- const char* processName,
+ const std::string& procPath,
+ const std::string& procName,
void(*pfnShutdownHandler)(int32 signalNum),
bool& isDaemonized,
bool& logInfos) {
- const char* logProcessName =
- (processName && *processName) ? processName : "CDaemonUtils";
- ::openlog(logProcessName, LOG_PID, LOG_USER);
+ const std::string logProcName = procName.empty() ? "CDaemonUtils" : procName;
+ ::openlog(logProcName.c_str(), LOG_PID, LOG_USER);
::atexit(::closelog);
- ::syslog(LOG_INFO, "Initializing %s", logProcessName);
+ ::syslog(LOG_INFO, "Initializing %s", logProcName.c_str());
isDaemonized = true;
logInfos = false;
}
// and re-open syslog
- ::openlog(logProcessName, LOG_CONS | LOG_PID, LOG_USER);
+ ::openlog(logProcName.c_str(), LOG_CONS | LOG_PID, LOG_USER);
errno = 0;
}
// to make sure we don't hold a file system open.
if (rootDir.empty()) {
if (logInfos) {
- ::syslog(LOG_INFO, "Switching to directory of %s", *argv);
+ ::syslog(LOG_INFO, "Switching to directory of %s", procPath.c_str());
}
- const char * lastSlash = ::strrchr(*argv, '/');
+ const char * lastSlash = ::strrchr(procPath.c_str(), '/');
if (*lastSlash) {
- std::string directory = *argv;
+ std::string directory = procPath;
directory.erase(directory.rfind('/'));
if (logInfos) {
::syslog(LOG_INFO, "chdir %s", directory.c_str());
CAF_CM_LOG_ERROR_VA0(message.c_str());
}
CAF_CM_CATCH_ALL;
+ CAF_CM_CLEAREXCEPTION;
::exit(-1);
}
static void MakeDaemon(
int32 argc,
char** argv,
- const char* processName,
+ const std::string& procPath,
+ const std::string& procName,
void(*pfnShutdownHandler)(int32 signalNum),
bool& isDaemonized,
bool& logInfos);
////////////////////////////////////////////////////////////////////////
CLoggingSetter::CLoggingSetter() :
_isInitialized(false),
- _useSingleLogging(false),
+ _remapLoggingLocation(false),
CAF_CM_INIT_LOG("CLoggingSetter") {
}
try {
if (_isInitialized) {
- if (! _useSingleLogging) {
+ if (_remapLoggingLocation) {
CAF_CM_LOG_DEBUG_VA0("Resetting log config dir");
CLoggingUtils::resetConfigFile();
CAF_CM_LOG_DEBUG_VA0("Reset log config dir");
CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_STRING(logDir);
- _useSingleLogging = AppConfigUtils::getOptionalBoolean("use_single_logging");
- if (! _useSingleLogging) {
+ _remapLoggingLocation = AppConfigUtils::getOptionalBoolean("remap_logging_location");
+ if (_remapLoggingLocation) {
CAF_CM_LOG_DEBUG_VA1("Setting log config dir - %s", logDir.c_str());
CLoggingUtils::setLogDir(logDir);
CAF_CM_LOG_DEBUG_VA1("Set log config dir - %s", logDir.c_str());
private:
bool _isInitialized;
- bool _useSingleLogging;
+ bool _remapLoggingLocation;
private:
CAF_CM_CREATE;
return rc;
}
-void CLoggingUtils::setStartupConfigFile() {
- setStartupConfigFile("log4cpp_config");
-}
-
-void CLoggingUtils::setStartupConfigFile(const std::string& configFile) {
+void CLoggingUtils::setStartupConfigFile(
+ const std::string& configFile,
+ const std::string& logDir) {
CAF_CM_STATIC_FUNC("CLoggingUtils", "setStartupConfigFile");
+ CAF_CM_VALIDATE_STRING(configFile);
#ifndef WIN32
char configFileFullBuf[ 32768 ];
_sInstance->_configFile = configFileFull;
_sInstance->loadProperties();
- _sInstance->loadConfig(configFileFull);
+ if (logDir.empty()) {
+ _sInstance->loadConfig(configFileFull);
+ } else {
+ setLogDir(logDir);
+ }
}
SmartPtrCLoggingUtils CLoggingUtils::getInstance() {
public:
static bool isConsoleAppenderUsed();
- static void setStartupConfigFile();
- static void setStartupConfigFile(const std::string& configFile);
+ static void setStartupConfigFile(
+ const std::string& configFile = "log4cpp_config",
+ const std::string& logDir = std::string());
static std::string getConfigFile();
static void resetConfigFile();
static void setLogDir(const std::string& logDir);
persistenceProtocol->initialize(
loadTextFile(protocolIdDir, "protocolName.txt"),
loadTextFile(protocolIdDir, "uri.txt"),
+ loadTextFile(protocolIdDir, "uri_amqp.txt"),
+ loadTextFile(protocolIdDir, "uri_tunnel.txt"),
loadTextFile(protocolIdDir, "tlsCert.pem"),
loadTextFile(protocolIdDir, "tlsProtocol.txt"),
tlsCipherCollection,
std::deque<SmartPtrCPersistenceProtocolDoc> persistenceProtocolCollectionInner =
persistenceProtocolCollection->getPersistenceProtocol();
- CAF_CM_VALIDATE_BOOL(! persistenceProtocolCollectionInner.empty());
- CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInner.size() == 1);
+ CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInner.size() <= 1);
- return persistenceProtocolCollectionInner.front();
+ SmartPtrCPersistenceProtocolDoc rc;
+ if (persistenceProtocolCollectionInner.size() == 1) {
+ rc = persistenceProtocolCollectionInner.front();
+ }
+
+ return rc;
}
void CPersistenceUtils::savePersistence(
amqpQueueDir, "uri.txt", persistenceProtocol->getUri());
}
+ if (! persistenceProtocol->getUriAmqp().empty()) {
+ FileSystemUtils::saveTextFile(
+ amqpQueueDir, "uri_amqp.txt", persistenceProtocol->getUriAmqp());
+ }
+
+ if (! persistenceProtocol->getUriTunnel().empty()) {
+ FileSystemUtils::saveTextFile(
+ amqpQueueDir, "uri_tunnel.txt", persistenceProtocol->getUriTunnel());
+ }
+
if (! persistenceProtocol->getTlsCert().empty()) {
FileSystemUtils::saveTextFile(
amqpQueueDir, "tlsCert.pem", persistenceProtocol->getTlsCert());
std::string CPersistenceUtils::loadTextFile(
const std::string& dir,
const std::string& file,
- const std::string& defaultVal) {
+ const std::string& defaultVal,
+ const bool isTrimRight) {
CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "loadTextFile");
CAF_CM_VALIDATE_STRING(dir);
CAF_CM_VALIDATE_STRING(file);
std::string rc;
if (FileSystemUtils::doesFileExist(path)) {
rc = FileSystemUtils::loadTextFile(path);
+ if (isTrimRight) {
+ rc = CStringUtils::trimRight(rc);
+ }
} else {
rc = defaultVal;
}
static std::string loadTextFile(
const std::string& dir,
const std::string& file,
- const std::string& defaultVal = std::string());
+ const std::string& defaultVal = std::string(),
+ const bool isTrimRight = true);
private:
static std::string createDirectory(
CThreadSignal::CThreadSignal(void) :
_isInitialized(false),
- _waitCnt(0),
CAF_CM_INIT("CThreadSignal") {
CAF_CM_INIT_THREADSAFE
;
CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
- for (uint32 iter = 0; iter < _waitCnt; iter++) {
- _condition.signal();
- }
-
- _waitCnt = 0;
+ _condition.signal();
}
void CThreadSignal::wait(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs) {
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_SMARTPTR(mutex);
- {
- CAF_CM_LOCK_UNLOCK;
- _waitCnt++;
- }
-
bool rc = false;
if (0 == timeoutMs) {
_condition.wait(mutex);
gint64 endTime;
endTime = ::g_get_monotonic_time() + timeoutMs * G_TIME_SPAN_MILLISECOND;
rc = _condition.waitUntil(mutex, endTime);
- if (!rc) {
- CAF_CM_LOCK_UNLOCK;
- _waitCnt--;
- }
}
return rc;
if (_isInitialized) {
_condition.close();
- _waitCnt = 0;
_isInitialized = false;
}
}
bool _isInitialized;
CAutoCondition _condition;
- uint32 _waitCnt;
-
private:
CAF_CM_CREATE;
CAF_CM_CREATE_THREADSAFE;
return stackSizeKb;
}
-void CThreadUtils::start(
- threadFunc func,
- void* data) {
- (void)startJoinable(func, data);
-}
-
-GThread* CThreadUtils::startJoinable(
- threadFunc func,
- void* data) {
-
+GThread* CThreadUtils::startJoinable(threadFunc func, void* data) {
CAF_CM_STATIC_FUNC("CThreadUtils", "startJoinable");
GThread *rc = g_thread_new("CThreadUtils::startJoinable", func, data);
return rc;
}
+void CThreadUtils::join(GThread* thread) {
+ (void) g_thread_join(thread);
+}
+
void CThreadUtils::sleep(
const uint32 milliseconds) {
public:
static uint32 getThreadStackSizeKb();
- static void start(threadFunc func, void* data);
static GThread* startJoinable(threadFunc func, void* data);
+ static void join(GThread* thread);
static void sleep(const uint32 milliseconds);
private:
uint32& value,
const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0;
+ virtual bool getInt32(
+ const std::string& sectionName,
+ const std::string& parameterName,
+ int32& value,
+ const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0;
+
virtual bool getBoolean(
const std::string& sectionName,
const std::string& parameterName,
uint32& value,
const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0;
+ virtual bool getGlobalInt32(
+ const std::string& parameterName,
+ int32& value,
+ const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0;
+
virtual bool getGlobalBoolean(
const std::string& parameterName,
bool& value,
const std::string& parameterName,
const uint32& value) = 0;
+ virtual void setInt32(
+ const std::string& sectionName,
+ const std::string& parameterName,
+ const int32& value) = 0;
+
virtual void setBoolean(
const std::string& sectionName,
const std::string& parameterName,
const std::string& parameterName,
const uint32& value) = 0;
+ virtual void setGlobalInt32(
+ const std::string& parameterName,
+ const int32& value) = 0;
+
virtual void setGlobalBoolean(
const std::string& parameterName,
const bool& value) = 0;
hostpath = value;
g_free(value);
}
+ g_match_info_free(matchInfo);
+ matchInfo = NULL;
+
if (g_regex_match(regexHost, hostpath.c_str(), (GRegexMatchFlags)0, &matchInfo)) {
value = g_match_info_fetch_named(matchInfo, "host");
data.host = value;
data.port = CStringConv::fromString<uint32>(value);
g_free(value);
}
+ g_match_info_free(matchInfo);
+ matchInfo = NULL;
+
if (g_regex_match(regexPath, hostpath.c_str(), (GRegexMatchFlags)0, &matchInfo)) {
value = g_match_info_fetch_named(matchInfo, "path");
data.path = value;
g_free(value);
}
+ g_match_info_free(matchInfo);
+ matchInfo = NULL;
}
if (params.length()) {
}
}
}
+ g_match_info_free(matchInfo);
+ matchInfo = NULL;
}
}
}
GError *error = NULL;
regexAddress = g_regex_new(addressPattern.c_str(),
- (GRegexCompileFlags)(G_REGEX_RAW),
- (GRegexMatchFlags)0,
- &error);
+ (GRegexCompileFlags)(G_REGEX_RAW),
+ (GRegexMatchFlags)0,
+ &error);
if (error) {
throw error;
}
matchInfo = NULL;
regexDrive = g_regex_new(drivePattern.c_str(),
- (GRegexCompileFlags)(G_REGEX_RAW),
- (GRegexMatchFlags)0,
- &error);
+ (GRegexCompileFlags)(G_REGEX_RAW),
+ (GRegexMatchFlags)0,
+ &error);
if (error) {
throw error;
}
- if (g_regex_match(regexDrive, data.path.c_str(), (GRegexMatchFlags)0, &matchInfo)) {
- g_match_info_free(matchInfo);
- matchInfo = NULL;
- } else {
+ if (! g_regex_match(regexDrive, data.path.c_str(), (GRegexMatchFlags)0, &matchInfo)) {
data.path = "/" + data.path;
}
+ g_match_info_free(matchInfo);
+ matchInfo = NULL;
}
}
CAF_CM_CATCH_CAF
thisXml->addAttribute("uri", uriVal);
}
+ const std::string uriAmqpVal = persistenceProtocolDoc->getUriAmqp();
+ if (! uriAmqpVal.empty()) {
+ thisXml->addAttribute("uriAmqp", uriAmqpVal);
+ }
+
+ const std::string uriTunnelVal = persistenceProtocolDoc->getUriTunnel();
+ if (! uriTunnelVal.empty()) {
+ thisXml->addAttribute("uriTunnel", uriTunnelVal);
+ }
+
const std::string tlsCertVal = persistenceProtocolDoc->getTlsCert();
if (! tlsCertVal.empty()) {
const SmartPtrCXmlElement tlsCertXml = thisXml->createAndAddElement("tlsCert");
const std::string uriVal =
thisXml->findOptionalAttribute("uri");
+ const std::string uriAmqpVal =
+ thisXml->findOptionalAttribute("uriAmqp");
+
+ const std::string uriTunnelVal =
+ thisXml->findOptionalAttribute("uriTunnel");
+
std::string tlsCertVal;
const SmartPtrCXmlElement tlsCertXml = thisXml->findOptionalChild("tlsCert");
if (tlsCertXml) {
persistenceProtocolDoc->initialize(
protocolNameVal,
uriVal,
+ uriAmqpVal,
+ uriTunnelVal,
tlsCertVal,
tlsProtocolVal,
tlsCipherCollectionVal,
return FALSE;
// Dynamically load the Entry-Points for dbghelp.dll:
// First try to load the newsest one from
- TCHAR szTemp[4096];
+ TCHAR localFile[4096];
// But before wqe do this, we first check if the ".local" file exists
- if (GetModuleFileName(NULL, szTemp, 4096) > 0)
+ if (GetModuleFileName(NULL, localFile, 4096) > 0)
{
- _tcscat_s(szTemp, _T(".local"));
- if (GetFileAttributes(szTemp) == INVALID_FILE_ATTRIBUTES)
+ _tcscat_s(localFile, _T(".local"));
+ if (GetFileAttributes(localFile) == INVALID_FILE_ATTRIBUTES)
{
// ".local" file does not exist, so we can try to load the dbghelp.dll from the "Debugging Tools for Windows"
// Ok, first try the new path according to the archtitecture:
+ TCHAR dbghelpFile[4096];
#ifdef _M_IX86
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
+ if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), dbghelpFile, 4096) > 0) )
{
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x86)\\dbghelp.dll"));
+ _tcscat_s(dbghelpFile, _T("\\Debugging Tools for Windows (x86)\\dbghelp.dll"));
// now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ if (GetFileAttributes(dbghelpFile) != INVALID_FILE_ATTRIBUTES)
{
- m_hDbhHelp = LoadLibrary(szTemp);
+ m_hDbhHelp = LoadLibrary(dbghelpFile);
}
}
#elif _M_X64
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
+ if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), dbghelpFile, 4096) > 0) )
{
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x64)\\dbghelp.dll"));
+ _tcscat_s(dbghelpFile, _T("\\Debugging Tools for Windows (x64)\\dbghelp.dll"));
// now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ if (GetFileAttributes(dbghelpFile) != INVALID_FILE_ATTRIBUTES)
{
- m_hDbhHelp = LoadLibrary(szTemp);
+ m_hDbhHelp = LoadLibrary(dbghelpFile);
}
}
#elif _M_IA64
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
+ if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), dbghelpFile, 4096) > 0) )
{
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (ia64)\\dbghelp.dll"));
+ _tcscat_s(dbghelpFile, _T("\\Debugging Tools for Windows (ia64)\\dbghelp.dll"));
// now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ if (GetFileAttributes(dbghelpFile) != INVALID_FILE_ATTRIBUTES)
{
- m_hDbhHelp = LoadLibrary(szTemp);
+ m_hDbhHelp = LoadLibrary(dbghelpFile);
}
}
#endif
// If still not found, try the old directories...
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
+ if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), dbghelpFile, 4096) > 0) )
{
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows\\dbghelp.dll"));
+ _tcscat_s(dbghelpFile, _T("\\Debugging Tools for Windows\\dbghelp.dll"));
// now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ if (GetFileAttributes(dbghelpFile) != INVALID_FILE_ATTRIBUTES)
{
- m_hDbhHelp = LoadLibrary(szTemp);
+ m_hDbhHelp = LoadLibrary(dbghelpFile);
}
}
#if defined _M_X64 || defined _M_IA64
// Still not found? Then try to load the (old) 64-Bit version:
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
+ if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), dbghelpFile, 4096) > 0) )
{
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows 64-Bit\\dbghelp.dll"));
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ _tcscat_s(dbghelpFile, _T("\\Debugging Tools for Windows 64-Bit\\dbghelp.dll"));
+ if (GetFileAttributes(dbghelpFile) != INVALID_FILE_ATTRIBUTES)
{
- m_hDbhHelp = LoadLibrary(szTemp);
+ m_hDbhHelp = LoadLibrary(dbghelpFile);
}
}
#endif
pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" );
if ( (pEPM == NULL) || (pGMFNE == NULL) || (pGMBN == NULL) || (pGMI == NULL) )
{
- // we couldn´t find all functions
+ // we couldn�t find all functions
FreeLibrary(hPsapi);
return FALSE;
}
const std::string destAttachmentFilename =
BasePlatform::UuidToString(requestId) + "-EnvelopePayload.xml";
const std::string destAttachmentPath = FileSystemUtils::buildPath(
- outputDir, destAttachmentFilename);
+ outputDir, "att", destAttachmentFilename);
const std::string destAttachmentUri =
"file:///" + destAttachmentPath + "?relPath=" + destAttachmentFilename;
}
SmartPtrIIntMessage CAbstractPollableChannel::receive() {
- return receive(-1);
+ return receive(0);
}
SmartPtrIIntMessage CAbstractPollableChannel::receive(const int32 timeout) {
CIntegrationAppContext::CIntegrationAppContext() :
_isInitialized(false),
_isIntegrationObjectCollectionReady(false),
+ _lifecycleBeansStarted(false),
+ _timeoutMs(0),
CAF_CM_INIT_LOG("CIntegrationAppContext") {
}
}
}
-void CIntegrationAppContext::initialize(const uint32 timeoutMs) {
+void CIntegrationAppContext::initialize(
+ const uint32 timeoutMs) {
CAF_CM_FUNCNAME_VALIDATE("initialize");
CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
const std::string beanConfigPath = getDefaultBeanConfigPath();
- initialize(timeoutMs, beanConfigPath);
+ initializeRaw(timeoutMs, beanConfigPath, true);
}
void CIntegrationAppContext::initialize(
const uint32 timeoutMs,
const std::string& beanConfigPath) {
- CAF_CM_FUNCNAME("initialize");
+ CAF_CM_FUNCNAME_VALIDATE("initialize");
CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_STRING(beanConfigPath);
+ initializeRaw(timeoutMs, beanConfigPath, true);
+}
+
+void CIntegrationAppContext::initializeTwoPhase(
+ const uint32 timeoutMs,
+ const std::string& beanConfigPath) {
+ CAF_CM_FUNCNAME_VALIDATE("initializeTwoPhase");
+ CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
+ CAF_CM_VALIDATE_STRING(beanConfigPath);
+
+ initializeRaw(timeoutMs, beanConfigPath, false);
+}
+
+void CIntegrationAppContext::initializeRaw(
+ const uint32 timeoutMs,
+ const std::string& beanConfigPath,
+ const bool startLifecycleBeans) {
+ CAF_CM_FUNCNAME("initializeRaw");
+ CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
+ CAF_CM_VALIDATE_STRING(beanConfigPath);
+
+ _timeoutMs = timeoutMs;
+
_weakSelfReference.CreateInstance();
_weakSelfReference->set(this);
}
// Start the lifecycle objects
- startStop(_lifecycleBeans, timeoutMs, true);
+ if (startLifecycleBeans) {
+ _lifecycleBeansStarted = true;
+ startStop(_lifecycleBeans, _timeoutMs, true);
+ }
_isInitialized = true;
}
+void CIntegrationAppContext::startLifecycleBeans() {
+ CAF_CM_FUNCNAME_VALIDATE("startLifecycleBeans");
+ CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
+ CAF_CM_PRECOND_ISNOTINITIALIZED(_lifecycleBeansStarted);
+
+ _lifecycleBeansStarted = true;
+ startStop(_lifecycleBeans, _timeoutMs, true);
+}
+
void CIntegrationAppContext::terminate(const uint32 timeoutMs) {
CAF_CM_FUNCNAME("terminate");
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
+ CAF_CM_PRECOND_ISINITIALIZED(_lifecycleBeansStarted);
try {
_weakSelfReference->set(NULL);
public:
void initialize(const uint32 timeoutMs);
void initialize(const uint32 timeoutMs, const std::string& beanConfigPath);
+ void initializeTwoPhase(const uint32 timeoutMs, const std::string& beanConfigPath);
void terminate(const uint32 timeoutMs);
public: // IIntegrationAppContext
+ void startLifecycleBeans();
SmartPtrIIntegrationObject getIntegrationObject(const std::string& id) const;
void getIntegrationObject(const IID& iid, void **ppv) const;
SmartPtrCObjectCollection getIntegrationObjects(const IID& iid) const;
typedef std::multimap<int32, SmartPtrILifecycle> LifecycleBeans;
private:
+ void initializeRaw(
+ const uint32 timeoutMs,
+ const std::string& beanConfigPath,
+ const bool startLifecycleBeans);
+
SmartPtrCIntegrationObjectCollection assign(
const IAppContext::SmartPtrCBeans& contextBeans,
const Cdeqstr& beanConfigPathCollection) const;
private:
bool _isInitialized;
bool _isIntegrationObjectCollectionReady;
+ bool _lifecycleBeansStarted;
+ uint32 _timeoutMs;
SmartPtrCApplicationContext _applicationContext;
SmartPtrCChannelResolver _channelResolver;
SmartPtrCIntegrationObjectCollection _integrationObjectCollection;
CSimpleAsyncTaskExecutor::CSimpleAsyncTaskExecutor() :
_isInitialized(false),
+ _thread(NULL),
CAF_CM_INIT_LOG("CSimpleAsyncTaskExecutor") {
CAF_CM_FUNCNAME("CSimpleAsyncTaskExecutor");
try {
+ CAF_CM_INIT_THREADSAFE;
CAF_THREADSIGNAL_INIT;
}
CAF_CM_CATCH_ALL;
}
CSimpleAsyncTaskExecutor::~CSimpleAsyncTaskExecutor() {
+ CAF_CM_FUNCNAME("~CSimpleAsyncTaskExecutor");
+
+ try {
+ cancel(0);
+ }
+ CAF_CM_CATCH_ALL;
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CAF_CM_CLEAREXCEPTION;
+
+ try {
+ if (_thread) {
+ CThreadUtils::join(_thread);
+ }
+ }
+ CAF_CM_CATCH_ALL;
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CAF_CM_CLEAREXCEPTION;
}
void CSimpleAsyncTaskExecutor::initialize(
const SmartPtrIRunnable& runnable,
const SmartPtrIErrorHandler& errorHandler) {
CAF_CM_FUNCNAME_VALIDATE("initialize");
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_INTERFACE(runnable);
CAF_CM_VALIDATE_INTERFACE(errorHandler);
void CSimpleAsyncTaskExecutor::execute(
const uint32 timeoutMs) {
CAF_CM_FUNCNAME("execute");
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
if (ITaskExecutor::ETaskStateNotStarted == _state->getState()) {
CThreadData threadData = std::make_pair(
CAF_THREADSIGNAL_MUTEX,
_state.GetNonAddRefedInterface());
- CThreadUtils::start(threadFunc, &threadData);
+ CAF_CM_VALIDATE_NULLPTR(_thread);
+ _thread = CThreadUtils::startJoinable(threadFunc, &threadData);
+
+ CAF_CM_UNLOCK_LOCK;
_state->waitForStart(CAF_THREADSIGNAL_MUTEX, timeoutMs);
}
if (_state->getState() != ITaskExecutor::ETaskStateStarted) {
- CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE, "Not Started: %s", _state->getStateStr().c_str());
+ CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE,
+ "Not Started: %s", _state->getStateStr().c_str());
}
} else if (ITaskExecutor::ETaskStateStarted != _state->getState()) {
- CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE, "Invalid State: %s", _state->getStateStr().c_str());
+ CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE,
+ "Invalid State: %s", _state->getStateStr().c_str());
}
CAF_CM_LOG_INFO_VA0("Started");
void CSimpleAsyncTaskExecutor::cancel(
const uint32 timeoutMs) {
CAF_CM_FUNCNAME("cancel");
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
if (ITaskExecutor::ETaskStateStarted == _state->getState()) {
// mutex is guaranteed to unlock
{
CAF_THREADSIGNAL_LOCK_UNLOCK;
- _state->waitForStop(CAF_THREADSIGNAL_MUTEX, timeoutMs);
+ CAF_CM_UNLOCK_LOCK;
+ while (! _state->getHasThreadExited()) {
+ _state->waitForStop(CAF_THREADSIGNAL_MUTEX, timeoutMs);
+ }
+ }
+
+ if (_thread) {
+ CThreadUtils::join(_thread);
+ _thread = NULL;
}
if (_state->getState() != ITaskExecutor::ETaskStateFinished) {
ITaskExecutor::ETaskState CSimpleAsyncTaskExecutor::getState() const {
CAF_CM_FUNCNAME_VALIDATE("getState");
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
return _state->getState();
SmartPtrCSimpleAsyncTaskExecutorState state;
SmartPtrCAutoMutex mutex;
+ ITaskExecutor::ETaskState stateState = ITaskExecutor::ETaskStateFailed;
try {
CAF_CM_VALIDATE_PTR(data);
CAF_CM_VALIDATE_SMARTPTR(state);
try {
- CAF_CM_LOCK_UNLOCK1(mutex);
state->setState(ITaskExecutor::ETaskStateStarted);
+
+ CAF_CM_LOCK_UNLOCK1(mutex);
state->signalStart();
}
CAF_CM_CATCH_ALL;
if (!CAF_CM_ISEXCEPTION) {
try {
state->getRunnable()->run();
+ stateState = ITaskExecutor::ETaskStateFinished;
}
CAF_CM_CATCH_ALL;
CAF_CM_LOG_CRIT_CAFEXCEPTION;
try {
if (CAF_CM_ISEXCEPTION) {
- state->setState(ITaskExecutor::ETaskStateFailed);
-
SmartPtrCIntException intException;
intException.CreateInstance();
intException->initialize(CAF_CM_GETEXCEPTION);
state->getErrorHandler()->handleError(intException, SmartPtrIIntMessage());
CAF_CM_CLEAREXCEPTION;
- } else {
- state->setState(ITaskExecutor::ETaskStateFinished);
}
}
CAF_CM_CATCH_ALL;
CAF_CM_LOG_CRIT_CAFEXCEPTION;
CAF_CM_CLEAREXCEPTION;
- CAF_CM_LOG_INFO_VA0("**** Thread exiting ****");
if (! state.IsNull()) {
try {
- CAF_CM_VALIDATE_PTR(mutex);
+ state->setState(stateState);
+ state->setThreadExited();
+
CAF_CM_LOCK_UNLOCK1(mutex);
- state->detach();
state->signalStop();
}
CAF_CM_CATCH_ALL;
CAF_CM_CLEAREXCEPTION;
}
+ CAF_CM_LOG_INFO_VA0("**** Thread exiting ****");
+
return NULL;
}
private:
bool _isInitialized;
+ GThread* _thread;
SmartPtrCSimpleAsyncTaskExecutorState _state;
typedef std::pair<SmartPtrCAutoMutex, CSimpleAsyncTaskExecutorState*> CThreadData;
CAF_CM_CREATE;
CAF_CM_CREATE_LOG;
CAF_THREADSIGNAL_CREATE;
+ CAF_CM_CREATE_THREADSAFE;
CAF_CM_DECLARE_NOCOPY(CSimpleAsyncTaskExecutor);
};
CSimpleAsyncTaskExecutorState::CSimpleAsyncTaskExecutorState() :
_isInitialized(false),
+ _hasThreadExited(false),
_runnableState(ITaskExecutor::ETaskStateNotStarted),
CAF_CM_INIT_LOG("CSimpleAsyncTaskExecutorState") {
CAF_CM_INIT_THREADSAFE;
_runnableState = runnableState;
}
+bool CSimpleAsyncTaskExecutorState::getHasThreadExited() {
+ CAF_CM_FUNCNAME_VALIDATE("getHasThreadExited");
+ CAF_CM_LOCK_UNLOCK;
+ CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
+
+ return _hasThreadExited;
+}
+
+void CSimpleAsyncTaskExecutorState::setThreadExited() {
+ CAF_CM_FUNCNAME_VALIDATE("setThreadExited");
+ CAF_CM_LOCK_UNLOCK;
+ CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
+
+ _hasThreadExited = true;
+}
+
SmartPtrIRunnable CSimpleAsyncTaskExecutorState::getRunnable() const {
CAF_CM_FUNCNAME_VALIDATE("getRunnable");
CAF_CM_LOCK_UNLOCK;
CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
- CAF_CM_LOG_DEBUG_VA1("Signal (%s)", _threadSignalStart.getName().c_str());
+ CAF_CM_LOG_DEBUG_VA2("Signal (%s) - %p", _threadSignalStart.getName().c_str(), this);
_threadSignalStart.signal();
}
_threadSignalStop.signal();
}
-void CSimpleAsyncTaskExecutorState::detach() {
- CAF_CM_FUNCNAME_VALIDATE("detach");
- CAF_CM_LOCK_UNLOCK;
- CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
-
- _runnable = NULL;
- _errorHandler = NULL;
-}
-
void CSimpleAsyncTaskExecutorState::waitForStop(
SmartPtrCAutoMutex& mutex,
const uint32 timeoutMs) {
SmartPtrIRunnable getRunnable() const;
SmartPtrIErrorHandler getErrorHandler() const;
+
ITaskExecutor::ETaskState getState() const;
std::string getStateStr() const;
-
void setState(const ITaskExecutor::ETaskState runnableState);
+ bool getHasThreadExited();
+ void setThreadExited();
+
void signalStart();
void waitForStart(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs);
void signalStop();
void waitForStop(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs);
- void detach();
-
private:
bool _isInitialized;
+ bool _hasThreadExited;
ITaskExecutor::ETaskState _runnableState;
SmartPtrIRunnable _runnable;
SmartPtrIErrorHandler _errorHandler;
_timeout(0),
CAF_CM_INIT_LOG("CSourcePollingChannelAdapter") {
CAF_CM_INIT_THREADSAFE;
+ CAF_THREADSIGNAL_INIT;
}
CSourcePollingChannelAdapter::~CSourcePollingChannelAdapter() {
_timeout = timeout;
_isTimeoutSet = true;
+ _threadSignalCancel.initialize("Cancel");
+
_isInitialized = true;
}
void CSourcePollingChannelAdapter::run() {
CAF_CM_FUNCNAME("run");
-
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
uint32 messageCount = 0;
if (message.IsNull()
|| (messageCount >= _pollerMetadata->getMaxMessagesPerPoll())) {
- CThreadUtils::sleep(_pollerMetadata->getFixedRate());
+ {
+ CAF_THREADSIGNAL_LOCK_UNLOCK;
+// CAF_CM_LOG_DEBUG_VA2("Wait (%s) - waitMs: %d",
+// _threadSignalCancel.getName().c_str(),
+// _pollerMetadata->getFixedRate());
+ _threadSignalCancel.waitOrTimeout(
+ CAF_THREADSIGNAL_MUTEX, _pollerMetadata->getFixedRate());
+ }
+
messageCount = 0;
}
}
void CSourcePollingChannelAdapter::cancel() {
CAF_CM_FUNCNAME_VALIDATE("cancel");
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
- CAF_CM_LOG_DEBUG_VA0("Canceling");
- setIsCancelled(true);
+ CAF_CM_LOG_DEBUG_VA1("Signal (%s)", _threadSignalCancel.getName().c_str());
+ _isCancelled = true;
+ _threadSignalCancel.signal();
}
bool CSourcePollingChannelAdapter::getIsCancelled() const {
CAF_CM_FUNCNAME_VALIDATE("getIsCancelled");
+ CAF_CM_LOCK_UNLOCK;
+ CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
- bool isCancelled = false;
-
- CAF_CM_ENTER_AND_LOCK {
- CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
-
- isCancelled = _isCancelled;
- }
- CAF_CM_UNLOCK_AND_EXIT;
-
- return isCancelled;
-}
-
-void CSourcePollingChannelAdapter::setIsCancelled(
- const bool isCancelled) {
- CAF_CM_FUNCNAME_VALIDATE("setIsCancelled");
-
- CAF_CM_ENTER_AND_LOCK {
- CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
-
- _isCancelled = isCancelled;
- }
- CAF_CM_UNLOCK_AND_EXIT;
+ return _isCancelled;
}
private:
bool getIsCancelled() const;
- void setIsCancelled(const bool isCancelled);
private:
bool _isInitialized;
SmartPtrIPollableChannel _inputPollableChannel;
SmartPtrIErrorHandler _errorHandler;
SmartPtrCPollerMetadata _pollerMetadata;
+ CThreadSignal _threadSignalCancel;
private:
CAF_CM_CREATE;
CAF_CM_CREATE_LOG;
CAF_CM_CREATE_THREADSAFE;
+ CAF_THREADSIGNAL_CREATE;
CAF_CM_DECLARE_NOCOPY(CSourcePollingChannelAdapter);
};
errorResponse, relFilename, message->getHeaders());
// Writing the error response for debugging purposes
- const std::string outputDir = AppConfigUtils::getRequiredString(_sConfigOutputDir);
- FileSystemUtils::saveTextFile(outputDir, _sErrorResponseFilename,
+ const std::string tmpDir = AppConfigUtils::getRequiredString(_sConfigTmpDir);
+ FileSystemUtils::saveTextFile(tmpDir, _sErrorResponseFilename,
newMessage->getPayloadStr());
}
CAF_CM_CATCH_ALL;
using namespace Caf;
-int main(int csz, char* asz[])
-{
- CConfigProvider provider;
- return CProviderDriver::processProviderCommandline(provider, csz, asz);
+int main(int csz, char* asz[]) {
+ CAF_CM_STATIC_FUNC_LOG("ConfigProvider", "main");
+
+ int rc = 0;
+ try {
+ CConfigProvider provider;
+ rc = CProviderDriver::processProviderCommandline(provider, csz, asz);
+ }
+ CAF_CM_CATCH_CAF
+ CAF_CM_CATCH_DEFAULT
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+
+ rc = CAF_CM_ISEXCEPTION ? 1 : rc;
+ CAF_CM_CLEAREXCEPTION;
+
+ return rc;
}
const char* _sInstallProviderSpecFilename = "installProviderSpec.xml";
}
-int main(int csz, char* asz[])
-{
- CInstallProvider provider;
- return CProviderDriver::processProviderCommandline(provider, csz, asz);
+int main(int csz, char* asz[]) {
+ CAF_CM_STATIC_FUNC_LOG("InstallProvider", "main");
+
+ int rc = 0;
+ try {
+ CInstallProvider provider;
+ rc = CProviderDriver::processProviderCommandline(provider, csz, asz);
+ }
+ CAF_CM_CATCH_CAF
+ CAF_CM_CATCH_DEFAULT
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+
+ rc = CAF_CM_ISEXCEPTION ? 1 : rc;
+ CAF_CM_CLEAREXCEPTION;
+
+ return rc;
}
using namespace Caf;
-int main(int csz, char* asz[])
-{
- CRemoteCommandProvider provider;
- return CProviderDriver::processProviderCommandline(provider, csz, asz);
+int main(int csz, char* asz[]) {
+ CAF_CM_STATIC_FUNC_LOG("RemoteCommandProvider", "main");
+
+ int rc = 0;
+ try {
+ CRemoteCommandProvider provider;
+ rc = CProviderDriver::processProviderCommandline(provider, csz, asz);
+ }
+ CAF_CM_CATCH_CAF
+ CAF_CM_CATCH_DEFAULT
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+
+ rc = CAF_CM_ISEXCEPTION ? 1 : rc;
+ CAF_CM_CLEAREXCEPTION;
+
+ return rc;
}
using namespace Caf;
-int main(int csz, char* asz[])
-{
- CTestInfraProvider provider;
- return CProviderDriver::processProviderCommandline(provider, csz, asz);
+int main(int csz, char* asz[]) {
+ CAF_CM_STATIC_FUNC_LOG("TestInfraProvider", "main");
+
+ int rc = 0;
+ try {
+ CTestInfraProvider provider;
+ rc = CProviderDriver::processProviderCommandline(provider, csz, asz);
+ }
+ CAF_CM_CATCH_CAF
+ CAF_CM_CATCH_DEFAULT
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+
+ rc = CAF_CM_ISEXCEPTION ? 1 : rc;
+ CAF_CM_CLEAREXCEPTION;
+
+ return rc;
}
_isWorking = true;
CLoggingUtils::setStartupConfigFile(
- AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile));
- CLoggingUtils::setLogDir(
+ AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile),
AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir));
const uint32 hostDelaySec = AppConfigUtils::getRequiredUint32(
}
CAF_CM_CATCH_ALL;
CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CAF_CM_CLEAREXCEPTION;
try {
if (! integrationAppContext.IsNull()) {
return 1;
}
- CafInitialize::serviceConfig();
SmartPtrIAppConfig appConfig;
-
try {
+ CafInitialize::serviceConfig();
+
std::string appConfigEnv;
CEnvironmentUtils::readEnvironmentVar("CAF_APPCONFIG", appConfigEnv);
if (appConfigEnv.empty()) {
"ManagementAgentHost: getAppConfig() failed . unknown exception\n");
}
- if (!appConfig) {
- CafInitialize::term();
- return 1;
- }
-
- const std::string cafBinDir = AppConfigUtils::getRequiredString("globals", "bin_dir");
- g_setenv("CAF_BIN_DIR", cafBinDir.c_str(), TRUE);
-
- const std::string cafLibDir = AppConfigUtils::getRequiredString("globals", "lib_dir");
- g_setenv("CAF_LIB_DIR", cafLibDir.c_str(), TRUE);
-
CAF_CM_STATIC_FUNC_LOG("ManagementAgentHostMain", "main");
int32 iRc = 0;
try {
+ if (!appConfig) {
+ CafInitialize::term();
+ return 1;
+ }
+
+ const std::string cafBinDir = AppConfigUtils::getRequiredString("globals", "bin_dir");
+ g_setenv("CAF_BIN_DIR", cafBinDir.c_str(), TRUE);
+
+ const std::string cafLibDir = AppConfigUtils::getRequiredString("globals", "lib_dir");
+ g_setenv("CAF_LIB_DIR", cafLibDir.c_str(), TRUE);
+
_gManagementAgentHostWork.CreateInstance();
_gManagementAgentHostWork->initialize();
return 1;
}
+ const std::string procPath = argv[0];
CDaemonUtils::MakeDaemon(
argc,
argv,
+ procPath,
"ManagementAgentHost",
TermHandler,
_gDaemonized,
_gSysLogInfos);
CLoggingUtils::setStartupConfigFile(
- AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile));
- CLoggingUtils::setLogDir(
+ AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile),
AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir));
_gManagementAgentHostWork->doWork();
const std::string outputDir = AppConfigUtils::getRequiredString(_sConfigOutputDir);
outputDirPath = FileSystemUtils::buildPath(
- outputDir, clientIdStr, requestIdStr, pmeIdStr);
+ outputDir, "att", clientIdStr, requestIdStr, pmeIdStr);
outputDirPath = CStringUtils::expandEnv(outputDirPath);
if (! FileSystemUtils::doesDirectoryExist(outputDirPath)) {
const std::string outputDir = FileSystemUtils::buildPath(
configOutputDir, _sProviderHostArea, relDirectory);
- if (AppConfigUtils::getRequiredBoolean("managementAgent", "remap_logging_location")) {
- SmartPtrCLoggingSetter loggingSetter;
- loggingSetter.CreateInstance();
- loggingSetter->initialize(outputDir);
- }
+ SmartPtrCLoggingSetter loggingSetter;
+ loggingSetter.CreateInstance();
+ loggingSetter->initialize(outputDir);
const std::string providerCollectSchemaMem = message->getPayloadStr();
const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequest =
_persistenceRemove = persistenceRemove;
}
} else {
+ _persistenceRemove = persistenceRemove;
+
_persistenceDir = AppConfigUtils::getRequiredString("persistence_dir");
_configDir = AppConfigUtils::getRequiredString("config_dir");
_persistence = CPersistenceUtils::loadPersistence(_persistenceDir);
_persistenceUpdated = _persistence;
- _persistenceRemove = persistenceRemove;
+ savePersistenceAppconfig(_persistence, _configDir);
_isInitialized = true;
}
const SmartPtrCPersistenceDoc persistenceTmp =
CConfigEnvMerge::mergePersistence(_persistence, _cacertPath, _vcidPath);
- if (! persistenceTmp.IsNull() || ! FileSystemUtils::doesFileExist(_persistenceAppconfigPath)) {
- if (! persistenceTmp.IsNull()) {
- _persistence = persistenceTmp;
- }
+ if (! persistenceTmp.IsNull()) {
+ _persistence = persistenceTmp;
+ _persistenceUpdated = _persistence;
savePersistenceAppconfig(_persistence, _configDir);
- restartListener("Updated persistence-appconfig");
+ CPersistenceUtils::savePersistence(_persistence, _persistenceDir);
+ restartListener("Info changed on disk");
}
SmartPtrCPersistenceDoc rc;
const SmartPtrCPersistenceDoc persistenceTmp =
CPersistenceMerge::mergePersistence(_persistence, persistence);
if (! persistenceTmp.IsNull()) {
- CAF_CM_LOG_DEBUG_VA1("Updating persistence info - %s", _persistenceDir.c_str());
-
_persistence = persistenceTmp;
- _persistenceUpdated = createPersistenceUpdated(_persistence);
+ _persistenceUpdated = _persistence;
+
+ savePersistenceAppconfig(_persistence, _configDir);
CPersistenceUtils::savePersistence(_persistence, _persistenceDir);
- const std::string reason = "Updated persistence info";
+ const std::string reason = "Info changed at source";
listenerConfigured(reason);
restartListener(reason);
-
removePrivateKey(_persistence, _persistenceRemove);
} else {
CAF_CM_LOG_DEBUG_VA0("Persistence info did not change");
CAF_CM_VALIDATE_SMARTPTR(persistence);
CAF_CM_VALIDATE_STRING(configDir);
- #ifdef WIN32
+ const SmartPtrCPersistenceProtocolDoc persistenceProtocol =
+ CPersistenceUtils::loadPersistenceProtocol(
+ persistence->getPersistenceProtocolCollection());
+ if (persistenceProtocol.IsNull() || persistenceProtocol->getUri().empty()) {
+ CAF_CM_LOG_DEBUG_VA1(
+ "Can't create persistence-appconfig until protocol is established - %s",
+ configDir.c_str());
+ } else {
+#ifdef WIN32
const std::string newLine = "\r\n";
#else
const std::string newLine = "\n";
#endif
- CAF_CM_LOG_DEBUG_VA1("Saving persistence-appconfig - %s", configDir.c_str());
- const SmartPtrCPersistenceProtocolDoc persistenceProtocol =
- CPersistenceUtils::loadPersistenceProtocol(
- persistence->getPersistenceProtocolCollection());
+ CAF_CM_LOG_DEBUG_VA1("Saving persistence-appconfig - %s", configDir.c_str());
- UriUtils::SUriRecord uriRecord;
- UriUtils::parseUriString(persistenceProtocol->getUri(), uriRecord);
- CAF_CM_VALIDATE_STRING(uriRecord.path);
+ UriUtils::SUriRecord uriRecord;
+ UriUtils::parseUriString(persistenceProtocol->getUri(), uriRecord);
+ CAF_CM_VALIDATE_STRING(uriRecord.path);
- const std::string listenerContext = calcListenerContext(uriRecord.protocol, configDir);
+ const std::string listenerContext = calcListenerContext(uriRecord.protocol, configDir);
- CAF_CM_LOG_DEBUG_VA2("Calculated listener context - uri: %s, protocol: %s",
- persistenceProtocol->getUri().c_str(), uriRecord.protocol.c_str());
+ CAF_CM_LOG_DEBUG_VA2("Calculated listener context - uri: %s, protocol: %s",
+ persistenceProtocol->getUri().c_str(), uriRecord.protocol.c_str());
- std::string appconfigContents;
- appconfigContents = "[globals]" + newLine;
- appconfigContents += "reactive_request_amqp_queue_id=" + uriRecord.path + newLine;
- appconfigContents += "comm_amqp_listener_context=" + listenerContext + newLine;
+ std::string appconfigContents;
+ appconfigContents = "[globals]" + newLine;
+ appconfigContents += "reactive_request_amqp_queue_id=" + uriRecord.path + newLine;
+ appconfigContents += "comm_amqp_listener_context=" + listenerContext + newLine;
- FileSystemUtils::saveTextFile(_persistenceAppconfigPath, appconfigContents);
+ FileSystemUtils::saveTextFile(_persistenceAppconfigPath, appconfigContents);
+ }
}
void CConfigEnv::removePrivateKey(
}
}
-SmartPtrCPersistenceDoc CConfigEnv::createPersistenceUpdated(
- const SmartPtrCPersistenceDoc& persistence) const {
- CAF_CM_FUNCNAME_VALIDATE("createPersistenceUpdated");
- CAF_CM_VALIDATE_SMARTPTR(persistence);
-
- SmartPtrCLocalSecurityDoc localSecurity;
- if (! persistence->getLocalSecurity().IsNull()
- && ! persistence->getLocalSecurity()->getLocalId().empty()) {
- localSecurity.CreateInstance();
- localSecurity->initialize(persistence->getLocalSecurity()->getLocalId());
- }
-
- SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollection;
- if (! persistence->getPersistenceProtocolCollection().IsNull()
- && ! persistence->getPersistenceProtocolCollection()->getPersistenceProtocol().empty()) {
- const SmartPtrCPersistenceProtocolDoc persistenceProtocolTmp =
- CPersistenceUtils::loadPersistenceProtocol(persistence->getPersistenceProtocolCollection());
- if (! persistenceProtocolTmp->getUri().empty()) {
- SmartPtrCPersistenceProtocolDoc persistenceProtocol;
- persistenceProtocol.CreateInstance();
- persistenceProtocol->initialize(
- persistenceProtocolTmp->getProtocolName(),
- persistenceProtocolTmp->getUri());
-
- std::deque<SmartPtrCPersistenceProtocolDoc> persistenceProtocolInner;
- persistenceProtocolInner.push_back(persistenceProtocol);
-
- persistenceProtocolCollection.CreateInstance();
- persistenceProtocolCollection->initialize(persistenceProtocolInner);
- }
- }
-
- SmartPtrCPersistenceDoc rc;
- if (! localSecurity.IsNull() || ! persistenceProtocolCollection.IsNull()) {
- rc.CreateInstance();
- rc->initialize(localSecurity, SmartPtrCRemoteSecurityCollectionDoc(),
- persistenceProtocolCollection, persistence->getVersion());
- }
-
- return rc;
-}
-
std::string CConfigEnv::calcListenerContext(
const std::string& uriSchema,
const std::string& configDir) const {
const SmartPtrCPersistenceDoc& persistence,
const SmartPtrIPersistence& persistenceRemove) const;
- SmartPtrCPersistenceDoc createPersistenceUpdated(
- const SmartPtrCPersistenceDoc& persistence) const;
-
std::string calcListenerContext(
const std::string& uriSchema,
const std::string& configDir) const;
#include "stdafx.h"
#include "CConfigEnvMerge.h"
+#ifdef WIN32
+ #include <winsock.h>
+ #pragma comment (lib, "wsock32.lib")
+#else
+ #include <sys/socket.h>
+ #include <netinet/in.h>
+ #include <arpa/inet.h>
+#endif
+
using namespace Caf;
SmartPtrCPersistenceDoc CConfigEnvMerge::mergePersistence(
CAF_CM_VALIDATE_STRING(cacertPath);
CAF_CM_VALIDATE_STRING(vcidPath);
- const std::string cacert = FileSystemUtils::doesFileExist(cacertPath) ?
- FileSystemUtils::loadTextFile(cacertPath) : std::string();
- const std::string vcid = FileSystemUtils::doesFileExist(vcidPath) ?
- FileSystemUtils::loadTextFile(vcidPath) : std::string();
- const std::string protocol = isTunnelEnabled() ? "tunnel" : "amqp";
-
- std::string vcidDiff;
- if (! vcid.empty()) {
- if (persistence->getLocalSecurity()->getLocalId().compare(vcid) != 0) {
- CAF_CM_LOG_DEBUG_VA2("vcid changed - %s != %s",
- persistence->getLocalSecurity()->getLocalId().c_str(), vcid.c_str());
- vcidDiff = vcid;
- }
+ const std::string localId = mergeLocalId(persistence, vcidPath);
+
+ std::string localIdDiff;
+ if (persistence->getLocalSecurity()->getLocalId().compare(localId) != 0) {
+ CAF_CM_LOG_DEBUG_VA2("LocalId changed - %s != %s",
+ persistence->getLocalSecurity()->getLocalId().c_str(), localId.c_str());
+ localIdDiff = localId;
}
+ const std::string cacert = loadTextFile(cacertPath);
+
const std::deque<SmartPtrCPersistenceProtocolDoc> persistenceProtocolCollectionInnerDiff =
mergePersistenceProtocolCollectionInner(
persistence->getPersistenceProtocolCollection()->getPersistenceProtocol(),
- protocol, vcid, cacert);
+ localId, cacert);
SmartPtrCPersistenceDoc rc;
- if (! vcidDiff.empty() || ! persistenceProtocolCollectionInnerDiff.empty()) {
+ if (! localIdDiff.empty() || ! persistenceProtocolCollectionInnerDiff.empty()) {
SmartPtrCLocalSecurityDoc localSecurity = persistence->getLocalSecurity();
- if (! vcidDiff.empty()) {
+ if (! localIdDiff.empty()) {
CAF_CM_LOG_DEBUG_VA0("Creating local security diff");
localSecurity.CreateInstance();
localSecurity->initialize(
- vcidDiff,
+ localIdDiff,
persistence->getLocalSecurity()->getPrivateKey(),
persistence->getLocalSecurity()->getCert(),
persistence->getLocalSecurity()->getPrivateKeyPath(),
return rc;
}
+std::string CConfigEnvMerge::mergeLocalId(
+ const SmartPtrCPersistenceDoc& persistence,
+ const std::string& vcidPath) {
+ CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergeLocalId");
+ CAF_CM_VALIDATE_SMARTPTR(persistence);
+ CAF_CM_VALIDATE_STRING(vcidPath);
+
+ std::string rc = loadTextFile(vcidPath);
+ if (rc.empty()) {
+ if (persistence->getLocalSecurity()->getLocalId().empty()) {
+ rc = CStringUtils::createRandomUuid();
+ } else {
+ rc = persistence->getLocalSecurity()->getLocalId();
+ }
+ }
+
+ return rc;
+}
+
std::deque<SmartPtrCPersistenceProtocolDoc> CConfigEnvMerge::mergePersistenceProtocolCollectionInner(
const std::deque<SmartPtrCPersistenceProtocolDoc>& persistenceProtocolCollectionInner,
- const std::string& protocol,
- const std::string& vcid,
+ const std::string& localId,
const std::string& cacert) {
CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergePersistenceProtocolCollectionInner");
- CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInner.size() <= 1);
+ CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInner.size() == 1);
+ CAF_CM_VALIDATE_STRING(localId);
std::deque<SmartPtrCPersistenceProtocolDoc> rc;
std::deque<SmartPtrCPersistenceProtocolDoc> persistenceProtocolCollectionInnerDiff;
persistenceProtocolIter; persistenceProtocolIter++) {
const SmartPtrCPersistenceProtocolDoc persistenceProtocol = *persistenceProtocolIter;
- const std::string uriDiff = mergeUri(persistenceProtocol->getUri(), protocol, vcid);
+ const std::string uriDiff = mergeUri(
+ persistenceProtocol->getUri(),
+ persistenceProtocol->getUriAmqp(),
+ persistenceProtocol->getUriTunnel(),
+ localId);
const SmartPtrCCertCollectionDoc tlsCertCollectionDiff =
mergeTlsCertCollection(persistenceProtocol->getTlsCertCollection(), cacert);
persistenceProtocolDiff->initialize(
persistenceProtocol->getProtocolName(),
uriDiff.empty() ? persistenceProtocol->getUri() : uriDiff,
+ persistenceProtocol->getUriAmqp(),
+ persistenceProtocol->getUriTunnel(),
persistenceProtocol->getTlsCert(),
persistenceProtocol->getTlsProtocol(),
persistenceProtocol->getTlsCipherCollection(),
}
std::string CConfigEnvMerge::mergeUri(
- const std::string& srcUri,
- const std::string& protocol,
- const std::string& vcid) {
- CAF_CM_STATIC_FUNC_LOG_ONLY("CConfigEnvMerge", "mergeUri");
- std::string rc;
- if (! srcUri.empty()) {
- UriUtils::SUriRecord uriData;
- UriUtils::parseUriString(srcUri, uriData);
-
- bool isUriChanged = false;
- //TODO: Comment back in once isTunnelEnabled() has been implemented
-// if (uriData.protocol.compare(protocol) != 0) {
-// uriData.protocol = protocol;
-// isUriChanged = true;
-// }
- std::string tunnelVcid = vcid;
- if (uriData.protocol.compare("tunnel") == 0) {
- tunnelVcid += "-agentId1";
- }
- if (! tunnelVcid.empty() && (uriData.path.compare(tunnelVcid) != 0)) {
- uriData.path = tunnelVcid;
- isUriChanged = true;
- }
+ const std::string& uri,
+ const std::string& uriAmqp,
+ const std::string& uriTunnel,
+ const std::string& localId) {
+ CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergeUri");
+ CAF_CM_VALIDATE_STRING(uriAmqp);
+ CAF_CM_VALIDATE_STRING(uriTunnel);
+ CAF_CM_VALIDATE_STRING(localId);
- if (isUriChanged) {
- rc = UriUtils::buildUriString(uriData);
- CAF_CM_LOG_DEBUG_VA2("uri changed - %s != %s", srcUri.c_str(), rc.c_str());
- }
+ UriUtils::SUriRecord uriData;
+ if (! uri.empty()) {
+ UriUtils::parseUriString(uri, uriData);
+ }
+
+ const bool isTunnelEnabled = isTunnelEnabledFunc();
+ const std::string uriProtocol = isTunnelEnabled ? "tunnel" : "amqp";
+
+ bool isUriChanged = false;
+ if (uriData.protocol.compare(uriProtocol) != 0) {
+ const std::string uriTmp = isTunnelEnabled ? uriTunnel : uriAmqp;
+ UriUtils::parseUriString(uriTmp, uriData);
+ isUriChanged = true;
+ }
+
+ std::string amqpQueueId = localId;
+ if (isTunnelEnabled) {
+ amqpQueueId += "-agentId1";
+ }
+
+ if (uriData.path.compare(amqpQueueId) != 0) {
+ uriData.path = amqpQueueId;
+ isUriChanged = true;
+ }
+
+ std::string rc;
+ if (isUriChanged) {
+ rc = UriUtils::buildUriString(uriData);
+ CAF_CM_LOG_DEBUG_VA2("uri changed - %s != %s", uri.c_str(), rc.c_str());
}
return rc;
return rc;
}
-//TODO: Implement isTunnelEnabled
-bool CConfigEnvMerge::isTunnelEnabled() {
- return false;
+bool CConfigEnvMerge::isTunnelEnabledFunc() {
+ CAF_CM_STATIC_FUNC_LOG("CConfigEnvMerge", "isTunnelEnabledFunc");
+
+ bool rc = false;
+
+#ifdef WIN32
+ try {
+ WSADATA wsaData;
+ int result = ::WSAStartup(MAKEWORD(2, 2), &wsaData);
+ if (result != NO_ERROR) {
+ CAF_CM_EXCEPTION_VA0(E_UNEXPECTED, "WSAStartup() Failed");
+ }
+
+ SOCKADDR_IN socketClient;
+ memset(&socketClient, 0, sizeof(SOCKADDR_IN));
+ socketClient.sin_family = AF_INET;
+ socketClient.sin_addr.s_addr = ::inet_addr("127.0.0.1");
+ socketClient.sin_port = ::htons(6672);
+
+ SOCKET socketFd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (socketFd == INVALID_SOCKET) {
+ CAF_CM_EXCEPTION_VA1(E_UNEXPECTED, "Failed to open socket - %s", WSAGetLastError());
+ }
+
+ rc = (0 == ::connect(socketFd, (SOCKADDR*) &socketClient, sizeof(socketClient)));
+ }
+ CAF_CM_CATCH_CAF
+ CAF_CM_CATCH_DEFAULT
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CAF_CM_CLEAREXCEPTION;
+
+ WSACleanup();
+#else
+ int socketFd = -1;
+ try {
+ socketFd = ::socket(AF_INET, SOCK_STREAM, 0);
+ if (socketFd < 0) {
+ CAF_CM_EXCEPTION_VA0(E_UNEXPECTED, "Failed to open socket");
+ }
+
+ struct sockaddr_in socketClient;
+ memset(&socketClient, 0, sizeof(sockaddr_in));
+ socketClient.sin_family = AF_INET;
+ socketClient.sin_port = htons(6672);
+
+ int result = ::inet_aton("127.0.0.1", &socketClient.sin_addr);
+ if (0 == result) {
+ CAF_CM_EXCEPTION_VA0(ERROR_PATH_NOT_FOUND,
+ "Failed to get address of 127.0.0.1");
+ }
+
+ rc = (0 == ::connect(socketFd, (struct sockaddr *) &socketClient,
+ sizeof(socketClient)));
+ }
+ CAF_CM_CATCH_CAF
+ CAF_CM_CATCH_DEFAULT
+ CAF_CM_LOG_CRIT_CAFEXCEPTION;
+ CAF_CM_CLEAREXCEPTION;
+
+ if (socketFd >= 0) {
+ ::close(socketFd);
+ }
+#endif
+
+ return rc;
+}
+
+std::string CConfigEnvMerge::loadTextFile(
+ const std::string& path) {
+
+ std::string rc;
+ if (FileSystemUtils::doesFileExist(path)) {
+ rc = FileSystemUtils::loadTextFile(path);
+ rc = CStringUtils::trimRight(rc);
+ }
+
+ return rc;
}
private:
static std::deque<SmartPtrCPersistenceProtocolDoc> mergePersistenceProtocolCollectionInner(
const std::deque<SmartPtrCPersistenceProtocolDoc>& persistenceProtocolCollectionInner,
- const std::string& protocol,
- const std::string& vcid,
+ const std::string& localId,
const std::string& cacert);
+ static std::string mergeLocalId(
+ const SmartPtrCPersistenceDoc& persistence,
+ const std::string& vcidPath);
+
static std::string mergeUri(
- const std::string& srcUri,
- const std::string& protocol,
- const std::string& vcid);
+ const std::string& uri,
+ const std::string& uriAmqp,
+ const std::string& uriTunnel,
+ const std::string& localId);
static SmartPtrCCertCollectionDoc mergeTlsCertCollection(
const SmartPtrCCertCollectionDoc& tlsCertCollection,
const std::string& cacert);
private:
- static bool isTunnelEnabled();
+ static bool isTunnelEnabledFunc();
+
+ static std::string loadTextFile(
+ const std::string& path);
private:
CAF_CM_DECLARE_NOCREATE(CConfigEnvMerge);
CAF_CM_LOG_WARN_VA2("initialize failed - ref: %s, msg: %s",
removeRefStr.c_str(), (CAF_CM_EXCEPTION_GET_FULLMSG).c_str());
rc = SmartPtrIPersistence();
+ CAF_CM_CLEAREXCEPTION;
}
}
_restartListenerPath = FileSystemUtils::buildPath(_monitorDir, "restartListener.txt");
_listenerConfiguredPath = FileSystemUtils::buildPath(_monitorDir, "listenerConfigured.txt");
- _outputDir = AppConfigUtils::getRequiredString(_sAppConfigGlobalParamOutputDir);
+ _scriptOutputDir = AppConfigUtils::getRequiredString(_sConfigTmpDir);
_listenerStartupType = AppConfigUtils::getRequiredString("monitor", "listener_startup_type");
- _listenerRetryMax = AppConfigUtils::getRequiredUint32("monitor", "listener_retry_max");
+ _listenerRetryMax = AppConfigUtils::getRequiredInt32("monitor", "listener_retry_max");
_listenerRestartMs = calcListenerRestartMs();
CAF_CM_LOG_DEBUG_VA1("_listenerRestartMs: %d", _listenerRestartMs);
_isListenerRunningScript = FileSystemUtils::buildPath(scriptsDir, "is-listener-running");
#endif
+ if (! FileSystemUtils::doesDirectoryExist(_monitorDir)) {
+ FileSystemUtils::createDirectory(_monitorDir);
+ }
_isInitialized = true;
}
if (_listenerStartupType.compare("Automatic") == 0) {
if ((_listenerRetryMax < 0) || (_listenerRetryCnt < _listenerRetryMax)) {
reason = "Listener not running... Starting - "
- + CStringConv::toString<uint32>(_listenerRetryCnt + 1) + " of "
- + CStringConv::toString<uint32>(_listenerRetryMax);
+ + CStringConv::toString<int32>(_listenerRetryCnt + 1) + " of "
+ + CStringConv::toString<int32>(_listenerRetryMax);
_listenerRetryCnt++;
_listenerStartTimeMs = CDateTimeUtils::getTimeMs();
startListener(reason);
} else {
reason = "Listener not running... Retries exhausted - "
- + CStringConv::toString<uint32>(_listenerRetryCnt + 1) + " of "
- + CStringConv::toString<uint32>(_listenerRetryMax);
+ + CStringConv::toString<int32>(_listenerRetryCnt + 1) + " of "
+ + CStringConv::toString<int32>(_listenerRetryMax);
CAF_CM_LOG_WARN_VA0(reason.c_str());
}
} else {
}
bool CMonitorReadingMessageSource::isListenerRunning() const {
- const std::string stdoutStr = executeScript(_isListenerRunningScript, _outputDir);
+ const std::string stdoutStr = executeScript(_isListenerRunningScript, _scriptOutputDir);
return (stdoutStr.compare("true") == 0);
}
CAF_CM_LOG_DEBUG_VA1(
"Starting the listener - reason: %s", reason.c_str());
- executeScript(_startListenerScript, _outputDir);
+ executeScript(_startListenerScript, _scriptOutputDir);
}
void CMonitorReadingMessageSource::stopListener(
CAF_CM_LOG_DEBUG_VA1(
"Stopping the listener - reason: %s", reason.c_str());
- executeScript(_stopListenerScript, _outputDir);
+ executeScript(_stopListenerScript, _scriptOutputDir);
}
void CMonitorReadingMessageSource::restartListener(
CAF_CM_LOG_DEBUG_VA1(
"Restarting the listener - reason: %s", reason.c_str());
- executeScript(_stopListenerScript, _outputDir);
- executeScript(_startListenerScript, _outputDir);
+ executeScript(_stopListenerScript, _scriptOutputDir);
+ executeScript(_startListenerScript, _scriptOutputDir);
}
std::string CMonitorReadingMessageSource::executeScript(
std::string _restartListenerPath;
std::string _listenerConfiguredPath;
- std::string _outputDir;
+ std::string _scriptOutputDir;
std::string _stopListenerScript;
std::string _startListenerScript;
std::string _isListenerRunningScript;
std::string _listenerStartupType;
- uint32 _listenerRetryCnt;
- uint32 _listenerRetryMax;
+ int32 _listenerRetryCnt;
+ int32 _listenerRetryMax;
private:
CAF_CM_CREATE;
CAF_CM_LOG_WARN_VA2("initialize failed - ref: %s, msg: %s",
removeRefStr.c_str(), (CAF_CM_EXCEPTION_GET_FULLMSG).c_str());
rc = SmartPtrIPersistence();
+ CAF_CM_CLEAREXCEPTION;
}
return rc;
rc->initialize(
protocolName.empty() ? persistenceProtocolIn->getProtocolName() : protocolName,
uri.empty() ? persistenceProtocolIn->getUri() : uri,
+ persistenceProtocolLoaded->getUriAmqp(),
+ persistenceProtocolLoaded->getUriTunnel(),
tlsCert.empty() ? persistenceProtocolIn->getTlsCert() : tlsCert,
tlsProtocol.empty() ? persistenceProtocolIn->getTlsProtocol() : tlsProtocol,
tlsCipherCollection.empty() ? persistenceProtocolIn->getTlsCipherCollection() : tlsCipherCollection,
#include <string>
using namespace Caf;
-using namespace std;
-
-#ifdef WIN32
- const string CPersistenceNamespaceDb::_NAMESPACE_DB_CMD_FILE = "VMwareNamespaceCmd.exe";
-#else
- const string CPersistenceNamespaceDb::_NAMESPACE_DB_CMD_FILE = "vmware-namespace-cmd";
-#endif
-
-const string CPersistenceNamespaceDb::_NAMESPACE = "com.vmware.caf.guest.rw";
CPersistenceNamespaceDb::CPersistenceNamespaceDb() :
_isInitialized(false),
_isReady(false),
CAF_CM_INIT_LOG("CPersistenceNamespaceDb") {
CAF_CM_INIT_THREADSAFE;
+ _nsdbNamespace = "com.vmware.caf.guest.rw";
}
CPersistenceNamespaceDb::~CPersistenceNamespaceDb() {
SmartPtrCPersistenceDoc rc;
if (isReady()) {
//If nothing has been updated, skip all of the unneeded work
- string updates = getValue("updates");
+ const std::string updates = getValue("updates");
if (!updates.empty()) {
- string version = getValue("version");
+ const std::string version = getValue("version");
//EP Doc
- string epLocalId = getValue("ep.local_id");
- string epPrivateKey = getValue("ep.private_key");
- string epCert = getValue("ep.cert");
+ const std::string epLocalId = getValue("ep.local_id");
+ const std::string epPrivateKey = getValue("ep.private_key");
+ const std::string epCert = getValue("ep.cert");
+
SmartPtrCLocalSecurityDoc endpoint;
endpoint.CreateInstance();
endpoint->initialize(epLocalId, epPrivateKey, epCert);
//App collection
std::deque<SmartPtrCRemoteSecurityDoc> applicationCollectionInner;
- string applications = getValue("applications");
+ const std::string applications = getValue("applications");
Cdeqstr appList = CStringUtils::split(applications, ',');
for (Cdeqstr::iterator appIt = appList.begin(); appIt != appList.end(); appIt++) {
- string appKey = "app." + *appIt;
- string appId = getValue(appKey + ".remote_id");
- string appProtocolName = getValue(appKey + ".protocol_name");
- string appCmsCipher = getValue(appKey + ".cms.cipher");
+ const std::string appKey = "app." + *appIt;
+ const std::string appId = getValue(appKey + ".remote_id");
+ const std::string appProtocolName = getValue(appKey + ".protocol_name");
+ const std::string appCmsCipher = getValue(appKey + ".cms.cipher");
std::deque<std::string> cmsCertCollectionInner;
- string appCmsCertChain = getValue(appKey + ".cms.cert_chain");
+ const std::string appCmsCertChain = getValue(appKey + ".cms.cert_chain");
Cdeqstr appCertList = CStringUtils::split(appCmsCertChain, ',');
for (Cdeqstr::iterator appCertIt = appCertList.begin(); appCertIt != appCertList.end(); appCertIt++) {
cmsCertCollectionInner.push_back(*appCertIt);
cmsCertCollection.CreateInstance();
cmsCertCollection->initialize(cmsCertCollectionInner);
- string cmsCert = getValue(appKey + ".cms.cert");
+ const std::string cmsCert = getValue(appKey + ".cms.cert");
SmartPtrCRemoteSecurityDoc application;
application.CreateInstance();
- application->initialize(appId, appProtocolName, cmsCert, appCmsCipher, cmsCertCollection);
+ application->initialize(appId, appProtocolName, cmsCert, appCmsCipher,
+ cmsCertCollection);
applicationCollectionInner.push_back(application);
}
applicationCollection.CreateInstance();
applicationCollection->initialize(applicationCollectionInner);
- string protocols = getValue("protocols");
+ const std::string protocols = getValue("protocols");
Cdeqstr protocolList = CStringUtils::split(protocols, ',');
std::deque<SmartPtrCPersistenceProtocolDoc> persistenceProtocolCollectionInner;
for (Cdeqstr::iterator protocolIt = protocolList.begin(); protocolIt != protocolList.end(); protocolIt++) {
- string protocolKey = "protocol." + *protocolIt;
+ const std::string protocolKey = "protocol." + *protocolIt;
//Protoccol Doc
std::deque<std::string> tlsCertCollectionInner;
- string tlsCertChain = getValue(protocolKey + ".tls.cert.chain");
+ const std::string tlsCertChain = getValue(protocolKey + ".tls.cert.chain");
Cdeqstr tlsCertList = CStringUtils::split(tlsCertChain, ',');
for (Cdeqstr::iterator tlsCertIt = tlsCertList.begin(); tlsCertIt != tlsCertList.end(); tlsCertIt++) {
tlsCertCollectionInner.push_back(*tlsCertIt);
}
Cdeqstr tlsCipherCollection;
- string tlsCiphers = getValue(protocolKey + ".tls.ciphers");
+ const std::string tlsCiphers = getValue(protocolKey + ".tls.ciphers");
Cdeqstr tlsCipherList = CStringUtils::split(tlsCiphers, ',');
for (Cdeqstr::iterator tlsCipherIt = tlsCipherList.begin(); tlsCipherIt != tlsCipherList.end(); tlsCipherIt++) {
tlsCipherCollection.push_back(*tlsCipherIt);
tlsCertCollection->initialize(tlsCertCollectionInner);
//For now, we only support one broker.
- string protocolName = getValue(protocolKey + ".protocol_name");
- string uri = getValue(protocolKey + ".uri");
- string tlsCert = getValue(protocolKey + ".tls.cert");
- string tlsProtocol = getValue(protocolKey + ".tls.protocol");
+ const std::string protocolName = getValue(protocolKey + ".protocol_name");
+ const std::string uri = getValue(protocolKey + ".uri");
+ const std::string uriAmqp = getValue(protocolKey + ".uri.amqp");
+ const std::string uriTunnel = getValue(protocolKey + ".uri.tunnel");
+ const std::string tlsCert = getValue(protocolKey + ".tls.cert");
+ const std::string tlsProtocol = getValue(protocolKey + ".tls.protocol");
+
SmartPtrCPersistenceProtocolDoc persistenceProtocol;
persistenceProtocol.CreateInstance();
- persistenceProtocol->initialize(protocolName, uri, tlsCert, tlsProtocol, tlsCipherCollection, tlsCertCollection);
+ persistenceProtocol->initialize(
+ protocolName, uri, uriAmqp, uriTunnel, tlsCert, tlsProtocol,
+ tlsCipherCollection, tlsCertCollection);
persistenceProtocolCollectionInner.push_back(persistenceProtocol);
}
//Update RemoteSecurity info
if (!persistenceCur->getRemoteSecurityCollection().IsNull()){
- deque<SmartPtrCRemoteSecurityDoc> applications = persistenceCur->getRemoteSecurityCollection()->getRemoteSecurity();
- for (deque<SmartPtrCRemoteSecurityDoc>::iterator appIt=applications.begin(); appIt != applications.end(); appIt++) {
- string appKey = "app." + (*appIt)->getRemoteId();
+ std::deque<SmartPtrCRemoteSecurityDoc> applications =
+ persistenceCur->getRemoteSecurityCollection()->getRemoteSecurity();
+ for (std::deque<SmartPtrCRemoteSecurityDoc>::iterator appIt = applications.begin(); appIt != applications.end(); appIt++) {
+ const std::string appKey = "app." + (*appIt)->getRemoteId();
+
setValue(appKey + ".remote_id", (*appIt)->getRemoteId());
setValue(appKey + ".cms.cert", (*appIt)->getCmsCert());
setValue(appKey + ".cms.cipher", (*appIt)->getCmsCipherName());
setValue(appKey + ".protocol_name", (*appIt)->getProtocolName());
- string cmsCertChain;
+
+ std::string cmsCertChain;
if (! (*appIt)->getCmsCertCollection().IsNull()) {
Cdeqstr cmsCertList = (*appIt)->getCmsCertCollection()->getCert();
for (Cdeqstr::iterator cmsCertIt=cmsCertList.begin(); cmsCertIt != cmsCertList.end(); cmsCertIt++) {
}
cmsCertChain += *cmsCertIt;
}
+
setValue(appKey + ".cms.cert_chain", cmsCertChain);
}
}
//For now, we only support one broker.
CAF_CM_ASSERT(persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol().size() <= 1);
- deque<SmartPtrCPersistenceProtocolDoc> brokerList = persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol();
- for (deque<SmartPtrCPersistenceProtocolDoc>::iterator protIt=brokerList.begin(); protIt != brokerList.end(); protIt++) {
- string protocolKey = "protocol." + (*protIt)->getProtocolName();
+ std::deque<SmartPtrCPersistenceProtocolDoc> brokerList = persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol();
+ for (std::deque<SmartPtrCPersistenceProtocolDoc>::iterator protIt=brokerList.begin(); protIt != brokerList.end(); protIt++) {
+ const std::string protocolKey = "protocol." + (*protIt)->getProtocolName();
setValue(protocolKey + ".protocol_name", (*protIt)->getProtocolName());
setValue(protocolKey + ".uri", (*protIt)->getUri());
+ setValue(protocolKey + ".uri.amqp", (*protIt)->getUriAmqp());
+ setValue(protocolKey + ".uri.tunnel", (*protIt)->getUriTunnel());
setValue(protocolKey + ".tls.cert", (*protIt)->getTlsCert());
setValue(protocolKey + ".tls.protocol", (*protIt)->getTlsProtocol());
Cdeqstr tlsCipherList = (*protIt)->getTlsCipherCollection();
- string tlsCiphers;
+ std::string tlsCiphers;
for (Cdeqstr::iterator tlsCipherIt=tlsCipherList.begin(); tlsCipherIt != tlsCipherList.end(); tlsCipherIt++) {
if (!tlsCiphers.empty()) {
tlsCiphers += ",";
if (! (*protIt)->getTlsCertCollection().IsNull()) {
Cdeqstr tlsCertList = (*protIt)->getTlsCertCollection()->getCert();
- string tlsCerts;
+ std::string tlsCerts;
for (Cdeqstr::iterator tlsCertIt=tlsCertList.begin(); tlsCertIt != tlsCertList.end(); tlsCertIt++) {
if (!tlsCerts.empty()) {
tlsCerts += ",";
//Remove RemoteSecurity info
if (!persistenceCur->getRemoteSecurityCollection().IsNull()){
- deque<SmartPtrCRemoteSecurityDoc> applications = persistenceCur->getRemoteSecurityCollection()->getRemoteSecurity();
- for (deque<SmartPtrCRemoteSecurityDoc>::iterator it=applications.begin(); it != applications.end(); it++) {
- string appKey = "app." + (*it)->getRemoteId();
+ std::deque<SmartPtrCRemoteSecurityDoc> applications = persistenceCur->getRemoteSecurityCollection()->getRemoteSecurity();
+ for (std::deque<SmartPtrCRemoteSecurityDoc>::iterator it=applications.begin(); it != applications.end(); it++) {
+ std::string appKey = "app." + (*it)->getRemoteId();
if (!(*it)->getProtocolName().empty()) {
removeKey(appKey + ".protocol_name");
}
//For now, we only support one broker.
CAF_CM_ASSERT(persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol().size() <= 1);
- deque<SmartPtrCPersistenceProtocolDoc> brokerList = persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol();
- for (deque<SmartPtrCPersistenceProtocolDoc>::iterator it=brokerList.begin(); it != brokerList.end(); it++) {
- string protocolKey = "protocol." + (*it)->getProtocolName();
+ std::deque<SmartPtrCPersistenceProtocolDoc> brokerList = persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol();
+ for (std::deque<SmartPtrCPersistenceProtocolDoc>::iterator it=brokerList.begin(); it != brokerList.end(); it++) {
+ std::string protocolKey = "protocol." + (*it)->getProtocolName();
if (!(*it)->getUri().empty()) {
removeKey(protocolKey + "uri");
}
+ if (!(*it)->getUriAmqp().empty()) {
+ removeKey(protocolKey + "uri.amqp");
+ }
+ if (!(*it)->getUriTunnel().empty()) {
+ removeKey(protocolKey + "uri.tunnel");
+ }
if (!(*it)->getTlsCert().empty()) {
removeKey(protocolKey + "tls.cert");
}
}
}
-string CPersistenceNamespaceDb::getCmdPath() {
-// CAF_CM_STATIC_FUNC("CPersistenceNamespaceDb", "getCmdPath");
-// "/usr/sbin/vmware-namespace-cmd";
- string cmdPath = "/usr/sbin";
+void CPersistenceNamespaceDb::setCmd() {
+ CAF_CM_FUNCNAME("setCmd");
+
+ std::string nsdbCmdDir;
+ std::string nsdbCmdFile;
#ifdef WIN32
-// "C:/Program Files/VMware/VMware Tools/VMwareNamespaceCmd.exe";
-// bin_dir=C:/Program Files/VMware/VMware Tools/VMware CAF/pme//bin
- cmdPath = AppConfigUtils::getRequiredString("globals", "bin_dir");
+ // "C:/Program Files/VMware/VMware Tools/VMwareNamespaceCmd.exe";
+ // bin_dir=C:/Program Files/VMware/VMware Tools/VMware CAF/pme//bin
+ nsdbCmdDir = AppConfigUtils::getRequiredString("globals", "bin_dir");
+
//Back up two levels
- cmdPath = FileSystemUtils::getDirname(cmdPath);
- cmdPath = FileSystemUtils::getDirname(cmdPath);
+ nsdbCmdDir = FileSystemUtils::getDirname(nsdbCmdDir);
+ nsdbCmdDir = FileSystemUtils::getDirname(nsdbCmdDir);
+
+ nsdbCmdFile = "VMwareNamespaceCmd.exe";
+#else
+ nsdbCmdDir = "/usr/sbin";
+ nsdbCmdFile = "vmware-namespace-cmd";
#endif
- return cmdPath;
-}
-void CPersistenceNamespaceDb::setCmd() {
- CAF_CM_FUNCNAME("setCmd");
- _namespaceDbCmd = FileSystemUtils::buildPath(getCmdPath(), _NAMESPACE_DB_CMD_FILE);
- CAF_CM_LOG_DEBUG_VA1("_namespaceDbCmd: %s", _namespaceDbCmd.c_str());
- if (!FileSystemUtils::doesFileExist(_namespaceDbCmd)) {
+ _nsdbCmdPath = FileSystemUtils::buildPath(nsdbCmdDir, nsdbCmdFile);
+ CAF_CM_LOG_DEBUG_VA1("_nsdbCmdPath: %s", _nsdbCmdPath.c_str());
+ if (!FileSystemUtils::doesFileExist(_nsdbCmdPath)) {
CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND,
- "Namespace DB command not found - %s", _namespaceDbCmd.c_str());
+ "Namespace DB command not found - %s", _nsdbCmdPath.c_str());
}
}
-string CPersistenceNamespaceDb::getValue(const std::string& key) {
+std::string CPersistenceNamespaceDb::getValue(const std::string& key) {
CAF_CM_FUNCNAME("getValue");
CAF_CM_VALIDATE_STRING(key);
- string value;
- string stdoutContent;
- string stderrContent;
+ std::string value;
+ std::string stdoutContent;
+ std::string stderrContent;
try {
value = getValueRaw(key, stdoutContent, stderrContent);
}
return value;
}
-void CPersistenceNamespaceDb::setValue(const std::string& key, const std::string& value) {
+void CPersistenceNamespaceDb::setValue(
+ const std::string& key,
+ const std::string& value) {
CAF_CM_FUNCNAME("setValue");
CAF_CM_VALIDATE_STRING(key);
return;
}
- string stdoutContent;
- string stderrContent;
+ std::string stdoutContent;
+ std::string stderrContent;
Cdeqstr argv;
- string tmpFile;
+ std::string tmpFile;
try {
//TODO: generate hash of value
tmpFile = FileSystemUtils::saveTempTextFile("caf_nsdb_XXXXXX", value);
CAF_CM_LOG_DEBUG_VA2("Setting %s to %s", key.c_str(), value.c_str());
- argv.push_back(_namespaceDbCmd);
+ argv.push_back(_nsdbCmdPath);
argv.push_back("set-key");
- argv.push_back(_NAMESPACE);
+ argv.push_back(_nsdbNamespace);
argv.push_back("-k");
argv.push_back(key);
argv.push_back("-f");
ProcessUtils::runSync(argv, stdoutContent, stderrContent);
//Add to key+hash _cache
- //TODO: generate a hash of the value string
+ //TODO: generate a hash of the value std::string
_cache[key] = value; //As a temporary hack use the entire value as the "hash"
}
catch(ProcessFailedException* ex){
CAF_CM_FUNCNAME("removeKey");
CAF_CM_VALIDATE_STRING(key);
- string stdoutContent;
- string stderrContent;
+ std::string stdoutContent;
+ std::string stderrContent;
Cdeqstr argv;
try {
- argv.push_back(_namespaceDbCmd);
+ argv.push_back(_nsdbCmdPath);
argv.push_back("delete-key");
- argv.push_back(_NAMESPACE);
+ argv.push_back(_nsdbNamespace);
argv.push_back("-k");
argv.push_back(key);
bool rc = true;
if (! _isReady) {
- string stdoutContent;
- string stderrContent;
+ std::string stdoutContent;
+ std::string stderrContent;
try {
(void) getValueRaw("updates", stdoutContent, stderrContent);
_isReady = true;
return rc;
}
-string CPersistenceNamespaceDb::getValueRaw(
+std::string CPersistenceNamespaceDb::getValueRaw(
const std::string& key,
- string& stdoutContent,
- string& stderrContent) {
+ std::string& stdoutContent,
+ std::string& stderrContent) {
CAF_CM_FUNCNAME_VALIDATE("getValueRaw");
CAF_CM_VALIDATE_STRING(key);
Cdeqstr argv;
- argv.push_back(_namespaceDbCmd);
+ argv.push_back(_nsdbCmdPath);
argv.push_back("get-value");
- argv.push_back(_NAMESPACE);
+ argv.push_back(_nsdbNamespace);
argv.push_back("-k");
argv.push_back(key);
ProcessUtils::runSync(argv, stdoutContent, stderrContent);
- string value = stdoutContent;
+ std::string value = stdoutContent;
//strip spaces
value = CStringUtils::trim(value);
value.erase(value.length()-1,1);
}
//TODO: parse hash from nsdb value
- string hash = value; //As a temporary hack, use the entire value as the "hash"
+ std::string hash = value; //As a temporary hack, use the entire value as the "hash"
//if hash has not changed, return empty
if (_cache[key] == hash) {
CAF_CM_LOG_DEBUG_VA1("Value for %s has not changed", key.c_str());
const SmartPtrCPersistenceDoc& persistence);
private:
- static std::string getCmdPath();
void setCmd();
- std::string getValue(const std::string& key);
- void setValue(const std::string& key, const std::string& value);
+
+ std::string getValue(
+ const std::string& key);
+
+ void setValue(
+ const std::string& key,
+ const std::string& value);
+
void removeKey(const std::string& key);
+
bool isReady();
+
std::string getValueRaw(
const std::string& key,
std::string& stdoutContent,
private:
bool _isInitialized;
bool _isReady;
- static const std::string _NAMESPACE_DB_CMD_FILE;
- static const std::string _NAMESPACE;
- std::string _namespaceDbCmd;
+
+ std::string _nsdbCmdPath;
+ std::string _nsdbNamespace;
Cmapstrstr _cache;
+
SmartPtrCPersistenceDoc _persistenceUpdate;
SmartPtrCPersistenceDoc _persistenceRemove;
CAF_CM_LOG_WARN_VA2("initialize failed - ref: %s, msg: %s",
removeRefStr.c_str(), (CAF_CM_EXCEPTION_GET_FULLMSG).c_str());
rc = SmartPtrIPersistence();
+ CAF_CM_CLEAREXCEPTION;
}
return rc;
}
FileSystemUtils::createDirectory(providerSchemaCacheDir);
-
- if (AppConfigUtils::getRequiredBoolean("managementAgent", "remap_logging_location")) {
- loggingSetter->initialize(providerSchemaCacheDir);
- }
+ loggingSetter->initialize(providerSchemaCacheDir);
}
void CProviderCollectSchemaExecutor::runProvider(
_isInitialized(false),
_isCancelled(false),
CAF_CM_INIT_LOG("CProviderExecutorRequestHandler") {
- _taskExecutor = NULL;
+ CAF_CM_INIT_THREADSAFE;
}
CProviderExecutorRequestHandler::~CProviderExecutorRequestHandler() {
const SmartPtrITransformer endImpersonationTransformer,
const SmartPtrIErrorHandler errorHandler) {
CAF_CM_FUNCNAME("initialize");
-
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_STRING(providerUri);
"Provider path not found - %s", _providerPath.c_str());
}
- SmartPtrCAutoMutex mutex;
- mutex.CreateInstance();
- mutex->initialize();
- _mutex = mutex;
-
_beginImpersonationTransformer = beginImpersonationTransformer;
_endImpersonationTransformer = endImpersonationTransformer;
_errorHandler = errorHandler;
_isInitialized = true;
}
-void CProviderExecutorRequestHandler::handleRequest(const SmartPtrCProviderExecutorRequest request) {
+void CProviderExecutorRequestHandler::handleRequest(
+ const SmartPtrCProviderExecutorRequest request) {
CAF_CM_FUNCNAME("handleRequest");
-
+ CAF_CM_LOCK_UNLOCK;
+ CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_SMARTPTR(request);
+
if (_providerUri.compare(request->getProviderUri()) != 0) {
CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, ERROR_INVALID_PARAMETER,
"Provider request not for current provider - %s", _providerUri.c_str());
}
- CAutoMutexLockUnlock lock(_mutex);
- if (_isCancelled) {
- CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, ERROR_INVALID_STATE,
- "Provider canceled: %s", _providerUri.c_str());
- }
- _pendingRequests.push_back(request);
-
- if (_taskExecutor == NULL) {
- SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor;
- simpleAsyncTaskExecutor.CreateInstance();
- simpleAsyncTaskExecutor->initialize(this, _errorHandler);
- _taskExecutor = simpleAsyncTaskExecutor;
- _taskExecutor->execute(0);
- }
-}
-
-SmartPtrCProviderExecutorRequest CProviderExecutorRequestHandler::getNextPendingRequest() {
- CAutoMutexLockUnlock lock(_mutex);
-
- SmartPtrCProviderExecutorRequest request;
- if (_isCancelled || _pendingRequests.empty()) {
- _taskExecutor = NULL;
- return request;
- }
- request = _pendingRequests.front();
- _pendingRequests.pop_front();
- return request;
+ executeRequestAsync(request);
}
void CProviderExecutorRequestHandler::run() {
CAF_CM_FUNCNAME("run");
-
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
SmartPtrIIntMessage message;
- SmartPtrCProviderExecutorRequest request = getNextPendingRequest();
- while (!request.IsNull()) {
+ const SmartPtrCProviderExecutorRequest request = getNextPendingRequest();
+ if (! request.IsNull()) {
try {
processRequest(request);
}
CAF_CM_CLEAREXCEPTION;
}
-
- request = getNextPendingRequest();
}
+
CAF_CM_LOG_DEBUG_VA0("Finished");
}
void CProviderExecutorRequestHandler::cancel() {
CAF_CM_FUNCNAME_VALIDATE("cancel");
+ CAF_CM_LOCK_UNLOCK;
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_LOG_DEBUG_VA0("Canceling");
-
- CAutoMutexLockUnlock lock(_mutex);
_isCancelled = true;
}
+SmartPtrCProviderExecutorRequest CProviderExecutorRequestHandler::getNextPendingRequest() {
+
+ SmartPtrCProviderExecutorRequest rc;
+ if (! _isCancelled && ! _pendingRequests.empty()) {
+ rc = _pendingRequests.front();
+ _pendingRequests.pop_front();
+ }
+
+ return rc;
+}
+
void CProviderExecutorRequestHandler::processRequest(
const SmartPtrCProviderExecutorRequest& request) const {
CAF_CM_FUNCNAME_VALIDATE("processRequest");
- CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_SMARTPTR(request);
- const std::string& outputDir = request->getOutputDirectory();
- if (AppConfigUtils::getRequiredBoolean("managementAgent", "remap_logging_location")) {
- SmartPtrCLoggingSetter loggingSetter;
- loggingSetter.CreateInstance();
- loggingSetter->initialize(outputDir);
- }
+ const std::string outputDir = request->getOutputDirectory();
+
+ SmartPtrCLoggingSetter loggingSetter;
+ loggingSetter.CreateInstance();
+ loggingSetter->initialize(outputDir);
SmartPtrIIntMessage message = request->getInternalRequest();
}
}
- ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath, priority);
+ {
+ CAF_CM_UNLOCK_LOCK;
+ ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath, priority);
+ }
// End impersonation
if (!_endImpersonationTransformer.IsNull()) {
FileSystemUtils::saveByteFile(filePath, payload->getPtr(), payload->getByteCount(),
FileSystemUtils::FILE_MODE_REPLACE, ".writing");
}
+
+void CProviderExecutorRequestHandler::executeRequestAsync(
+ const SmartPtrCProviderExecutorRequest& request) {
+ CAF_CM_FUNCNAME_VALIDATE("executeRequestAsync");
+ CAF_CM_VALIDATE_SMARTPTR(request);
+
+ _pendingRequests.push_back(request);
+
+ _taskExecutors = removeFinishedTaskExecutors(_taskExecutors);
+
+ SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor;
+ simpleAsyncTaskExecutor.CreateInstance();
+ simpleAsyncTaskExecutor->initialize(this, _errorHandler);
+ _taskExecutors.push_back(simpleAsyncTaskExecutor);
+ simpleAsyncTaskExecutor->execute(0);
+}
+
+std::deque<SmartPtrITaskExecutor> CProviderExecutorRequestHandler::removeFinishedTaskExecutors(
+ const std::deque<SmartPtrITaskExecutor> taskExecutors) const {
+
+ std::deque<SmartPtrITaskExecutor> taskExecutorsTmp;
+ for (TConstIterator<std::deque<SmartPtrITaskExecutor> > iter(taskExecutors);
+ iter; iter++) {
+ const SmartPtrITaskExecutor taskExecutorIter = *iter;
+ if (! ((taskExecutorIter->getState() == ITaskExecutor::ETaskStateFinished)
+ || (taskExecutorIter->getState() == ITaskExecutor::ETaskStateFailed))) {
+ taskExecutorsTmp.push_back(taskExecutorIter);
+ }
+ }
+
+ return taskExecutorsTmp;
+}
private:
SmartPtrCProviderExecutorRequest getNextPendingRequest();
+
void processRequest(const SmartPtrCProviderExecutorRequest& request) const;
+ void executeRequestAsync(
+ const SmartPtrCProviderExecutorRequest& request);
+
+ std::deque<SmartPtrITaskExecutor> removeFinishedTaskExecutors(
+ const std::deque<SmartPtrITaskExecutor> taskExecutors) const;
+
private:
bool _isInitialized;
bool _isCancelled;
std::string _providerPath;
std::string _providerUri;
- SmartPtrITaskExecutor _taskExecutor;
+ std::deque<SmartPtrITaskExecutor> _taskExecutors;
SmartPtrCAutoMutex _mutex;
std::deque<SmartPtrCProviderExecutorRequest> _pendingRequests;
SmartPtrITransformer _beginImpersonationTransformer;
private:
CAF_CM_CREATE;
CAF_CM_CREATE_LOG;
+ CAF_CM_CREATE_THREADSAFE;
CAF_CM_DECLARE_NOCOPY(CProviderExecutorRequestHandler);
};
schema_namespace_root=http://schemas.vmware.com/caf/schema
schema_location_root=${input_dir}/schemas/caf
-use_single_logging=true
+remap_logging_location=false
[communication_amqp]
working_dir=${output_dir}/comm-wrk
schema_namespace_root=http://schemas.vmware.com/caf/schema
schema_location_root=${input_dir}/schemas/caf
-use_single_logging=true
+remap_logging_location=false
[security]
cms_policy=CAF_Encrypted_And_Signed
host_delay_sec=5
host_integration_timeout_ms=5000
use_impersonation=false
-remap_logging_location=true
# Value used to specify the priority that provider sub-process are created at.
# Valid values are: NORMAL, LOW, IDLE. Default value is NORMAL.
provider_process_priority=NORMAL
schema_namespace_root=http://schemas.vmware.com/caf/schema
schema_location_root=${input_dir}/schemas/caf
-use_single_logging=true
+remap_logging_location=false
[providerHost]
install_dir=${config_dir}/../install
validateNotEmpty "$password" "password"
local uriFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/uri.txt"
+ local uriAmqpFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/uri_amqp.txt"
sed -i "s/#amqpUsername#/${username}/g" "$uriFile"
sed -i "s/#amqpPassword#/${password}/g" "$uriFile"
+ sed -i "s/#amqpUsername#/${username}/g" "$uriAmqpFile"
+ sed -i "s/#amqpPassword#/${password}/g" "$uriAmqpFile"
}
function setBroker() {
validateNotEmpty "$brokerAddr" "brokerAddr"
local uriFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/uri.txt"
+ local uriAmqpFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/uri_amqp.txt"
sed -i "s/#brokerAddr#/$brokerAddr/g" "$uriFile"
+ sed -i "s/#brokerAddr#/$brokerAddr/g" "$uriAmqpFile"
}
function setListenerConfigured() {
+ mkdir -p "$CAF_INPUT_DIR/monitor"
echo "Manual" > "$CAF_INPUT_DIR/monitor/listenerConfigured.txt"
}
echo ""
echo " * checkTunnel Checks the AMQP Tunnel "
echo " * checkCerts Checks the certificates"
- echo " * checkCertsVerbose Checks the certificates"
- echo " * checkToolsInstall Checks the Tools install"
+ echo " * prtCerts Prints the certificates"
+ echo " * checkVmwTools Checks VMware Tools"
echo ""
echo " * validateXml Validates the XML files against the published schema"
echo " * validateInstall Validates that the files are in the right locations and have the right permissions"
}
function checkCerts() {
- local certDir="$CAF_INPUT_DIR/certs"
+ local localDir="$CAF_INPUT_DIR/persistence/local"
+ local cacertFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem"
- pushd $certDir > /dev/null
+ prtHeader "Checking private key - $localDir/privateKey.pem"
+ openssl rsa -in "$localDir/privateKey.pem" -check -noout
- prtHeader "Checking certs - $certDir"
+ prtHeader "Checking cert - $localDir/cert.pem"
+ openssl verify -check_ss_sig -x509_strict -CAfile "$cacertFile" "$localDir/cert.pem"
- openssl rsa -in privateKey.pem -check -noout
- openssl verify -check_ss_sig -x509_strict -CAfile cacert.pem publicKey.pem
-
- local clientCertMd5=$(openssl x509 -noout -modulus -in publicKey.pem | openssl md5 | cut -d' ' -f2)
- local clientKeyMd5=$(openssl rsa -noout -modulus -in privateKey.pem | openssl md5 | cut -d' ' -f2)
+ prtHeader "Validating that private key and cert match - $localDir/cert.pem"
+ local clientCertMd5=$(openssl x509 -noout -modulus -in "$localDir/cert.pem" | openssl md5 | cut -d' ' -f2)
+ local clientKeyMd5=$(openssl rsa -noout -modulus -in "$localDir/privateKey.pem" | openssl md5 | cut -d' ' -f2)
if [ "$clientCertMd5" == "$clientKeyMd5" ]; then
echo "Public and Private Key md5's match"
else
echo "*** Public and Private Key md5's do not match"
exit 1
fi
-
- popd > /dev/null
}
-function checkCertsVerbose() {
- local certDir="$CAF_INPUT_DIR/certs"
-
- pushd $certDir > /dev/null
+function prtCerts() {
+ local localDir="$CAF_INPUT_DIR/persistence/local"
+ local cacertFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem"
- prtHeader "Checking $certDir/cacert.pem"
- openssl x509 -in cacert.pem -text -noout
+ prtHeader "Printing - $cacertFile"
+ openssl x509 -in "$cacertFile" -text -noout
- prtHeader "Checking $certDir/publicKey.pem"
- openssl x509 -in publicKey.pem -text -noout
-
- prtHeader "Checking /etc/vmware-tools/GuestProxyData/server/cert.pem"
- openssl x509 -in /etc/vmware-tools/GuestProxyData/server/cert.pem -text -noout
-
- popd > /dev/null
+ prtHeader "Printing - $localDir/cert.pem"
+ openssl x509 -in "$localDir/cert.pem" -text -noout
}
function checkTunnel() {
- local certDir="$CAF_INPUT_DIR/certs"
-
- pushd $certDir > /dev/null
+ local localDir="$CAF_INPUT_DIR/persistence/local"
+ local cacertFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem"
prtHeader "Connecting to tunnel"
- openssl s_client -connect localhost:6672 -key privateKey.pem -cert publicKey.pem -CAfile cacert.pem -verify 10
-
- popd > /dev/null
+ openssl s_client -connect localhost:6672 -key "$localDir/privateKey.pem" -cert "$localDir/cert.pem" -CAfile "$cacertFile" -verify 10
}
-function checkToolsInstall() {
- systemctl status vmware-tools.service
+function checkVmwTools() {
+ local isToolboxCmd=$(which vmware-toolbox-cmd 2>/dev/null)
+ if [ "$isToolboxCmd" != "" ]; then
+ vmware-toolbox-cmd --version
+ else
+ echo "It doesn't appear as though VMware Tools is installed"
+ fi
+
+ local isSystemctl=$(which systemctl 2>/dev/null)
+ if [ "$isSystemctl" != "" ]; then
+ systemctl status vmware-tools.service
+ fi
}
function validateInstall() {
checkFileExists "$CAF_CONFIG_DIR/ma-log4cpp_config"
checkFileExists "$CAF_CONFIG_DIR/providerFx-appconfig"
checkFileExists "$CAF_CONFIG_DIR/providerFx-log4cpp_config"
- checkFileExists "$CAF_CONFIG_DIR/persistence-appconfig"
}
function checkFileExistsScripts() {
$CAF_OUTPUT_DIR/providerHost/* \
$CAF_OUTPUT_DIR/responses/* \
$CAF_OUTPUT_DIR/requests/* \
+ $CAF_OUTPUT_DIR/split-requests/* \
$CAF_OUTPUT_DIR/request_state/* \
$CAF_OUTPUT_DIR/events/* \
- $CAF_OUTPUT_DIR/errorResponse.xml \
+ $CAF_OUTPUT_DIR/tmp/* \
+ $CAF_OUTPUT_DIR/att/* \
$CAF_LOG_DIR/* \
$CAF_BIN_DIR/*.log
}
checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-appconfig"
checkFileExists "$CAF_CONFIG_DIR/providerFx-log4cpp_config"
checkFileExists "$CAF_CONFIG_DIR/cafenv-appconfig"
- checkFileExists "$CAF_CONFIG_DIR/persistence-appconfig"
}
function checkFileExistsScripts() {
"checkCerts")
checkCerts "$certDir"
;;
- "checkCertsVerbose")
- checkCertsVerbose "$certDir"
+ "prtCerts")
+ prtCerts "$certDir"
;;
"checkTunnel")
checkTunnel "$certDir"
;;
- "checkToolsInstall")
- checkToolsInstall
+ "checkVmwTools")
+ checkVmwTools
;;
"getAmqpQueueName")
getAmqpQueueName
providersDir="$inputDir/providers"
invokersDir="$inputDir/invokers"
-persistenceDir="$inputDir/persistence"
-protocolDir="$persistenceDir/protocol"
-localDir="$persistenceDir/local"
-amqpBrokerDir="$protocolDir/amqpBroker_default"
-tlsCertCollectionDir="$amqpBrokerDir/tlsCertCollection"
+amqpBrokerDir="$inputDir/persistence/protocol/amqpBroker_default"
logDir="${D}/var/log/$stdQuals"
installDir="$baseEtcDir/install"
scriptDir="$baseEtcDir/scripts"
-#Ensure directories exist
-mkdir -p "$outputDir"
-mkdir -p "$persistenceDir"
-mkdir -p "$protocolDir"
mkdir -p "$amqpBrokerDir"
-mkdir -p "$tlsCertCollectionDir"
-mkdir -p "$localDir"
-mkdir -p "$invokersDir"
-mkdir -p "$providersDir"
-mkdir -p "$logDir"
-
-if [ -f "/etc/vmware-tools/GuestProxyData/server/cert.pem" ]; then
- cp -f "/etc/vmware-tools/GuestProxyData/server/cert.pem" "$tlsCertCollectionDir/cacert.pem"
-fi
-
-vcidPath="/etc/vmware-tools/GuestProxyData/VmVcUuid/vm.vc.uuid"
-if [ -f "$vcidPath" ]; then
- reactiveRequestAmqpQueueId=$(cat "$vcidPath")-agentId1
-else
- reactiveRequestAmqpQueueId=`uuidgen`
-fi
-
-tunnelPort=$(netstat -ldn | egrep ":6672 ")
-if [ -f "$vcidPath" -a "$tunnelPort" != "" ]; then
- brokerUri="tunnel:agentId1:bogus@localhost:6672/${reactiveRequestAmqpQueueId}"
-else
- brokerUri="amqp:#amqpUsername#:#amqpPassword#@${brokerAddr}:5672/${reactiveRequestAmqpQueueId}"
-fi
-
-echo -n "$brokerUri" > "$amqpBrokerDir/uri.txt"
-echo -n "$reactiveRequestAmqpQueueId" > "$localDir/localId.txt"
+echo -n "amqp:#amqpUsername#:#amqpPassword#@${brokerAddr}:5672/reactiveRequestAmqpQueueId" > "$amqpBrokerDir/uri_amqp.txt"
+echo -n "tunnel:agentId1:bogus@localhost:6672/reactiveRequestAmqpQueueId" > "$amqpBrokerDir/uri_tunnel.txt"
#Substitute values into config files
setupCafConfig '@installDir@' "$installDir" "$configDir"
$processPath -n
;;
"valgrindMemChecks")
- G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind -v --tool=memcheck --leak-check=full --num-callers=40 --track-origins=yes --log-file=${processPath}-valgrind-memchecks.log $processPath -n
+ G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind -v --tool=memcheck --leak-check=full --num-callers=40 --track-origins=yes --leak-resolution=med --track-fds=yes --log-file=${processPath}-valgrind-memchecks.log $processPath -n
;;
"valgrindProfiling")
valgrind --tool=callgrind --log-file=${processPath}-valgrind-profiling.log $processPath -n
$processPath -d
;;
"valgrindMemChecks")
- G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind -v --tool=memcheck --leak-check=full --num-callers=40 --log-file=${processPath}-valgrind.log $processPath -d
+ G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind -v --tool=memcheck --leak-check=full --show-leak-kinds=all --num-callers=40 --log-file=${processPath}-valgrind.log $processPath -d
;;
"valgrindProfiling")
valgrind --tool=callgrind $processPath -d