void RegistryI::setupThreadPool(const PropertiesPtr& properties, const string& name, int size, int sizeMax) { if(properties->getPropertyAsIntWithDefault(name + ".Size", 0) < size) { ostringstream os; os << size; properties->setProperty(name + ".Size", os.str()); } else { size = properties->getPropertyAsInt(name + ".Size"); } if(sizeMax > 0 && properties->getPropertyAsIntWithDefault(name + ".SizeMax", 0) < sizeMax) { if(size >= sizeMax) { sizeMax = size * 10; } ostringstream os; os << sizeMax; properties->setProperty(name + ".SizeMax", os.str()); } }
void IceSSL::SSLEngine::initialize() { const string propPrefix = "IceSSL."; const PropertiesPtr properties = communicator()->getProperties(); // // CheckCertName determines whether we compare the name in a peer's // certificate against its hostname. // _checkCertName = properties->getPropertyAsIntWithDefault(propPrefix + "CheckCertName", 0) > 0; // // VerifyDepthMax establishes the maximum length of a peer's certificate // chain, including the peer's certificate. A value of 0 means there is // no maximum. // _verifyDepthMax = properties->getPropertyAsIntWithDefault(propPrefix + "VerifyDepthMax", 3); // // VerifyPeer determines whether certificate validation failures abort a connection. // _verifyPeer = properties->getPropertyAsIntWithDefault(propPrefix + "VerifyPeer", 2); if(_verifyPeer < 0 || _verifyPeer > 2) { throw PluginInitializationException(__FILE__, __LINE__, "IceSSL: invalid value for " + propPrefix + "VerifyPeer"); } _securityTraceLevel = properties->getPropertyAsInt("IceSSL.Trace.Security"); _securityTraceCategory = "Security"; }
void MonitorAnalyzerI::reload(const Current& current) { MCE_INFO("MonitorAnalyzerI::reload"); PropertiesPtr properties = Ice::createProperties(); properties->load(CONFIG); mashineavailablememoryanalyzer_->reload(properties); mashineloadanalyzer_->reload(properties); mashinediskanalyzer_->reload(properties); }
MetricsMapI::MetricsMapI(const std::string& mapPrefix, const PropertiesPtr& properties) : _properties(properties->getPropertiesForPrefix(mapPrefix)), _retain(properties->getPropertyAsIntWithDefault(mapPrefix + "RetainDetached", 10)), _accept(parseRule(properties, mapPrefix + "Accept")), _reject(parseRule(properties, mapPrefix + "Reject")) { validateProperties(mapPrefix, properties); string groupBy = properties->getPropertyWithDefault(mapPrefix + "GroupBy", "id"); vector<string>& groupByAttributes = const_cast<vector<string>&>(_groupByAttributes); vector<string>& groupBySeparators = const_cast<vector<string>&>(_groupBySeparators); if(!groupBy.empty()) { string v; bool attribute = IceUtilInternal::isAlpha(groupBy[0]) || IceUtilInternal::isDigit(groupBy[0]); if(!attribute) { groupByAttributes.push_back(""); } for(string::const_iterator p = groupBy.begin(); p != groupBy.end(); ++p) { bool isAlphaNum = IceUtilInternal::isAlpha(*p) || IceUtilInternal::isDigit(*p) || *p == '.'; if(attribute && !isAlphaNum) { groupByAttributes.push_back(v); v = *p; attribute = false; } else if(!attribute && isAlphaNum) { groupBySeparators.push_back(v); v = *p; attribute = true; } else { v += *p; } } if(attribute) { groupByAttributes.push_back(v); } else { groupBySeparators.push_back(v); } } }
Ice::PropertiesPtr IceBox::ServiceManagerI::createServiceProperties(const string& service) { PropertiesPtr properties; PropertiesPtr communicatorProperties = _communicator->getProperties(); if(communicatorProperties->getPropertyAsInt("IceBox.InheritProperties") > 0) { properties = communicatorProperties->clone(); properties->setProperty("Ice.Admin.Endpoints", ""); // Inherit all except Ice.Admin.Endpoints! } else { properties = createProperties(); } string programName = communicatorProperties->getProperty("Ice.ProgramName"); if(programName.empty()) { properties->setProperty("Ice.ProgramName", service); } else { properties->setProperty("Ice.ProgramName", programName + "-" + service); } return properties; }
// look for ServiceNamex.TrainedModel // Note that the x is significant string ServiceManagerI::getModelFileFromConfig() { CommunicatorPtr comm = mAdapter->getCommunicator(); if ( comm ) { PropertiesPtr props = comm->getProperties(); if (props==true) { string propname = mServiceName + "x.TrainedModel"; string propval = props->getProperty( propname ); return propval; } } return ""; }
bool CPacketizer::initialize(PropertiesPtr properties) { Properties::iterator ret; ret=properties->find(std::string("hdrLength")); if (ret == properties->end()) { LOG_ERROR("hdrLength not present in config file"); return false; } else { int* hdr=boost::any_cast<int>(&(ret->second)); if (hdr == NULL) { LOG_ERROR("hdrLength not an integer value"); return false; } hdrLength_=*hdr; } #if 0 ret=(*serverDetails)->find(std::string("bodyLength")); if (ret == (*serverDetails)->end()) { LOG_ERROR("bodyLength not present in config file"); return false; } else { int* bodyLen=boost::any_cast<int>(&(ret->second)); if (bodyLen == NULL) { LOG_ERROR("bodyLength not an integer value"); return false; } bodyLength_=*bodyLen; } #endif std::ostringstream tmp; tmp << "Cpacketize initialized with header length " << hdrLength_; LOG_DEBUG(tmp.str()); return true; }
IceInternal::TraceLevels::TraceLevels(const PropertiesPtr& properties) : network(0), networkCat("Network"), protocol(0), protocolCat("Protocol"), retry(0), retryCat("Retry"), location(0), locationCat("Locator"), slicing(0), slicingCat("Slicing"), gc(0), gcCat("GC"), threadPool(0), threadPoolCat("ThreadPool") { const string keyBase = "Ice.Trace."; const_cast<int&>(network) = properties->getPropertyAsInt(keyBase + networkCat); const_cast<int&>(protocol) = properties->getPropertyAsInt(keyBase + protocolCat); const_cast<int&>(retry) = properties->getPropertyAsInt(keyBase + retryCat); const_cast<int&>(location) = properties->getPropertyAsInt(keyBase + locationCat); const_cast<int&>(slicing) = properties->getPropertyAsInt(keyBase + slicingCat); const_cast<int&>(gc) = properties->getPropertyAsInt(keyBase + gcCat); const_cast<int&>(threadPool) = properties->getPropertyAsInt(keyBase + threadPoolCat); }
int run(int, char* argv[], const CommunicatorPtr& communicator) { PropertiesPtr properties = communicator->getProperties(); const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default"; string managerProxy = properties->getProperty(managerProxyProperty); if(managerProxy.empty()) { cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl; return EXIT_FAILURE; } IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( communicator->stringToProxy(managerProxy)); if(!manager) { cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl; return EXIT_FAILURE; } TopicPrx topic; try { topic = manager->retrieve("single"); } catch(const NoSuchTopic& e) { cerr << argv[0] << ": NoSuchTopic: " << e.name << endl; return EXIT_FAILURE; } assert(topic); // // Get a publisher object, create a twoway proxy and then cast to // a Single object. // SinglePrx single = SinglePrx::uncheckedCast(topic->getPublisher()->ice_twoway()); for(int i = 0; i < 1000; ++i) { single->event(i); } return EXIT_SUCCESS; }
std::string ServiceManagerI::getDataDir() { PropertiesPtr props = mAdapter->getCommunicator()->getProperties(); getVLogger().setLocalVerbosityLevel(props->getProperty("CVAC.ServicesVerbosity")); // Load the CVAC property: 'CVAC.DataDir'. Used for the xml filename path, // and to provide a prefix to Runset paths std::string dataDir = props->getProperty("CVAC.DataDir"); if(dataDir.empty()) { localAndClientMsg(VLogger::WARN, NULL, "Unable to locate CVAC Data directory, specified: " "'CVAC.DataDir = path/to/dataDir' in config.service\n"); } localAndClientMsg(VLogger::DEBUG, NULL, "CVAC Data directory configured as: %s \n", dataDir.c_str()); return dataDir; }
IcePatch2::Patcher::Patcher(const CommunicatorPtr& communicator, const PatcherFeedbackPtr& feedback) : _feedback(feedback), _dataDir(getDataDir(communicator, ".")), _thorough(getThorough(communicator, 0) > 0), _chunkSize(getChunkSize(communicator, 100)), _remove(getRemove(communicator, 1)), _log(0) { const PropertiesPtr properties = communicator->getProperties(); const char* clientProxyProperty = "IcePatch2Client.Proxy"; std::string clientProxy = properties->getProperty(clientProxyProperty); if(clientProxy.empty()) { const char* endpointsProperty = "IcePatch2.Endpoints"; string endpoints = properties->getProperty(endpointsProperty); if(endpoints.empty()) { ostringstream os; os << "No proxy to IcePatch2 server. Please set `" << clientProxyProperty << "' or `" << endpointsProperty << "'."; throw os.str(); } ostringstream os; os << "The property " << endpointsProperty << " is deprecated, use " << clientProxyProperty << " instead."; communicator->getLogger()->warning(os.str()); Identity id; id.category = properties->getPropertyWithDefault("IcePatch2.InstanceName", "IcePatch2"); id.name = "server"; clientProxy = "\"" + communicator->identityToString(id) + "\" :" + endpoints; } ObjectPrx serverBase = communicator->stringToProxy(clientProxy); FileServerPrx server = FileServerPrx::checkedCast(serverBase); if(!server) { throw "proxy `" + clientProxy + "' is not a file server."; } init(server); }
void Analyzer::reload(const PropertiesPtr& properties) { MCE_INFO("Analyzer::reload type: " << type_); int defaultmin = properties->getPropertyAsIntWithDefault("Analyzer."+type_+".Default.Min", INT_MIN); int defaultmax = properties->getPropertyAsIntWithDefault("Analyzer."+type_+".Default.Max", INT_MAX); int defaultmoremin = properties->getPropertyAsIntWithDefault("Analyzer."+type_+".Default.MoreMin", INT_MIN); int defaultmoremax = properties->getPropertyAsIntWithDefault("Analyzer."+type_+".Default.MoreMax", INT_MAX); LimiterPtr defaulter = new Limiter(defaultmoremin, defaultmin, defaultmax, defaultmoremax); map<string, LimiterPtr> limits; PropertyDict patterns = properties->getPropertiesForPrefix("Analyzer."+type_+".Patterns"); for (PropertyDict::iterator pattern = patterns.begin(); pattern != patterns.end(); ++pattern) { vector<string> strings; boost::algorithm::split(strings, pattern->second, boost::algorithm::is_any_of(" ")); limits[strings.at(0)]=new Limiter(lexical_cast<int>(strings.at(1)),lexical_cast<int>(strings.at(2)),lexical_cast<int>(strings.at(3)),lexical_cast<int>(strings.at(4))); } { RWRecMutex::WLock lock(mutex_); limits_ = limits; default_ = defaulter; } MCE_DEBUG("Analyzer::reload done"); }
void JsonSchema::readString(cJSON *childProperties, PropertiesPtr property) { cJSON *stringMax = cJSON_GetObjectItem(childProperties, "maxLength"); if (stringMax) { cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum"); if (exclusiveMax) { if (exclusiveMax->type == cJSON_True) property->setMax (--(stringMax->valueint)); else property->setMax(stringMax->valueint); } else property->setMax(stringMax->valueint); } cJSON *stringMin = cJSON_GetObjectItem(childProperties, "minLength"); if (stringMin) { cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum"); if (exclusiveMin) { if (exclusiveMin->type == cJSON_True) property->setMin( ++(stringMin->valueint)); else property->setMin(stringMin->valueint); } else property->setMin(stringMin->valueint); } cJSON *stringFormat = cJSON_GetObjectItem(childProperties, "format"); if (stringFormat) { property->setFormat(stringFormat->valuestring); } cJSON *stringPattern = cJSON_GetObjectItem(childProperties, "pattern"); if (stringPattern) { property->setPattern(stringPattern->valuestring); } }
Glacier2::FilterManagerPtr Glacier2::FilterManager::create(const InstancePtr& instance, const string& userId, const bool allowAddUser) { PropertiesPtr props = instance->properties(); string allow = props->getProperty("Glacier2.Filter.Category.Accept"); vector<string> allowSeq; stringToSeq(allow, allowSeq); if(allowAddUser) { int addUserMode = 0; if(!props->getProperty("Glacier2.Filter.Category.AcceptUser").empty()) { addUserMode = props->getPropertyAsInt("Glacier2.Filter.Category.AcceptUser"); } if(addUserMode > 0 && !userId.empty()) { if(addUserMode == 1) { allowSeq.push_back(userId); // Add user id to allowed categories. } else if(addUserMode == 2) { allowSeq.push_back('_' + userId); // Add user id with prepended underscore to allowed categories. } } } Glacier2::StringSetIPtr categoryFilter = new Glacier2::StringSetI(allowSeq); // // TODO: refactor initialization of filters. // allow = props->getProperty("Glacier2.Filter.AdapterId.Accept"); stringToSeq(allow, allowSeq); Glacier2::StringSetIPtr adapterIdFilter = new Glacier2::StringSetI(allowSeq); // // TODO: Object id's from configurations? // IdentitySeq allowIdSeq; allow = props->getProperty("Glacier2.Filter.Identity.Accept"); stringToSeq(instance->communicator(), allow, allowIdSeq); Glacier2::IdentitySetIPtr identityFilter = new Glacier2::IdentitySetI(allowIdSeq); return new Glacier2::FilterManager(instance, categoryFilter, adapterIdFilter, identityFilter); }
void JsonSchema::readDouble(cJSON *childProperties, PropertiesPtr property) { cJSON *Max = cJSON_GetObjectItem(childProperties, "maximum"); if (Max) { cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum"); if (exclusiveMax) { if (exclusiveMax->type == cJSON_True) property->setMaxDouble( --(Max->valuedouble)); else property->setMaxDouble(Max->valuedouble); } else property->setMaxDouble(Max->valuedouble); } cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum"); if (Min) { cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum"); if (exclusiveMin) { if (exclusiveMin->type == cJSON_True) property->setMinDouble( ++(Min->valuedouble)); else property->setMinDouble(Min->valuedouble); } else property->setMinDouble(Min->valuedouble); } cJSON *multipleOf = cJSON_GetObjectItem(childProperties, "multipleOf"); if (multipleOf) { property->setMultipleOf(multipleOf->valueint); } }
IceBox::ServiceManagerI::ServiceManagerI(CommunicatorPtr communicator, int& argc, char* argv[]) : _communicator(communicator), _adminEnabled(false), _pendingStatusChanges(false), _traceServiceObserver(0) { #ifndef ICE_CPP11_MAPPING const_cast<CallbackPtr&>(_observerCompletedCB) = newCallback(this, &ServiceManagerI::observerCompleted); #endif _logger = _communicator->getLogger(); PropertiesPtr props = _communicator->getProperties(); _traceServiceObserver = props->getPropertyAsInt("IceBox.Trace.ServiceObserver"); if(props->getProperty("Ice.Admin.Enabled") == "") { _adminEnabled = props->getProperty("Ice.Admin.Endpoints") != ""; } else { _adminEnabled = props->getPropertyAsInt("Ice.Admin.Enabled") > 0; } if(_adminEnabled) { StringSeq facetSeq = props->getPropertyAsList("Ice.Admin.Facets"); if(!facetSeq.empty()) { _adminFacetFilter.insert(facetSeq.begin(), facetSeq.end()); } } for(int i = 1; i < argc; i++) { _argv.push_back(argv[i]); } }
void Ice::ObjectAdapterI::initialize(const RouterPrx& router) { if(_noConfig) { _reference = _instance->referenceFactory()->create("dummy -t", ""); return; } PropertiesPtr properties = _instance->initializationData().properties; StringSeq unknownProps; bool noProps = filterProperties(unknownProps); // // Warn about unknown object adapter properties. // if(unknownProps.size() != 0 && properties->getPropertyAsIntWithDefault("Ice.Warn.UnknownProperties", 1) > 0) { Warning out(_instance->initializationData().logger); out << "found unknown properties for object adapter `" << _name << "':"; for(unsigned int i = 0; i < unknownProps.size(); ++i) { out << "\n " << unknownProps[i]; } } try { // // Make sure named adapter has some configuration // if(router == 0 && noProps) { InitializationException ex(__FILE__, __LINE__); ex.reason = "object adapter `" + _name + "' requires configuration"; throw ex; } const_cast<string&>(_id) = properties->getProperty(_name + ".AdapterId"); const_cast<string&>(_replicaGroupId) = properties->getProperty(_name + ".ReplicaGroupId"); // // Setup a reference to be used to get the default proxy options // when creating new proxies. By default, create twoway proxies. // string proxyOptions = properties->getPropertyWithDefault(_name + ".ProxyOptions", "-t"); try { _reference = _instance->referenceFactory()->create("dummy " + proxyOptions, ""); } catch(const ProxyParseException&) { InitializationException ex(__FILE__, __LINE__); ex.reason = "invalid proxy options `" + proxyOptions + "' for object adapter `" + _name + "'"; throw ex; } int threadPoolSize = properties->getPropertyAsInt(_name + ".ThreadPool.Size"); int threadPoolSizeMax = properties->getPropertyAsInt(_name + ".ThreadPool.SizeMax"); bool hasPriority = properties->getProperty(_name + ".ThreadPool.ThreadPriority") != ""; // // Create the per-adapter thread pool, if necessary. This is done before the creation of the incoming // connection factory as the thread pool is needed during creation for the call to incFdsInUse. // if(threadPoolSize > 0 || threadPoolSizeMax > 0 || hasPriority) { _threadPool = new ThreadPool(_instance, _name + ".ThreadPool", 0); } _hasAcmTimeout = properties->getProperty(_name + ".ACM") != ""; if(_hasAcmTimeout) { _acmTimeout = properties->getPropertyAsInt(_name + ".ACM"); _instance->connectionMonitor()->checkIntervalForACM(_acmTimeout); } if(!router) { const_cast<RouterPrx&>(router) = RouterPrx::uncheckedCast( _instance->proxyFactory()->propertyToProxy(_name + ".Router")); } if(router) { _routerInfo = _instance->routerManager()->get(router); if(_routerInfo) { // // Make sure this router is not already registered with another adapter. // if(_routerInfo->getAdapter()) { throw AlreadyRegisteredException(__FILE__, __LINE__, "object adapter with router", _instance->identityToString(router->ice_getIdentity())); } // // Add the router's server proxy endpoints to this object // adapter. // vector<EndpointIPtr> endpoints = _routerInfo->getServerEndpoints(); copy(endpoints.begin(), endpoints.end(), back_inserter(_routerEndpoints)); sort(_routerEndpoints.begin(), _routerEndpoints.end()); // Must be sorted. _routerEndpoints.erase(unique(_routerEndpoints.begin(), _routerEndpoints.end()), _routerEndpoints.end()); // // Associate this object adapter with the router. This way, // new outgoing connections to the router's client proxy will // use this object adapter for callbacks. // _routerInfo->setAdapter(this); // // Also modify all existing outgoing connections to the // router's client proxy to use this object adapter for // callbacks. // _instance->outgoingConnectionFactory()->setRouterInfo(_routerInfo); } } else { // // Parse the endpoints, but don't store them in the adapter. // The connection factory might change it, for example, to // fill in the real port number. // vector<EndpointIPtr> endpoints = parseEndpoints(properties->getProperty(_name + ".Endpoints"), true); for(vector<EndpointIPtr>::iterator p = endpoints.begin(); p != endpoints.end(); ++p) { IncomingConnectionFactoryPtr factory = new IncomingConnectionFactory(_instance, *p, this); factory->initialize(_name); _incomingConnectionFactories.push_back(factory); } if(endpoints.empty()) { TraceLevelsPtr tl = _instance->traceLevels(); if(tl->network >= 2) { Trace out(_instance->initializationData().logger, tl->networkCat); out << "created adapter `" << _name << "' without endpoints"; } } // // Parse the published endpoints. // _publishedEndpoints = parsePublishedEndpoints(); } if(!properties->getProperty(_name + ".Locator").empty()) { setLocator(LocatorPrx::uncheckedCast(_instance->proxyFactory()->propertyToProxy(_name + ".Locator"))); } else { setLocator(_instance->referenceFactory()->getDefaultLocator()); } } catch(...) { destroy(); throw; } }
void Ice::ObjectAdapterI::activate() { LocatorInfoPtr locatorInfo; bool registerProcess = false; bool printAdapterReady = false; { IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(*this); checkForDeactivation(); // // If some threads are waiting on waitForHold(), we set this // flag to ensure the threads will start again the wait for // all the incoming connection factories. // _waitForHoldRetry = _waitForHold > 0; // // If the one off initializations of the adapter are already // done, we just need to activate the incoming connection // factories and we're done. // if(_activateOneOffDone) { for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), Ice::voidMemFun(&IncomingConnectionFactory::activate)); return; } // // One off initializations of the adapter: update the locator // registry and print the "adapter ready" message. We set the // _waitForActivate flag to prevent deactivation from other // threads while these one off initializations are done. // _waitForActivate = true; locatorInfo = _locatorInfo; if(!_noConfig) { PropertiesPtr properties = _instance->initializationData().properties; printAdapterReady = properties->getPropertyAsInt("Ice.PrintAdapterReady") > 0; registerProcess = properties->getPropertyAsInt(_name + ".RegisterProcess") > 0; } } try { Ice::Identity dummy; dummy.name = "dummy"; updateLocatorRegistry(locatorInfo, createDirectProxy(dummy), registerProcess); } catch(const Ice::LocalException&) { // // If we couldn't update the locator registry, we let the // exception go through and don't activate the adapter to // allow to user code to retry activating the adapter // later. // { IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(*this); _waitForActivate = false; notifyAll(); } throw; } if(printAdapterReady) { cout << _name << " ready" << endl; } { IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(*this); assert(!_deactivated); // Not possible if _waitForActivate = true; // // Signal threads waiting for the activation. // _waitForActivate = false; notifyAll(); _activateOneOffDone = true; for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), Ice::voidMemFun(&IncomingConnectionFactory::activate)); } }
int run(int, char* argv[], const CommunicatorPtr& communicator) { PropertiesPtr properties = communicator->getProperties(); const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default"; string managerProxy = properties->getProperty(managerProxyProperty); if(managerProxy.empty()) { cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl; return EXIT_FAILURE; } ObjectPrx base = communicator->stringToProxy(managerProxy); IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); if(!manager) { cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl; return EXIT_FAILURE; } TopicPrx fed1; try { fed1 = manager->retrieve("fed1"); } catch(const NoSuchTopic& e) { cerr << argv[0] << ": NoSuchTopic: " << e.name << endl; return EXIT_FAILURE; } TopicPrx fed2; try { fed2 = manager->retrieve("fed2"); } catch(const NoSuchTopic& e) { cerr << argv[0] << ": NoSuchTopic: " << e.name << endl; return EXIT_FAILURE; } TopicPrx fed3; try { fed3 = manager->retrieve("fed3"); } catch(const NoSuchTopic& e) { cerr << argv[0] << ": NoSuchTopic: " << e.name << endl; return EXIT_FAILURE; } EventPrx eventFed1 = EventPrx::uncheckedCast(fed1->getPublisher()->ice_oneway()); EventPrx eventFed2 = EventPrx::uncheckedCast(fed2->getPublisher()->ice_oneway()); EventPrx eventFed3 = EventPrx::uncheckedCast(fed3->getPublisher()->ice_oneway()); Ice::Context context; int i; context["cost"] = "0"; for(i = 0; i < 10; ++i) { eventFed1->pub("fed1:0", context); } context["cost"] = "10"; for(i = 0; i < 10; ++i) { eventFed1->pub("fed1:10", context); } context["cost"] = "15"; for(i = 0; i < 10; ++i) { eventFed1->pub("fed1:15", context); } context["cost"] = "0"; for(i = 0; i < 10; ++i) { eventFed2->pub("fed2:0", context); } context["cost"] = "5"; for(i = 0; i < 10; ++i) { eventFed2->pub("fed2:5", context); } context["cost"] = "0"; for(i = 0; i < 10; ++i) { eventFed3->pub("fed3:0", context); } // // Before we exit, we ping all proxies as twoway, to make sure // that all oneways are delivered. // EventPrx::uncheckedCast(eventFed1->ice_twoway())->ice_ping(); EventPrx::uncheckedCast(eventFed2->ice_twoway())->ice_ping(); EventPrx::uncheckedCast(eventFed3->ice_twoway())->ice_ping(); return EXIT_SUCCESS; }
bowCV* BowICETrainI::initialize( TrainerCallbackHandlerPrx& _callback, const TrainerProperties &tprops, DetectorDataArchive& dda, const Current& current ) { // Set CVAC verbosity according to ICE properties PropertiesPtr iceprops = (current.adapter->getCommunicator()->getProperties()); string verbStr = iceprops->getProperty("CVAC.ServicesVerbosity"); if (!verbStr.empty()) { vLogger.setLocalVerbosityLevel( verbStr ); } // defaults //SURF, SIFT, FAST, STAR, MSER, GFTT, HARRIS string _nameFeature("SIFT"); //SURF, SIFT, OpponentSIFT, OpponentSURF string _nameDescriptor("SIFT"); //BruteForce-L1, BruteForce, FlannBased string _nameMatcher("BruteForce-L1"); int _countWords = 150; // read properties; need to cast const away cvac::Properties& trp = (cvac::Properties&) tprops.props; const string& nf = trp[bowCV::BOW_DETECTOR_NAME]; if (!nf.empty()) { _nameFeature = nf; localAndClientMsg(VLogger::DEBUG, _callback, "Set FeatureType to %s\n", nf.c_str() ); } const string& nd = trp[bowCV::BOW_EXTRACTOR_NAME]; if (!nd.empty()) { _nameDescriptor = nd; localAndClientMsg(VLogger::DEBUG, _callback, "Set DescriptorType to %s\n", nd.c_str() ); } const string& nm = trp[bowCV::BOW_MATCHER_NAME]; if (!nm.empty()) { _nameMatcher = nm; localAndClientMsg(VLogger::DEBUG, _callback, "Set MatcherType to %s\n", nm.c_str() ); } const string& nw = trp["NumWords"]; if (!nw.empty()) { errno=0; long int cw = (int) strtol( nw.c_str(), (char**) NULL, 10 ); if (cw>0 && cw<INT_MAX && errno==0) { // no error, successfully parsed int from NumWords property _countWords = cw; localAndClientMsg(VLogger::DEBUG, _callback, "Number of words set to %d\n", cw ); } } // figure out how to handle Negative purpose samples, if any const string& strategy = trp[bowCV::BOW_REJECT_CLASS_STRATEGY]; if (!strategy.empty()) { std::string strat = strategy; std::transform( strategy.begin(), strategy.end(), strat.begin(), ::tolower ); rejectClassStrategy = bowCV::BOW_REJECT_CLASS_AS_MULTICLASS; if (0==strat.compare(bowCV::BOW_REJECT_CLASS_IGNORE_SAMPLES)) { rejectClassStrategy = bowCV::BOW_REJECT_CLASS_IGNORE_SAMPLES; localAndClientMsg(VLogger::DEBUG, _callback, "BOW will ignore any samples with Negative purpose\n"); } else if (0==strat.compare(bowCV::BOW_REJECT_CLASS_AS_MULTICLASS)) { rejectClassStrategy = bowCV::BOW_REJECT_CLASS_AS_MULTICLASS; localAndClientMsg(VLogger::DEBUG, _callback, "BOW will treat samples with Negative purpose as a separate class\n"); } else if (0==strat.compare(bowCV::BOW_REJECT_CLASS_AS_FIRST_STAGE)) { rejectClassStrategy = bowCV::BOW_REJECT_CLASS_AS_FIRST_STAGE; localAndClientMsg(VLogger::DEBUG, _callback, "BOW will create a two-stage classifier: reject first, multiclass second\n"); localAndClientMsg(VLogger::ERROR, _callback, "BOW two-stage classifier is not implemented yet\n"); return false; } else { localAndClientMsg(VLogger::WARN, _callback, "Incorrect specifier for %s property, using default (%s).\n", bowCV::BOW_REJECT_CLASS_STRATEGY.c_str(), rejectClassStrategy.c_str() ); } } bowCV* pBowCV = new bowCV(this); bool fInitialized = pBowCV->train_initialize(_nameFeature,_nameDescriptor,_nameMatcher,_countWords, &dda); if (fInitialized) { return pBowCV; } else { return NULL; } }
void BowICETrainI::process(const Identity &client,const ::RunSet& runset, const TrainerProperties &tprops, const Current& current) { localAndClientMsg(VLogger::DEBUG, NULL, "starting BOW training process\n"); callbackPtr = TrainerCallbackHandlerPrx::uncheckedCast( current.con->createProxy(client)->ice_oneway()); localAndClientMsg( VLogger::DEBUG_2, callbackPtr, "starting BOW training process, got callback pointer\n"); PropertiesPtr props = (current.adapter->getCommunicator()->getProperties()); std::string CVAC_DataDir = props->getProperty("CVAC.DataDir"); // argument error checking: any data? consistent multiclass or pos/neg purpose? if (!checkPurposedLists( runset.purposedLists, callbackPtr )) return; DetectorDataArchive dda; bowCV* pBowCV = initialize(callbackPtr, tprops, dda, current); if ( NULL==pBowCV ) { localAndClientMsg(VLogger::ERROR, callbackPtr, "Trainer not initialized, aborting.\n"); return; } // Ingest the data for processing, one purposed list at a time. // Also, determine if the classIDs match nicely to the labels; // if so, add appropriate annotations into the trained model file. LabelMap labelmap; bool labelsMatch = true; for (size_t listidx = 0; listidx < runset.purposedLists.size(); listidx++) { processPurposedList( runset.purposedLists[listidx], pBowCV, callbackPtr, CVAC_DataDir, labelmap, &labelsMatch ); } if ( !labelsMatch ) labelmap.clear(); if ( !hasUniqueLabels(labelmap) ) labelmap.clear(); // create a sandbox for this client std::string connectName = cvac::getClientConnectionName(current); std::string clientName = mServiceMan->getSandbox()->createClientName( mServiceMan->getServiceName(), connectName); std::string tTempDir = mServiceMan->getSandbox()->createTrainingDir(clientName); // TODO: when should this tTempDir be deleted? localAndClientMsg(VLogger::INFO, callbackPtr, "Starting actual training procedure...\n"); // Tell ServiceManager that we will listen for stop mServiceMan->setStoppable(); // // run the actual training procedure on the previously ingested data; // this sets the pBowCV to point to files that it created, // and it adds some properties directly to the DDA // bool fTrain = pBowCV->train_run(tTempDir, mServiceMan); // Tell ServiceManager that we are done listening for stop mServiceMan->clearStop(); if(!fTrain) { deleteDirectory(tTempDir); localAndClientMsg(VLogger::ERROR, callbackPtr, "Error during the training of BoW.\n"); return; } // create the archive of the trained model FilePath trainedModel = createArchive( dda, pBowCV, labelmap, clientName, CVAC_DataDir, tTempDir ); callbackPtr->createdDetector(trainedModel); delete pBowCV; pBowCV = NULL; localAndClientMsg(VLogger::INFO, callbackPtr, "Training procedure completed.\n"); }
IceInternal::ThreadPool::ThreadPool(const InstancePtr& instance, const string& prefix, int timeout) : _instance(instance), _dispatcher(_instance->initializationData().dispatcher), _destroyed(false), _prefix(prefix), _selector(instance), _nextThreadId(0), _size(0), _sizeIO(0), _sizeMax(0), _sizeWarn(0), _serialize(_instance->initializationData().properties->getPropertyAsInt(_prefix + ".Serialize") > 0), _hasPriority(false), _priority(0), _serverIdleTime(timeout), _threadIdleTime(0), _stackSize(0), _inUse(0), #if !defined(ICE_USE_IOCP) && !defined(ICE_OS_WINRT) _inUseIO(0), _nextHandler(_handlers.end()), #endif _promote(true) { PropertiesPtr properties = _instance->initializationData().properties; #ifndef ICE_OS_WINRT # ifdef _WIN32 SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); int nProcessors = sysInfo.dwNumberOfProcessors; # else int nProcessors = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN)); # endif #endif // // We use just one thread as the default. This is the fastest // possible setting, still allows one level of nesting, and // doesn't require to make the servants thread safe. // int size = properties->getPropertyAsIntWithDefault(_prefix + ".Size", 1); if(size < 1) { Warning out(_instance->initializationData().logger); out << _prefix << ".Size < 1; Size adjusted to 1"; size = 1; } int sizeMax = properties->getPropertyAsIntWithDefault(_prefix + ".SizeMax", size); #ifndef ICE_OS_WINRT if(sizeMax == -1) { sizeMax = nProcessors; } #endif if(sizeMax < size) { Warning out(_instance->initializationData().logger); out << _prefix << ".SizeMax < " << _prefix << ".Size; SizeMax adjusted to Size (" << size << ")"; sizeMax = size; } int sizeWarn = properties->getPropertyAsInt(_prefix + ".SizeWarn"); if(sizeWarn != 0 && sizeWarn < size) { Warning out(_instance->initializationData().logger); out << _prefix << ".SizeWarn < " << _prefix << ".Size; adjusted SizeWarn to Size (" << size << ")"; sizeWarn = size; } else if(sizeWarn > sizeMax) { Warning out(_instance->initializationData().logger); out << _prefix << ".SizeWarn > " << _prefix << ".SizeMax; adjusted SizeWarn to SizeMax (" << sizeMax << ")"; sizeWarn = sizeMax; } int threadIdleTime = properties->getPropertyAsIntWithDefault(_prefix + ".ThreadIdleTime", 60); if(threadIdleTime < 0) { Warning out(_instance->initializationData().logger); out << _prefix << ".ThreadIdleTime < 0; ThreadIdleTime adjusted to 0"; threadIdleTime = 0; } const_cast<int&>(_size) = size; const_cast<int&>(_sizeMax) = sizeMax; const_cast<int&>(_sizeWarn) = sizeWarn; #ifndef ICE_OS_WINRT const_cast<int&>(_sizeIO) = min(sizeMax, nProcessors); #else const_cast<int&>(_sizeIO) = sizeMax; #endif const_cast<int&>(_threadIdleTime) = threadIdleTime; #ifdef ICE_USE_IOCP _selector.setup(_sizeIO); #endif int stackSize = properties->getPropertyAsInt(_prefix + ".StackSize"); if(stackSize < 0) { Warning out(_instance->initializationData().logger); out << _prefix << ".StackSize < 0; Size adjusted to OS default"; stackSize = 0; } const_cast<size_t&>(_stackSize) = static_cast<size_t>(stackSize); const_cast<bool&>(_hasPriority) = properties->getProperty(_prefix + ".ThreadPriority") != ""; const_cast<int&>(_priority) = properties->getPropertyAsInt(_prefix + ".ThreadPriority"); if(!_hasPriority) { const_cast<bool&>(_hasPriority) = properties->getProperty("Ice.ThreadPriority") != ""; const_cast<int&>(_priority) = properties->getPropertyAsInt("Ice.ThreadPriority"); } _workQueue = new ThreadPoolWorkQueue(_instance, _selector); if(_instance->traceLevels()->threadPool >= 1) { Trace out(_instance->initializationData().logger, _instance->traceLevels()->threadPoolCat); out << "creating " << _prefix << ": Size = " << _size << ", SizeMax = " << _sizeMax << ", SizeWarn = " << _sizeWarn; } __setNoDelete(true); try { for(int i = 0 ; i < _size ; ++i) { EventHandlerThreadPtr thread = new EventHandlerThread(this, nextThreadId()); if(_hasPriority) { thread->start(_stackSize, _priority); } else { thread->start(_stackSize); } _threads.insert(thread); } } catch(const IceUtil::Exception& ex) { { Error out(_instance->initializationData().logger); out << "cannot create thread for `" << _prefix << "':\n" << ex; } destroy(); joinWithAllThreads(); __setNoDelete(false); throw; } catch(...) { __setNoDelete(false); throw; } __setNoDelete(false); }
Ice::ObjectAdapterI::ObjectAdapterI(const InstancePtr& instance, const CommunicatorPtr& communicator, const ObjectAdapterFactoryPtr& objectAdapterFactory, const string& name, const string& endpointInfo, const RouterPrx& router, bool noConfig) : _deactivated(false), _instance(instance), _communicator(communicator), _objectAdapterFactory(objectAdapterFactory), _servantManager(new ServantManager(instance, name)), _activateOneOffDone(false), _name(name), _directCount(0), _waitForActivate(false), _destroying(false), _destroyed(false), _noConfig(noConfig), _threadPerConnection(false), _threadPerConnectionStackSize(0) { if(_noConfig) { return; } PropertiesPtr properties = instance->initializationData().properties; StringSeq unknownProps; bool noProps = filterProperties(unknownProps); // // Warn about unknown object adapter properties. // if(unknownProps.size() != 0 && properties->getPropertyAsIntWithDefault("Ice.Warn.UnknownProperties", 1) > 0) { Warning out(_instance->initializationData().logger); out << "found unknown properties for object adapter '" << _name << "':"; for(unsigned int i = 0; i < unknownProps.size(); ++i) { out << "\n " << unknownProps[i]; } } // // Make sure named adapter has some configuration // if(endpointInfo.empty() && router == 0 && noProps) { InitializationException ex(__FILE__, __LINE__); ex.reason = "object adapter \"" + _name + "\" requires configuration."; throw ex; } const_cast<string&>(_id) = properties->getProperty(_name + ".AdapterId"); const_cast<string&>(_replicaGroupId) = properties->getProperty(_name + ".ReplicaGroupId"); __setNoDelete(true); try { _threadPerConnection = properties->getPropertyAsInt(_name + ".ThreadPerConnection") > 0; int threadPoolSize = properties->getPropertyAsInt(_name + ".ThreadPool.Size"); int threadPoolSizeMax = properties->getPropertyAsInt(_name + ".ThreadPool.SizeMax"); if(_threadPerConnection && (threadPoolSize > 0 || threadPoolSizeMax > 0)) { InitializationException ex(__FILE__, __LINE__); ex.reason = "object adapter \"" + _name + "\" cannot be configured for both\n" "thread pool and thread per connection"; throw ex; } if(!_threadPerConnection && threadPoolSize == 0 && threadPoolSizeMax == 0) { _threadPerConnection = _instance->threadPerConnection(); } if(_threadPerConnection) { int stackSize = properties->getPropertyAsIntWithDefault(_name + ".ThreadPerConnection.StackSize", static_cast<Int>(_instance->threadPerConnectionStackSize())); if(stackSize < 0) { stackSize = 0; } _threadPerConnectionStackSize = stackSize; } // // Create the per-adapter thread pool, if necessary. This is done before the creation of the incoming // connection factory as the thread pool is needed during creation for the call to incFdsInUse. // if(threadPoolSize > 0 || threadPoolSizeMax > 0) { _threadPool = new ThreadPool(_instance, _name + ".ThreadPool", 0); } if(!router) { const_cast<RouterPrx&>(router) = RouterPrx::uncheckedCast( _instance->proxyFactory()->propertyToProxy(_name + ".Router")); } if(router) { _routerInfo = _instance->routerManager()->get(router); if(_routerInfo) { // // Make sure this router is not already registered with another adapter. // if(_routerInfo->getAdapter()) { throw AlreadyRegisteredException(__FILE__, __LINE__, "object adapter with router", _instance->identityToString(router->ice_getIdentity())); } // // Add the router's server proxy endpoints to this object // adapter. // vector<EndpointIPtr> endpoints = _routerInfo->getServerEndpoints(); copy(endpoints.begin(), endpoints.end(), back_inserter(_routerEndpoints)); sort(_routerEndpoints.begin(), _routerEndpoints.end()); // Must be sorted. _routerEndpoints.erase(unique(_routerEndpoints.begin(), _routerEndpoints.end()), _routerEndpoints.end()); // // Associate this object adapter with the router. This way, // new outgoing connections to the router's client proxy will // use this object adapter for callbacks. // _routerInfo->setAdapter(this); // // Also modify all existing outgoing connections to the // router's client proxy to use this object adapter for // callbacks. // _instance->outgoingConnectionFactory()->setRouterInfo(_routerInfo); } } else { // // Parse the endpoints, but don't store them in the adapter. // The connection factory might change it, for example, to // fill in the real port number. // vector<EndpointIPtr> endpoints; if(endpointInfo.empty()) { endpoints = parseEndpoints(properties->getProperty(_name + ".Endpoints")); } else { endpoints = parseEndpoints(endpointInfo); } for(vector<EndpointIPtr>::iterator p = endpoints.begin(); p != endpoints.end(); ++p) { _incomingConnectionFactories.push_back(new IncomingConnectionFactory(instance, *p, this, _name)); } if(endpoints.empty()) { TraceLevelsPtr tl = _instance->traceLevels(); if(tl->network >= 2) { Trace out(_instance->initializationData().logger, tl->networkCat); out << "created adapter `" << name << "' without endpoints"; } } // // Parse published endpoints. If set, these are used in proxies // instead of the connection factory endpoints. // string endpts = properties->getProperty(_name + ".PublishedEndpoints"); _publishedEndpoints = parseEndpoints(endpts); if(_publishedEndpoints.empty()) { transform(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), back_inserter(_publishedEndpoints), Ice::constMemFun(&IncomingConnectionFactory::endpoint)); } // // Filter out any endpoints that are not meant to be published. // _publishedEndpoints.erase(remove_if(_publishedEndpoints.begin(), _publishedEndpoints.end(), not1(Ice::constMemFun(&EndpointI::publish))), _publishedEndpoints.end()); } if(!properties->getProperty(_name + ".Locator").empty()) { setLocator(LocatorPrx::uncheckedCast(_instance->proxyFactory()->propertyToProxy(_name + ".Locator"))); } else { setLocator(_instance->referenceFactory()->getDefaultLocator()); } } catch(...) { destroy(); __setNoDelete(false); throw; } __setNoDelete(false); }
{ instanceName = opts.optArg("instanceName"); } int port = communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.Port"); if(!opts.optArg("port").empty()) { istringstream is(opts.optArg("port")); if(!(is >> port)) { cerr << _appName << ": given port number is not a numeric value" << endl; return EXIT_FAILURE; } } PropertiesPtr properties = communicator()->getProperties(); string replica = properties->getProperty("IceGridAdmin.Replica"); if(!opts.optArg("replica").empty()) { replica = opts.optArg("replica"); } Glacier2::RouterPrx router; AdminSessionPrx session; SessionKeepAliveThreadPtr keepAlive; int status = EXIT_SUCCESS; try { int sessionTimeout; int acmTimeout = 0; if(!communicator()->getDefaultLocator() && !communicator()->getDefaultRouter())
void IceServiceInstaller::install(const PropertiesPtr& properties) { _debug = properties->getPropertyAsInt("Debug") != 0; initializeSid(properties->getPropertyWithDefault("ObjectName", "NT Authority\\LocalService")); const string defaultDisplayName[] = { "IceGrid registry (" + _icegridInstanceName + ")", "IceGrid node (" + _nodeName + " within " + _icegridInstanceName + ")", "Glacier2 router (" + _glacier2InstanceName + ")" }; const string defaultDescription[] = { "Location and deployment service for Ice applications", "Starts and monitors Ice servers", "Ice Firewall traversal service" }; string displayName = properties->getPropertyWithDefault("DisplayName", defaultDisplayName[_serviceType]); string description = properties->getPropertyWithDefault("Description", defaultDescription[_serviceType]); string imagePath = properties->getProperty("ImagePath"); if(imagePath == "") { char buffer[MAX_PATH]; DWORD size = GetModuleFileName(0, buffer, MAX_PATH); if(size == 0) { throw "Can't get full path to self: " + IceUtilInternal::errorToString(GetLastError()); } imagePath = string(buffer, size); imagePath.replace(imagePath.rfind('\\'), string::npos, "\\" + serviceTypeToLowerString(_serviceType) + ".exe"); } else { imagePath = fixDirSeparator(imagePath); } if(!fileExists(imagePath)) { throw imagePath + ": not found"; } string dependency; if(_serviceType == icegridregistry) { if(properties->getPropertyAsInt("DependOnRegistry") != 0) { throw "The IceGrid registry service can't depend on itself"; } string registryDataDir = fixDirSeparator(_serviceProperties->getProperty("IceGrid.Registry.Data")); if(registryDataDir == "") { throw "IceGrid.Registry.Data must be set in " + _configFile; } if(!IceUtilInternal::isAbsolutePath(registryDataDir)) { throw "'" + registryDataDir + "' is a relative path; IceGrid.Registry.Data must be an absolute path"; } if(!mkdir(registryDataDir)) { grantPermissions(registryDataDir, SE_FILE_OBJECT, true, true); } } else if(_serviceType == icegridnode) { string nodeDataDir = fixDirSeparator(_serviceProperties->getProperty("IceGrid.Node.Data")); if(nodeDataDir == "") { throw "IceGrid.Node.Data must be set in " + _configFile; } if(!IceUtilInternal::isAbsolutePath(nodeDataDir)) { throw "'" + nodeDataDir + "' is a relative path; IceGrid.Node.Data must be an absolute path"; } if(!mkdir(nodeDataDir)) { grantPermissions(nodeDataDir, SE_FILE_OBJECT, true, true); } grantPermissions("MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib", SE_REGISTRY_KEY, true); if(properties->getPropertyAsInt("DependOnRegistry") != 0) { dependency = "icegridregistry." + _icegridInstanceName; } } else if(_serviceType == glacier2router) { if(properties->getPropertyAsInt("DependOnRegistry") != 0) { if(_icegridInstanceName == "") { throw "Ice.Default.Locator must be set in " + _configFile + " when DependOnRegistry is not zero"; } dependency = "icegridregistry." + _icegridInstanceName; } } if(!_configFile.find("HKLM\\") == 0) { grantPermissions(_configFile); } string eventLog = properties->getProperty("EventLog"); if(eventLog == "") { eventLog = "Application"; } else { addLog(eventLog); } string eventLogSource = _serviceProperties->getPropertyWithDefault("Ice.EventLog.Source", _serviceName); addSource(eventLogSource, eventLog, getIceDLLPath(imagePath)); SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS); if(scm == 0) { DWORD res = GetLastError(); throw "Cannot open SCM: " + IceUtilInternal::errorToString(res); } string deps = dependency; if(deps.empty()) { const string candidates[] = { "netprofm", "Nla" }; const int candidatesLen = 2; for(int i = 0; i < candidatesLen; ++i) { SC_HANDLE service = OpenService(scm, candidates[i].c_str(), GENERIC_READ); if(service != 0) { deps = candidates[i]; CloseServiceHandle(service); break; // for } } } deps += '\0'; // must be double-null terminated string command = "\"" + imagePath + "\" --service " + _serviceName + " --Ice.Config=\""; // // Get the full path of config file. // if(!_configFile.find("HKLM\\") == 0) { char fullPath[MAX_PATH]; if(GetFullPathName(_configFile.c_str(), MAX_PATH, fullPath, 0) > MAX_PATH) { throw "Could not compute the full path of " + _configFile; } command += string(fullPath) + "\""; } else { command += _configFile + "\""; } bool autoStart = properties->getPropertyAsIntWithDefault("AutoStart", 1) != 0; string password = properties->getProperty("Password"); SC_HANDLE service = CreateServiceW( scm, IceUtil::stringToWstring(_serviceName).c_str(), IceUtil::stringToWstring(displayName).c_str(), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, autoStart ? SERVICE_AUTO_START : SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, IceUtil::stringToWstring(command).c_str(), 0, 0, IceUtil::stringToWstring(deps).c_str(), IceUtil::stringToWstring(_sidName).c_str(), IceUtil::stringToWstring(password).c_str()); if(service == 0) { DWORD res = GetLastError(); CloseServiceHandle(scm); throw "Cannot create service" + _serviceName + ": " + IceUtilInternal::errorToString(res); } // // Set description // wstring uDescription = IceUtil::stringToWstring(description); SERVICE_DESCRIPTIONW sd = { const_cast<wchar_t*>(uDescription.c_str()) }; if(!ChangeServiceConfig2W(service, SERVICE_CONFIG_DESCRIPTION, &sd)) { DWORD res = GetLastError(); CloseServiceHandle(scm); CloseServiceHandle(service); throw "Cannot set description for service" + _serviceName + ": " + IceUtilInternal::errorToString(res); } CloseServiceHandle(scm); CloseServiceHandle(service); }
int run(int argc, char* argv[], const CommunicatorPtr& communicator) { IceUtilInternal::Options opts; opts.addOpt("", "count", IceUtilInternal::Options::NeedArg); try { opts.parse(argc, (const char**)argv); } catch(const IceUtilInternal::BadOptException& e) { cerr << argv[0] << ": " << e.reason << endl; return EXIT_FAILURE; } PropertiesPtr properties = communicator->getProperties(); const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default"; string managerProxy = properties->getProperty(managerProxyProperty); if(managerProxy.empty()) { cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl; return EXIT_FAILURE; } ObjectPrx base = communicator->stringToProxy(managerProxy); IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); if(!manager) { cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl; return EXIT_FAILURE; } TopicPrx fed1; try { fed1 = manager->retrieve("fed1"); } catch(const NoSuchTopic& e) { cerr << argv[0] << ": NoSuchTopic: " << e.name << endl; return EXIT_FAILURE; } EventPrx eventFed1 = EventPrx::uncheckedCast(fed1->getPublisher()->ice_oneway()); string arg = opts.optArg("count"); int count = 1; if(arg.empty()) { count = atoi(arg.c_str()); } while(true) { for(int i = 0; i < 10; ++i) { eventFed1->pub("fed1"); } // // Before we exit, we ping all proxies as twoway, to make sure // that all oneways are delivered. // EventPrx::uncheckedCast(eventFed1->ice_twoway())->ice_ping(); if(count == 0) { break; } --count; IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1)); } return EXIT_SUCCESS; }
Ice::ObjectAdapter::ObjectAdapter(const InstancePtr& instance, const CommunicatorPtr& communicator, const ObjectAdapterFactoryPtr& objectAdapterFactory, const string& name, const string& endpointInfo, #ifdef ICEE_HAS_ROUTER const RouterPrx& router, #endif bool noConfig) : _deactivated(false), _instance(instance), _communicator(communicator), _objectAdapterFactory(objectAdapterFactory), _servantManager(new ServantManager(instance, name)), _activateOneOffDone(false), _name(name), #ifdef ICEE_HAS_LOCATOR _id(instance->initializationData().properties->getProperty(name + ".AdapterId")), _replicaGroupId(instance->initializationData().properties->getProperty(name + ".ReplicaGroupId")), #endif _waitForActivate(false), _destroying(false), _destroyed(false), _noConfig(noConfig) { if(_noConfig) { _reference = _instance->referenceFactory()->create("dummy -t", ""); return; } PropertiesPtr properties = instance->initializationData().properties; // // Setup a reference to be used to get the default proxy options // when creating new proxies. By default, create twoway proxies. // string proxyOptions = properties->getPropertyWithDefault(_name + ".ProxyOptions", "-t"); try { _reference = _instance->referenceFactory()->create("dummy " + proxyOptions, ""); } catch(const ProxyParseException&) { InitializationException ex(__FILE__, __LINE__); ex.reason = "invalid proxy options `" + proxyOptions + "' for object adapter `" + _name + "'"; throw ex; } __setNoDelete(true); try { #ifdef ICEE_HAS_ROUTER if(!router) { string routerStr = _instance->initializationData().properties->getProperty(_name + ".Router"); if(!routerStr.empty()) { const_cast<RouterPrx&>(router) = RouterPrx::uncheckedCast(_instance->proxyFactory()->stringToProxy(routerStr)); } } if(router) { _routerInfo = _instance->routerManager()->get(router); if(_routerInfo) { // // Make sure this router is not already registered with another adapter. // if(_routerInfo->getAdapter()) { throw AlreadyRegisteredException(__FILE__, __LINE__, "object adapter with router", _instance->identityToString(router->ice_getIdentity())); } // // Add the router's server proxy endpoints to this object // adapter. // vector<EndpointPtr> endpoints = _routerInfo->getServerEndpoints(); copy(endpoints.begin(), endpoints.end(), back_inserter(_routerEndpoints)); sort(_routerEndpoints.begin(), _routerEndpoints.end()); // Must be sorted. _routerEndpoints.erase(unique(_routerEndpoints.begin(), _routerEndpoints.end()), _routerEndpoints.end()); // // Associate this object adapter with the router. This way, // new outgoing connections to the router's client proxy will // use this object adapter for callbacks. // _routerInfo->setAdapter(this); // // Also modify all existing outgoing connections to the // router's client proxy to use this object adapter for // callbacks. // _instance->outgoingConnectionFactory()->setRouterInfo(_routerInfo); } } else #endif { // // Parse the endpoints, but don't store them in the adapter. // The connection factory might change it, for example, to // fill in the real port number. // vector<EndpointPtr> endpoints; if(endpointInfo.empty()) { endpoints = parseEndpoints(_instance->initializationData().properties->getProperty(_name + ".Endpoints"), true); } else { endpoints = parseEndpoints(endpointInfo, true); } for(vector<EndpointPtr>::iterator p = endpoints.begin(); p != endpoints.end(); ++p) { _incomingConnectionFactories.push_back(new IncomingConnectionFactory(_instance, *p, this)); } if(endpoints.empty()) { TraceLevelsPtr tl = _instance->traceLevels(); if(tl->network >= 2) { Trace out(_instance->initializationData().logger, tl->networkCat); out << "created adapter `" << name << "' without endpoints"; } } // // Parse published endpoints. // _publishedEndpoints = parsePublishedEndpoints(); } #ifdef ICEE_HAS_LOCATOR string locator = _instance->initializationData().properties->getProperty(_name + ".Locator"); if(!locator.empty()) { setLocator(LocatorPrx::uncheckedCast(_instance->proxyFactory()->stringToProxy(locator))); } else { setLocator(_instance->referenceFactory()->getDefaultLocator()); } #endif } catch(...) { // // There's no need to remove the adapter from the factory if // creation fails. Furthermore, since this code is called with // the factory mutex locked, we can't call removeObjectAdapter // on the factory here so we clear the factory reference to // ensure it won't be called by destroy(). // _objectAdapterFactory = 0; destroy(); __setNoDelete(false); throw; } __setNoDelete(false); }
bool IceBox::ServiceManagerI::start() { try { ServiceManagerPtr obj = this; PropertiesPtr properties = _communicator->getProperties(); // // Create an object adapter. Services probably should NOT share // this object adapter, as the endpoint(s) for this object adapter // will most likely need to be firewalled for security reasons. // ObjectAdapterPtr adapter; if(properties->getProperty("IceBox.ServiceManager.Endpoints") != "") { adapter = _communicator->createObjectAdapter("IceBox.ServiceManager"); Identity identity; identity.category = properties->getPropertyWithDefault("IceBox.InstanceName", "IceBox"); identity.name = "ServiceManager"; adapter->add(obj, identity); } // // Parse the property set with the prefix "IceBox.Service.". These // properties should have the following format: // // IceBox.Service.Foo=entry_point [args] // // We parse the service properties specified in IceBox.LoadOrder // first, then the ones from remaining services. // const string prefix = "IceBox.Service."; PropertyDict services = properties->getPropertiesForPrefix(prefix); PropertyDict::iterator p; StringSeq loadOrder = properties->getPropertyAsList("IceBox.LoadOrder"); vector<StartServiceInfo> servicesInfo; for(StringSeq::const_iterator q = loadOrder.begin(); q != loadOrder.end(); ++q) { p = services.find(prefix + *q); if(p == services.end()) { FailureException ex(__FILE__, __LINE__); ex.reason = "ServiceManager: no service definition for `" + *q + "'"; throw ex; } servicesInfo.push_back(StartServiceInfo(*q, p->second, _argv)); services.erase(p); } for(p = services.begin(); p != services.end(); ++p) { servicesInfo.push_back(StartServiceInfo(p->first.substr(prefix.size()), p->second, _argv)); } // // Check if some services are using the shared communicator in which // case we create the shared communicator now with a property set which // is the union of all the service properties (services which are using // the shared communicator). // PropertyDict sharedCommunicatorServices = properties->getPropertiesForPrefix("IceBox.UseSharedCommunicator."); if(!sharedCommunicatorServices.empty()) { InitializationData initData; initData.properties = createServiceProperties("SharedCommunicator"); for(vector<StartServiceInfo>::iterator q = servicesInfo.begin(); q != servicesInfo.end(); ++q) { if(properties->getPropertyAsInt("IceBox.UseSharedCommunicator." + q->name) <= 0) { continue; } // // Load the service properties using the shared communicator properties as // the default properties. // PropertiesPtr svcProperties = createProperties(q->args, initData.properties); // // Erase properties from the shared communicator which don't exist in the // service properties (which include the shared communicator properties // overriden by the service properties). // PropertyDict allProps = initData.properties->getPropertiesForPrefix(""); for(PropertyDict::iterator p = allProps.begin(); p != allProps.end(); ++p) { if(svcProperties->getProperty(p->first) == "") { initData.properties->setProperty(p->first, ""); } } // // Add the service properties to the shared communicator properties. // PropertyDict props = svcProperties->getPropertiesForPrefix(""); for(PropertyDict::const_iterator r = props.begin(); r != props.end(); ++r) { initData.properties->setProperty(r->first, r->second); } // // Parse <service>.* command line options (the Ice command line options // were parsed by the createProperties above) // q->args = initData.properties->parseCommandLineOptions(q->name, q->args); } _sharedCommunicator = initialize(initData); } // // Start the services. // for(vector<StartServiceInfo>::const_iterator r = servicesInfo.begin(); r != servicesInfo.end(); ++r) { start(r->name, r->entryPoint, r->args); } // // We may want to notify external scripts that the services // have started. This is done by defining the property: // // IceBox.PrintServicesReady=bundleName // // Where bundleName is whatever you choose to call this set of // services. It will be echoed back as "bundleName ready". // // This must be done after start() has been invoked on the // services. // string bundleName = properties->getProperty("IceBox.PrintServicesReady"); if(!bundleName.empty()) { cout << bundleName << " ready" << endl; } // // Register "this" as a facet to the Admin object, and then create // Admin object // try { _communicator->addAdminFacet(this, "IceBox.ServiceManager"); // // Add a Properties facet for each service // for(vector<ServiceInfo>::iterator r = _services.begin(); r != _services.end(); ++r) { const ServiceInfo& info = *r; CommunicatorPtr communicator = info.communicator != 0 ? info.communicator : _sharedCommunicator; _communicator->addAdminFacet(new PropertiesAdminI(communicator->getProperties()), "IceBox.Service." + info.name + ".Properties"); } _communicator->getAdmin(); } catch(const ObjectAdapterDeactivatedException&) { // // Expected if the communicator has been shutdown. // } if(adapter) { try { adapter->activate(); } catch(const ObjectAdapterDeactivatedException&) { // // Expected if the communicator has been shutdown. // } } } catch(const FailureException& ex) { Error out(_logger); out << ex.reason; stopAll(); return false; } catch(const Exception& ex) { Error out(_logger); out << "ServiceManager: " << ex; stopAll(); return false; } return true; }
int run(int argc, char* argv[], const CommunicatorPtr& communicator) { bool batch = false; int idx = 1; while(idx < argc) { if(strcmp(argv[idx], "-b") == 0) { batch = true; for(int i = idx ; i + 1 < argc ; ++i) { argv[i] = argv[i + 1]; } --argc; } else if(strcmp(argv[idx], "-h") == 0 || strcmp(argv[idx], "--help") == 0) { usage(argv[0]); return EXIT_SUCCESS; } else if(argv[idx][0] == '-') { cerr << argv[0] << ": unknown option `" << argv[idx] << "'" << endl; usage(argv[0]); return EXIT_FAILURE; } } PropertiesPtr properties = communicator->getProperties(); const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default"; string managerProxy = properties->getProperty(managerProxyProperty); if(managerProxy.empty()) { cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl; return EXIT_FAILURE; } ObjectPrx base = communicator->stringToProxy(managerProxy); IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); if(!manager) { cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl; return EXIT_FAILURE; } ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default"); EventIPtr eventFed1 = new EventI(communicator); // // Activate the servants. // ObjectPrx obj = adapter->addWithUUID(eventFed1); IceStorm::QoS qos; if(batch) { obj = obj->ice_batchOneway(); } else { obj = obj->ice_oneway(); } TopicPrx fed1; try { fed1 = manager->retrieve("fed1"); } catch(const IceStorm::NoSuchTopic& e) { cerr << argv[0] << ": NoSuchTopic: " << e.name << endl; return EXIT_FAILURE; } fed1->subscribeAndGetPublisher(qos, obj); adapter->activate(); communicator->waitForShutdown(); fed1->unsubscribe(obj); return EXIT_SUCCESS; }
void Ice::ObjectAdapterI::activate() { LocatorInfoPtr locatorInfo; bool printAdapterReady = false; { IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(*this); checkForDeactivation(); // // If we've previously been initialized we just need to activate the // incoming connection factories and we're done. // if(_state != StateUninitialized) { #ifdef ICE_CPP11_MAPPING for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), [](const IncomingConnectionFactoryPtr& factory) { factory->activate(); }); #else for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), Ice::voidMemFun(&IncomingConnectionFactory::activate)); #endif return; } // // One off initializations of the adapter: update the // locator registry and print the "adapter ready" // message. We set set state to StateActivating to prevent // deactivation from other threads while these one off // initializations are done. // _state = StateActivating; locatorInfo = _locatorInfo; if(!_noConfig) { PropertiesPtr properties = _instance->initializationData().properties; printAdapterReady = properties->getPropertyAsInt("Ice.PrintAdapterReady") > 0; } } try { Ice::Identity dummy; dummy.name = "dummy"; updateLocatorRegistry(locatorInfo, createDirectProxy(dummy)); } catch(const Ice::LocalException&) { // // If we couldn't update the locator registry, we let the // exception go through and don't activate the adapter to // allow to user code to retry activating the adapter // later. // { IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(*this); _state = StateUninitialized; notifyAll(); } throw; } if(printAdapterReady) { consoleOut << _name << " ready" << endl; } { IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(*this); assert(_state == StateActivating); #ifdef ICE_CPP11_MAPPING for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), [](const IncomingConnectionFactoryPtr& factory) { factory->activate(); }); #else for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), Ice::voidMemFun(&IncomingConnectionFactory::activate)); #endif _state = StateActive; notifyAll(); } }