//--------------------------------------------------------------------------- int main(int argc, char *argv[]) { printf("\n"); // Set up the dprintf stuff to write to stderr, so that Condor // libraries which use it will write to the right place... dprintf_set_tool_debug("TOOL", 0); set_debug_flags(NULL, D_ALWAYS | D_NOHEADER); config(); // Initialize our Distribution object -- condor vs. hawkeye, etc. myDistro->Init( argc, argv ); // Load command-line arguments into the deepOpts and shallowOpts // structures. SubmitDagDeepOptions deepOpts; SubmitDagShallowOptions shallowOpts; // We're setting strScheddDaemonAdFile and strScheddAddressFile // here so that the classad updating feature (see gittrac #1782) // works properly. The problem is that the schedd daemon ad and // address files are normally defined relative to the $LOG value. // Because we specify a different log directory on the condor_dagman // command line, if we don't set the values here, condor_dagman // won't be able to find those files when it tries to communicate /// with the schedd. wenger 2013-03-11 shallowOpts.strScheddDaemonAdFile = param( "SCHEDD_DAEMON_AD_FILE" ); shallowOpts.strScheddAddressFile = param( "SCHEDD_ADDRESS_FILE" ); parseCommandLine(deepOpts, shallowOpts, argc, argv); int tmpResult; // Recursively run ourself on nested DAGs. We need to do this // depth-first so all of the lower-level .condor.sub files already // exist when we check for log files. if ( deepOpts.recurse ) { bool useOldDagReader = param_boolean( "DAGMAN_USE_OLD_DAG_READER", false ); if ( useOldDagReader ) { tmpResult = doRecursion( deepOpts, shallowOpts ); } else { tmpResult = doRecursionNew( deepOpts, shallowOpts ); } if ( tmpResult != 0) { fprintf( stderr, "Recursive submit(s) failed; exiting without " "attempting top-level submit\n" ); return tmpResult; } } // Further work to get the shallowOpts structure set up properly. tmpResult = setUpOptions( deepOpts, shallowOpts ); if ( tmpResult != 0 ) return tmpResult; // Check whether the output files already exist; if so, we may // abort depending on the -f flag and whether we're running // a rescue DAG. ensureOutputFilesExist( deepOpts, shallowOpts ); // Make sure that all node jobs have log files, the files // aren't on NFS, etc. // Note that this MUST come after recursion, otherwise we'd // pass down the "preserved" values from the current .condor.sub // file. if ( deepOpts.updateSubmit ) { tmpResult = getOldSubmitFlags( shallowOpts ); if ( tmpResult != 0 ) return tmpResult; } // Write the actual submit file for DAGMan. writeSubmitFile( deepOpts, shallowOpts ); return submitDag( shallowOpts ); }
int main( int argc, char** argv ) { Argument param( argc, argv ); param.exec(); kvs::File fileOri( param.filename_ori ); kvs::File fileEva( param.filename_eva ); kvs::StructuredVolumeObject* ori_volume = NULL; kvs::UnstructuredVolumeObject* eva_volume = NULL; if( fileOri.extension() == "kvsml" ) { ori_volume = new kvs::StructuredVolumeImporter( param.filename_ori ); std::cout << "use kvsml volume data as original data" << std::endl; } else if( fileOri.extension() == "vld" ) { ori_volume = new kun::VldImporter( param.filename_ori ); std::cout << "use vld volume data as original data" << std::endl; } size_t nx = ori_volume->resolution().x(); size_t ny = ori_volume->resolution().y(); size_t nz = ori_volume->resolution().z(); if( fileEva.extension() == "kvsml") { eva_volume = new kvs::UnstructuredVolumeImporter( param.filename_eva ); std::cout << "use kvsml volume data as evaluation data" << std::endl; } else if( fileEva.extension() == "zk" ) { eva_volume = new kun::BlockLoader( param.filename_eva ); std::cout << "use zk volume data as evaluation data" << std::endl; } float max_value = (float)ori_volume->maxValue(); float min_value = (float)ori_volume->minValue(); std::cout << "max valume of the compressed volume:" << max_value << std::endl; std::cout << "min valume of the compressed volume:" << min_value << std::endl; float* ori_values = new float[nx * ny * nz]; ori_values = (float*)ori_volume->values().pointer(); size_t NCells = eva_volume->ncells(); kvs::TetrahedralCell<float>* cell = new kvs::TetrahedralCell<float>( eva_volume ); kvs::ValueArray<float> eva_values; eva_values.allocate( nx * ny * nz ); for ( size_t count = 0; count < NCells ; count++ ) { cell->bindCell( count ); kvs::Vector3f minf, maxf; kvs::Vector3i mini, maxi; CalcBoundingBox( cell, minf, maxf ); for ( int a = 0; a < 3; ++a ) { mini[a] = kvs::Math::Floor( minf[a] ); maxi[a] = kvs::Math::Ceil( maxf[a] ); } if ( mini.x() < 0 || maxi.x() > (float)nx ) std::cout << "x out" << std::endl; if ( mini.y() < 0 || maxi.y() > (float)ny ) std::cout << "y out" << std::endl; if ( mini.z() < 0 || maxi.z() > (float)nz ) std::cout << "z out" << std::endl; for ( int k = mini.z(); k <= maxi.z(); k++ ) for ( int j = mini.y(); j <= maxi.y(); j ++ ) for ( int i = mini.x(); i <= maxi.x(); i ++ ) { cell->setGlobalPoint( kvs::Vector3f( i, j, k ) ); kvs::Vector3f local = cell->localPoint(); if ( !(local.x() < 0 || local.y() < 0 || local.z() < 0 || 1 - local.x() + local.y() + local.z() < 0 ) ) { int index = i + j * nx + k * nx * ny; eva_values[ index ] = cell->scalar(); } } } //Calculate the error float error = 0; float average_error = 0; for ( unsigned int i = 0; i < nx * ny * nz; i ++ ) { error += fabs(eva_values[i] - ori_values[i]) / ( max_value - min_value ) ; } average_error = error / ( nx * ny * nz ); std::cout << "whole error: " << error << std::endl; std::cout << "The average error is: " << average_error << std::endl; }
/* static */ wxString wxFileType::ExpandCommand(const wxString& command, const wxFileType::MessageParameters& params) { bool hasFilename = false; wxString str; for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) { if ( *pc == wxT('%') ) { switch ( *++pc ) { case wxT('s'): // '%s' expands into file name (quoted because it might // contain spaces) - except if there are already quotes // there because otherwise some programs may get confused // by double double quotes #if 0 if ( *(pc - 2) == wxT('"') ) str << params.GetFileName(); else str << wxT('"') << params.GetFileName() << wxT('"'); #endif str << params.GetFileName(); hasFilename = true; break; case wxT('t'): // '%t' expands into MIME type (quote it too just to be // consistent) str << wxT('\'') << params.GetMimeType() << wxT('\''); break; case wxT('{'): { const wxChar *pEnd = wxStrchr(pc, wxT('}')); if ( pEnd == NULL ) { wxString mimetype; wxLogWarning(_("Unmatched '{' in an entry for mime type %s."), params.GetMimeType().c_str()); str << wxT("%{"); } else { wxString param(pc + 1, pEnd - pc - 1); str << wxT('\'') << params.GetParamValue(param) << wxT('\''); pc = pEnd; } } break; case wxT('n'): case wxT('F'): // TODO %n is the number of parts, %F is an array containing // the names of temp files these parts were written to // and their mime types. break; default: wxLogDebug(wxT("Unknown field %%%c in command '%s'."), *pc, command.c_str()); str << *pc; } } else { str << *pc; } } // metamail(1) man page states that if the mailcap entry doesn't have '%s' // the program will accept the data on stdin so normally we should append // "< %s" to the end of the command in such case, but not all commands // behave like this, in particular a common test is 'test -n "$DISPLAY"' // and appending "< %s" to this command makes the test fail... I don't // know of the correct solution, try to guess what we have to do. // test now carried out on reading file so test should never get here if ( !hasFilename && !str.empty() #ifdef __UNIX__ && !str.StartsWith(_T("test ")) #endif // Unix ) { str << wxT(" < '") << params.GetFileName() << wxT('\''); } return str; }
bool VMUniverseMgr::testVMGahp(const char* gahppath, const char* vmtype) { m_needCheck = false; if( !m_starter_has_vmcode ) { return false; } if( !gahppath || !vmtype ) { return false; } #if defined(WIN32) // On Windows machine, the option that Starter log file includes // logs from vmgahp causes deadlock even if the option works well // on Linux machine. I guess that is due to Windows Pipes but // I don't know the exact reason. // Until the problem is solved, // this option will be disabled on Windows machine. char *need_log_file = param("VM_GAHP_LOG"); if( need_log_file ) { free(need_log_file); }else { dprintf( D_ALWAYS, "To support vm universe, '%s' must be defined " "in condor config file, which is a log file for vmgahp.\n", "VM_GAHP_LOG"); return false; } #endif // vmgahp is daemonCore, so we need to add -f -t options of daemonCore. // Then, try to execute vmgahp with // vmtype <vmtype>" // and grab the output as a ClassAd ArgList systemcmd; systemcmd.AppendArg(gahppath); systemcmd.AppendArg("-f"); char *gahp_log_file = param("VM_GAHP_LOG"); if( gahp_log_file ) { free(gahp_log_file); }else { systemcmd.AppendArg("-t"); } systemcmd.AppendArg("-M"); systemcmd.AppendArg(VMGAHP_TEST_MODE); systemcmd.AppendArg("vmtype"); systemcmd.AppendArg(vmtype); #if !defined(WIN32) if( can_switch_ids() ) { MyString tmp_str; tmp_str.formatstr("%d", (int)get_condor_uid()); SetEnv("VMGAHP_USER_UID", tmp_str.Value()); } #endif priv_state prev_priv; if( (strcasecmp(vmtype, CONDOR_VM_UNIVERSE_XEN) == MATCH) || (strcasecmp(vmtype, CONDOR_VM_UNIVERSE_KVM) == MATCH) ) { // Xen requires root privilege prev_priv = set_root_priv(); }else { prev_priv = set_condor_priv(); } FILE* fp = NULL; fp = my_popen(systemcmd, "r", FALSE ); set_priv(prev_priv); if( !fp ) { dprintf( D_ALWAYS, "Failed to execute %s, ignoring\n", gahppath ); return false; } bool read_something = false; char buf[2048]; m_vmgahp_info.Clear(); while( fgets(buf, 2048, fp) ) { if( !m_vmgahp_info.Insert(buf) ) { dprintf( D_ALWAYS, "Failed to insert \"%s\" into VMInfo, " "ignoring invalid parameter\n", buf ); continue; } read_something = true; } my_pclose( fp ); if( !read_something ) { MyString args_string; systemcmd.GetArgsStringForDisplay(&args_string,0); dprintf( D_ALWAYS, "Warning: '%s' did not produce any valid output.\n", args_string.Value()); if( (strcasecmp(vmtype, CONDOR_VM_UNIVERSE_XEN) == 0) ) { MyString err_msg; err_msg += "\n#######################################################\n"; err_msg += "##### Make sure the followings "; err_msg += "to use VM universe for Xen\n"; err_msg += "### - The owner of script progrm like "; err_msg += "'condor_vm_xen.sh' must be root\n"; err_msg += "### - The script program must be executable\n"; err_msg += "### - Other writable bit for the above files is "; err_msg += "not allowed.\n"; err_msg += "#########################################################\n"; dprintf( D_ALWAYS, "%s", err_msg.Value()); } else if( (strcasecmp(vmtype, CONDOR_VM_UNIVERSE_KVM) == 0)) { MyString err_msg; err_msg += "\n#######################################################\n"; err_msg += "##### Make sure the followings "; err_msg += "to use VM universe for KVM\n"; err_msg += "### - The owner of script progrm like "; err_msg += "'condor_vm_xen.sh' must be root\n"; err_msg += "### - The script program must be executable\n"; err_msg += "### - Other writable bit for the above files is "; err_msg += "not allowed.\n"; err_msg += "#########################################################\n"; dprintf( D_ALWAYS, "%s", err_msg.Value()); }else if( strcasecmp(vmtype, CONDOR_VM_UNIVERSE_VMWARE ) == 0 ) { MyString err_msg; MyString err_msg2; err_msg += "\n#######################################################\n"; err_msg += "##### Make sure the followings "; err_msg += "to use VM universe for VMware\n"; if( can_switch_ids() ) { // Condor runs as root err_msg += "### - The script program like 'condor_vm_vmware'"; err_msg += " must be readable for anybody.\n"; } err_msg += "### - Check the path of vmware-cmd, vmrun, and mkisofs "; err_msg += "in 'condor_vm_vmware\n'"; err_msg += "#########################################################\n"; dprintf( D_ALWAYS, "%s", err_msg.Value()); } return false; } // For debug printVMGahpInfo(D_ALWAYS); // Read vm_type MyString tmp_vmtype; if( m_vmgahp_info.LookupString( ATTR_VM_TYPE, tmp_vmtype) != 1 ) { dprintf( D_ALWAYS, "There is no %s in the output of vmgahp. " "So VM Universe will be disabled\n", ATTR_VM_TYPE); return false; } if( strcasecmp(tmp_vmtype.Value(), vmtype) != 0 ) { dprintf( D_ALWAYS, "The vmgahp(%s) doesn't support this vmtype(%s)\n", gahppath, vmtype); return false; } dprintf( D_ALWAYS, "VMType('%s') is supported\n", vmtype); // Read vm_memory if( m_vmgahp_info.LookupInteger(ATTR_VM_MEMORY, m_vm_max_memory) != 1 ) { dprintf( D_ALWAYS, "There is no %s in the output of vmgahp\n",ATTR_VM_MEMORY); return false; } if( m_vm_max_memory == 0 ) { dprintf( D_ALWAYS, "There is no sufficient memory for virtual machines\n"); return false; } dprintf( D_ALWAYS, "The maximum available memory for vm universe is " "set to %d MB\n", m_vm_max_memory); // Read vm_networking bool tmp_networking = false; MyString tmp_networking_types; m_vmgahp_info.LookupBool(ATTR_VM_NETWORKING, tmp_networking); if( tmp_networking ) { if( m_vmgahp_info.LookupString( ATTR_VM_NETWORKING_TYPES, tmp_networking_types) != 1 ) { tmp_networking = false; m_vmgahp_info.Assign(ATTR_VM_NETWORKING, false); } } m_vm_networking = param_boolean("VM_NETWORKING",false); if( m_vm_networking ) { if( !tmp_networking ) { dprintf( D_ALWAYS, "Even if VM_NETWORKING is TRUE in condor config," " VM_NETWORKING is disabled because vmgahp doesn't " "support VM_NETWORKING\n"); m_vm_networking = false; } } if( m_vm_networking == false ) { dprintf( D_ALWAYS, "VM networking is disabled\n"); }else { dprintf( D_ALWAYS, "VM networking is enabled\n"); dprintf( D_ALWAYS, "Supported networking types are %s\n", tmp_networking_types.Value()); } // Now, we received correct information from vmgahp m_vm_type = tmp_vmtype; m_vmgahp_server = gahppath; return true; }
void eval_to(dense_matrix<real_type>& result) const { result = param(); }
int main(int argc, char **argv) { enum ExitCode { /** * We start from 2, because QApplicationArgumentParser * uses 1. */ QueryFailure = 2, StdOutFailure }; const QCoreApplication app(argc, argv); QCoreApplication::setApplicationName(QLatin1String("xmlpatterns")); QXmlNamePool namePool; PatternistApplicationParser parser(argc, argv, namePool); parser.setApplicationDescription(QLatin1String("A tool for running XQuery queries.")); parser.setApplicationVersion(QLatin1String("0.1")); QApplicationArgument param(QLatin1String("param"), QXmlPatternistCLI::tr("Binds an external variable. The value is directly available using the variable reference: $name."), qMetaTypeId<Parameter>()); param.setMaximumOccurrence(-1); parser.addArgument(param); const QApplicationArgument noformat(QLatin1String("no-format"), QXmlPatternistCLI::tr("By default output is formatted for readability. When specified, strict serialization is performed.")); parser.addArgument(noformat); const QApplicationArgument isURI(QLatin1String("is-uri"), QXmlPatternistCLI::tr("If specified, all filenames on the command line are interpreted as URIs instead of a local filenames.")); parser.addArgument(isURI); const QApplicationArgument initialTemplateName(QLatin1String("initial-template"), QXmlPatternistCLI::tr("The name of the initial template to call as a Clark Name."), QVariant::String); parser.addArgument(initialTemplateName); /* The temporary object is required to compile with g++ 3.3. */ QApplicationArgument queryURI = QApplicationArgument(QLatin1String("query/stylesheet"), QXmlPatternistCLI::tr("A local filename pointing to the query to run. If the name ends with .xsl it's assumed " "to be an XSL-T stylesheet. If it ends with .xq, it's assumed to be an XQuery query. (In " "other cases it's also assumed to be an XQuery query, but that interpretation may " "change in a future release of Qt.)"), QVariant::String); queryURI.setMinimumOccurrence(1); queryURI.setNameless(true); parser.addArgument(queryURI); QApplicationArgument focus = QApplicationArgument(QLatin1String("focus"), QXmlPatternistCLI::tr("The document to use as focus. Mandatory " "in case a stylesheet is used. This option is " "also affected by the is-uris option."), QVariant::String); focus.setMinimumOccurrence(0); focus.setNameless(true); parser.addArgument(focus); QApplicationArgument output(QLatin1String("output"), QXmlPatternistCLI::tr("A local file to which the output should be written. " "The file is overwritten, or if not exist, created. " "If absent, stdout is used."), qMetaTypeId<QIODevice *>()); parser.addArgument(output); if(!parser.parse()) return parser.exitCode(); /* Get the query URI. */ const QUrl effectiveURI(finalizeURI(parser, isURI, queryURI)); QXmlQuery::QueryLanguage lang; if(effectiveURI.toString().endsWith(QLatin1String(".xsl"))) lang = QXmlQuery::XSLT20; else lang = QXmlQuery::XQuery10; if(lang == QXmlQuery::XQuery10 && parser.has(initialTemplateName)) { parser.message(QXmlPatternistCLI::tr("An initial template name cannot be specified when running an XQuery.")); return QApplicationArgumentParser::ParseError; } QXmlQuery query(lang, namePool); query.setInitialTemplateName(qvariant_cast<QXmlName>(parser.value(initialTemplateName))); /* Bind external variables. */ { const QVariantList parameters(parser.values(param)); const int len = parameters.count(); /* For tracking duplicates. */ QSet<QString> usedParameters; for(int i = 0; i < len; ++i) { const Parameter p(qvariant_cast<Parameter>(parameters.at(i))); if(usedParameters.contains(p.first)) { parser.message(QXmlPatternistCLI::tr("Each parameter must be unique, %1 is specified at least twice.").arg(p.first)); return QApplicationArgumentParser::ParseError; } else { usedParameters.insert(p.first); query.bindVariable(p.first, QXmlItem(p.second)); } } } if(parser.has(focus)) { if(!query.setFocus(finalizeURI(parser, isURI, focus))) return QueryFailure; } else if(lang == QXmlQuery::XSLT20 && !parser.has(initialTemplateName)) { parser.message(QXmlPatternistCLI::tr("When a stylesheet is used, a " "document must be specified as a focus, or an " "initial template name must be specified, or both.")); return QApplicationArgumentParser::ParseError; } query.setQuery(effectiveURI); const QPatternist::AutoPtr<QIODevice> outDevice(qvariant_cast<QIODevice *>(parser.value(output))); Q_ASSERT(outDevice); Q_ASSERT(outDevice->isWritable()); if(query.isValid()) { typedef QPatternist::AutoPtr<QAbstractXmlReceiver> RecPtr; RecPtr receiver; if(parser.has(noformat)) receiver = RecPtr(new QXmlSerializer(query, outDevice.data())); else receiver = RecPtr(new QXmlFormatter(query, outDevice.data())); const bool success = query.evaluateTo(receiver.data()); if(success) return parser.exitCode(); else return QueryFailure; } else return QueryFailure; }
bool UserPolicy::FiringReason(MyString &reason,int &reason_code,int &reason_subcode) { reason_code = 0; reason_subcode = 0; if ( m_ad == NULL || m_fire_expr == NULL ) { return false; } const char * expr_src; MyString exprString; std::string reason_expr_param; std::string reason_expr_attr; std::string subcode_expr_param; std::string subcode_expr_attr; switch(m_fire_source) { case FS_NotYet: expr_src = "UNKNOWN (never set)"; break; case FS_JobAttribute: { expr_src = "job attribute"; ExprTree *tree; tree = m_ad->LookupExpr( m_fire_expr ); // Get a formatted expression string if( tree ) { exprString = ExprTreeToString( tree ); } if( m_fire_expr_val == -1 ) { reason_code = CONDOR_HOLD_CODE_JobPolicyUndefined; } else { reason_code = CONDOR_HOLD_CODE_JobPolicy; sprintf(reason_expr_attr,"%sReason", m_fire_expr); sprintf(subcode_expr_attr,"%sSubCode", m_fire_expr); } break; } case FS_SystemMacro: { expr_src = "system macro"; char * val = param(m_fire_expr); exprString = val; free(val); if( m_fire_expr_val == -1 ) { reason_code = CONDOR_HOLD_CODE_SystemPolicyUndefined; } else { reason_code = CONDOR_HOLD_CODE_SystemPolicy; sprintf(reason_expr_param,"%s_REASON", m_fire_expr); sprintf(subcode_expr_param,"%s_SUBCODE", m_fire_expr); } break; } default: expr_src = "UNKNOWN (bad value)"; break; } reason = ""; MyString subcode_expr; if( !subcode_expr_param.empty() && param(subcode_expr,subcode_expr_param.c_str(),NULL) && !subcode_expr.IsEmpty()) { m_ad->AssignExpr(ATTR_SCRATCH_EXPRESSION, subcode_expr.Value()); m_ad->EvalInteger(ATTR_SCRATCH_EXPRESSION, m_ad, reason_subcode); m_ad->Delete(ATTR_SCRATCH_EXPRESSION); } else if( !subcode_expr_attr.empty() ) { m_ad->EvalInteger(subcode_expr_attr.c_str(), m_ad, reason_subcode); } MyString reason_expr; if( !reason_expr_param.empty() && param(reason_expr,reason_expr_param.c_str(),NULL) && !reason_expr.IsEmpty()) { m_ad->AssignExpr(ATTR_SCRATCH_EXPRESSION, reason_expr.Value()); m_ad->EvalString(ATTR_SCRATCH_EXPRESSION, m_ad, reason); m_ad->Delete(ATTR_SCRATCH_EXPRESSION); } else if( !reason_expr_attr.empty() ) { m_ad->EvalString(reason_expr_attr.c_str(), m_ad, reason); } if( !reason.IsEmpty() ) { return true; } // Format up the reason string reason.sprintf( "The %s %s expression '%s' evaluated to ", expr_src, m_fire_expr, exprString.Value()); // Get a string for it's value switch( m_fire_expr_val ) { case 0: reason += "FALSE"; break; case 1: reason += "TRUE"; break; case -1: reason += "UNDEFINED"; break; default: EXCEPT( "Unrecognized FiringExpressionValue: %d", m_fire_expr_val ); break; } return true; }
void command_line_parser::parse_options(void) { while(const char* token = m_command_line.peek()) { if (*token != '-') break; std::string param(m_command_line.read()); logger().trace(corecpp::concat<std::string>({"parsing ", param}), __FILE__, __LINE__); if (param.substr(0,2) == "--") { std::string value = ""; auto pos = param.find('='); if(pos == std::string::npos) { //param with no value => value is let to an empty string param = param.substr(2); } else { value = param.substr(pos); param = param.substr(2, param.length() - 2 - pos); } auto option = get_option(param); if (option == m_options.end()) throw std::invalid_argument(param); if (option->require_value() && (pos == std::string::npos)) throw value_error(param); option->read(value); } else if (param[0] == '-') { param = param.substr(1); const char* value = m_command_line.peek(); if(value && *value == '-') //another option value = nullptr; //for loop because we can have multiple params for(auto iter = param.begin(); iter != param.end(); ) { char shortname = *iter; auto option = get_option(shortname); if(option == m_options.end()) throw std::invalid_argument(std::string(1, shortname)); if (++iter == param.end())//last option => must give the value to it { if (!value && option->require_value()) throw value_error(param); if (option->require_value()) { value = m_command_line.read(); //consume the parameter option->read(value); } else option->read(""); } else //not the last parameter => should not need a value { if (option->require_value()) throw value_error(param); option->read(""); } } } } }
void phillip_main_t::write_header() const { auto write = [this](std::ostream *os) { (*os) << "<phillip>" << std::endl; (*os) << "<configure>" << std::endl; (*os) << "<version>" << VERSION << "</version>" << std::endl; auto get_time_stamp_exe = []() -> std::string { int year, month, day, hour, min, sec; std::string out; util::beginning_time(&year, &month, &day, &hour, &min, &sec); switch (month) { case 1: out = "Jan"; break; case 2: out = "Feb"; break; case 3: out = "Mar"; break; case 4: out = "Apr"; break; case 5: out = "May"; break; case 6: out = "Jun"; break; case 7: out = "Jul"; break; case 8: out = "Aug"; break; case 9: out = "Sep"; break; case 10: out = "Oct"; break; case 11: out = "Nov"; break; case 12: out = "Dec"; break; default: throw; } return out + util::format(" %2d %4d %02d:%02d:%02d", day, year, hour, min, sec); }; (*os) << "<time_stamp compiled=\"" << util::format("%s %s", __DATE__, __TIME__) << "\" executed=\"" << get_time_stamp_exe() << "\"></time_stamp>" << std::endl; (*os) << "<components lhs=\"" << m_lhs_enumerator->repr() << "\" ilp=\"" << m_ilp_convertor->repr() << "\" sol=\"" << m_ilp_solver->repr() << "\"></components>" << std::endl; const kb::knowledge_base_t *base = kb::knowledge_base_t::instance(); (*os) << "<knowledge_base path=\"" << base->filename() << "\" size=\"" << base->num_of_axioms() << "\" max_distance=\"" << base->get_max_distance() << "\"></knowledge_base>" << std::endl; (*os) << "<params timeout_lhs=\"" << timeout_lhs().get() << "\" timeout_ilp=\"" << timeout_ilp().get() << "\" timeout_sol=\"" << timeout_sol().get() << "\" timeout_all=\"" << timeout_all().get() << "\" verbose=\"" << verbose(); for (auto it = m_params.begin(); it != m_params.end(); ++it) (*os) << "\" " << it->first << "=\"" << it->second; for (auto it = m_flags.begin(); it != m_flags.end(); ++it) (*os) << "\" " << (*it) << "=\"yes"; #ifdef DISABLE_CANCELING (*os) << "\" disable_canceling=\"yes"; #endif #ifdef DISABLE_HARD_TERM (*os) << "\" disable_hard_term=\"yes"; #endif (*os) << "\"></params>" << std::endl; (*os) << "</configure>" << std::endl; }; auto f_write = [&](const std::string &key) { std::ofstream *fo(NULL); if ((fo = _open_file(param(key), (std::ios::out | std::ios::trunc))) != NULL) { write(fo); delete fo; } }; f_write("path_lhs_out"); f_write("path_ilp_out"); f_write("path_sol_out"); f_write("path_out"); write(&std::cout); }
int RefreshProxyThruMyProxy(X509CredentialWrapper * proxy) { const char * proxy_filename = proxy->GetStorageName(); char * myproxy_host = NULL; int status; if (((X509Credential*)proxy->cred)->GetMyProxyServerHost() == NULL) { dprintf (D_ALWAYS, "Skipping %s\n", proxy->cred->GetName()); return FALSE; } // First check if a refresh process is already running time_t now = time(NULL); if (proxy->get_delegation_pid != GET_DELEGATION_PID_NONE) { time_t time_started = proxy->get_delegation_proc_start_time; // If the old "refresh proxy" proc is still running, kill it if (now - time_started > 500) { dprintf (D_FULLDEBUG, "MyProxy refresh process pid=%d still running, " "sending signal %d\n", proxy->get_delegation_pid, SIGKILL); daemonCore->Send_Signal (proxy->get_delegation_pid, SIGKILL); // Wait for reaper to cleanup. } else { dprintf (D_FULLDEBUG, "MyProxy refresh process pid=%d still running, " "letting it finish\n", proxy->get_delegation_pid); } return FALSE; } proxy->get_delegation_proc_start_time = now; // Set up environnment for myproxy-get-delegation Env myEnv; MyString strBuff; if (((X509Credential*)proxy->cred)->GetMyProxyServerDN()) { strBuff="MYPROXY_SERVER_DN="; strBuff+= ((X509Credential*)proxy->cred)->GetMyProxyServerDN(); myEnv.SetEnv (strBuff.Value()); dprintf (D_FULLDEBUG, "%s\n", strBuff.Value()); } strBuff="X509_USER_PROXY="; strBuff+=proxy->GetStorageName(); dprintf (D_FULLDEBUG, "%s\n", strBuff.Value()); // Get password (this will end up in stdin for myproxy-get-delegation) const char * myproxy_password =((X509Credential*)proxy->cred)->GetRefreshPassword(); if (myproxy_password == NULL ) { dprintf (D_ALWAYS, "No MyProxy password specified for %s:%s\n", proxy->cred->GetName(), proxy->cred->GetOwner()); myproxy_password = ""; } status = pipe (proxy->get_delegation_password_pipe); if (status == -1) { dprintf (D_ALWAYS, "get_delegation pipe() failed: %s\n", strerror(errno) ); proxy->get_delegation_reset(); return FALSE; } // TODO: check write() return values for errors, short writes. int written = write (proxy->get_delegation_password_pipe[1], myproxy_password, strlen (myproxy_password)); if (written < (long)strlen(myproxy_password)) { dprintf (D_ALWAYS, "Write to proxy delegation pipe failed (%s)", strerror(errno)); proxy->get_delegation_reset(); return FALSE; } written = write (proxy->get_delegation_password_pipe[1], "\n", 1); if (written < 1) { dprintf (D_ALWAYS, "Write newline to proxy delegation pipe failed (%s)", strerror(errno) ); proxy->get_delegation_reset(); return FALSE; } // Figure out user name; const char * username = proxy->cred->GetOrigOwner(); // Figure out myproxy host and port myproxy_host = getHostFromAddr (((X509Credential*)proxy->cred)->GetMyProxyServerHost()); int myproxy_port = getPortFromAddr (((X509Credential*)proxy->cred)->GetMyProxyServerHost()); // construct arguments ArgList args; args.AppendArg("--verbose "); args.AppendArg("--out"); args.AppendArg(proxy_filename); args.AppendArg("--pshost"); args.AppendArg(myproxy_host); if ( myproxy_host != NULL ) { free ( myproxy_host ); } args.AppendArg("--dn_as_username"); args.AppendArg("--proxy_lifetime"); // hours args.AppendArg(6); args.AppendArg("--stdin_pass"); args.AppendArg("--username"); args.AppendArg(username); // Optional port argument if (myproxy_port) { args.AppendArg("--psport"); args.AppendArg(myproxy_port); } // Optional credential name if ( ((X509Credential*)proxy->cred)->GetCredentialName() && ( ((X509Credential*)proxy->cred)->GetCredentialName() )[0] ) { args.AppendArg("--credname"); args.AppendArg(((X509Credential*)proxy->cred)->GetCredentialName()); } // Create temporary file to store myproxy-get-delegation's stderr // The file will be owned by the "condor" user priv_state priv = set_condor_priv(); proxy->get_delegation_err_filename = create_temp_file(); if (proxy->get_delegation_err_filename == NULL) { dprintf (D_ALWAYS, "get_delegation create_temp_file() failed: %s\n", strerror(errno) ); proxy->get_delegation_reset(); return FALSE; } status = chmod (proxy->get_delegation_err_filename, 0600); if (status == -1) { dprintf (D_ALWAYS, "chmod() get_delegation_err_filename %s failed: %s\n", proxy->get_delegation_err_filename, strerror(errno) ); proxy->get_delegation_reset(); return FALSE; } proxy->get_delegation_err_fd = safe_open_wrapper_follow(proxy->get_delegation_err_filename,O_RDWR); if (proxy->get_delegation_err_fd == -1) { dprintf (D_ALWAYS, "Error opening get_delegation file %s: %s\n", proxy->get_delegation_err_filename, strerror(errno) ); proxy->get_delegation_reset(); return FALSE; } set_priv (priv); int arrIO[3]; arrIO[0]=proxy->get_delegation_password_pipe[0]; //stdin arrIO[1]=-1; //proxy->get_delegation_err_fd; arrIO[2]=proxy->get_delegation_err_fd; // stderr char * myproxy_get_delegation_pgm = param ("MYPROXY_GET_DELEGATION"); if (!myproxy_get_delegation_pgm) { dprintf (D_ALWAYS, "MYPROXY_GET_DELEGATION not defined in config file\n"); return FALSE; } MyString args_string; args.GetArgsStringForDisplay(&args_string); dprintf (D_ALWAYS, "Calling %s %s\n", myproxy_get_delegation_pgm, args_string.Value()); int pid = daemonCore->Create_Process ( myproxy_get_delegation_pgm, // name args, // args PRIV_USER_FINAL, // priv myproxyGetDelegationReaperId, // reaper_id FALSE, // want_command_port FALSE, // want_command_port &myEnv, // env NULL, // cwd NULL, // family_info NULL, // sock_inherit_list arrIO); // in/out/err streams // nice_inc // job_opt_mask free (myproxy_get_delegation_pgm); myproxy_get_delegation_pgm = NULL; if (pid == FALSE) { dprintf (D_ALWAYS, "Failed to run myproxy-get-delegation\n"); proxy->get_delegation_reset(); return FALSE; } proxy->get_delegation_pid = pid; return TRUE; }
void Init() { char * tmp = param( "CRED_SUPER_USERS" ); if( tmp ) { super_users.initializeFromString( tmp ); free( tmp ); } else { #if defined(WIN32) super_users.initializeFromString("Administrator"); #else super_users.initializeFromString("root"); #endif } char * spool = param ("SPOOL"); tmp = param ( "CRED_STORE_DIR" ); if ( tmp ) { cred_store_dir = tmp; } else { cred_store_dir = dircat (spool, "cred"); } if ( spool != NULL ) { free (spool); } tmp = param ( "CRED_INDEX_FILE" ); if (tmp ) { cred_index_file = tmp; } else { cred_index_file = dircat (cred_store_dir, "cred-index"); } // default 1 hr default_cred_expire_threshold = param_integer ("DEFAULT_CRED_EXPIRE_THRESHOLD", 3600); // default 1 minute CheckCredentials_interval = param_integer ( "CRED_CHECK_INTERVAL", // param name DEF_CRED_CHECK_INTERVAL // default value, seconds ); struct stat stat_buff; if (stat (cred_store_dir, &stat_buff)) { dprintf (D_ALWAYS, "ERROR: Cred store directory %s does not exist\n", cred_store_dir); DC_Exit (1 ); } if (stat (cred_index_file, &stat_buff)) { dprintf (D_ALWAYS, "Creating credential index file %s\n", cred_index_file); priv_state priv = set_root_priv(); int fd = safe_open_wrapper_follow(cred_index_file, O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd != -1) { close (fd); set_priv (priv); } else { dprintf (D_ALWAYS, "ERROR: Unable to create credential index file %s\n", cred_index_file); set_priv (priv); DC_Exit (1 ); } } else { if ((stat_buff.st_mode & (S_IRWXG | S_IRWXO)) || (stat_buff.st_uid != getuid())) { dprintf (D_ALWAYS, "ERROR: Invalid ownership / permissions on credential index file %s\n", cred_index_file); DC_Exit (1 ); } } }
app * pb_util::mk_at_least_k(unsigned num_args, expr * const * args, unsigned k) { parameter param(k); return m.mk_app(m_fid, OP_AT_LEAST_K, 1, ¶m, num_args, args, m.mk_bool_sort()); }
void main_init(int argc, char* argv[]) { char** ptr; MyString job_queue_name; int argc_count = 1; for(ptr = argv + 1, argc_count = 1; argc_count<argc && *ptr; ptr++,argc_count++) { if(ptr[0][0] != '-') { usage(argv[0]); } switch(ptr[0][1]) { case 'n': Name = build_valid_daemon_name( *(++ptr) ); break; default: usage(argv[0]); } } // Tell Attrlist to publish the server time AttrList_setPublishServerTime( true ); // Initialize DaemonCore's use of ProcFamily. We do this so that we // launch a ProcD if necessary so that any Starters that we launch // for Local Universe jobs can share a single ProcD, instead of // each creating their own daemonCore->Proc_Family_Init(); #if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT) #if defined(HAVE_DLOPEN) // Intialization of the plugin manager, i.e. loading all // plugins, should be performed before the job queue log is // read so plugins have a chance to learn about all jobs // already in the queue ClassAdLogPluginManager::Load(); // Load all ScheddPlugins. In reality this doesn't do much // since initializing any plugin manager loads plugins for all // plugin manager. ScheddPluginManager::Load(); // Tell all ScheddPlugins to initialze themselves ScheddPluginManager::EarlyInitialize(); // Tell all plugins to initialize themselves ClassAdLogPluginManager::EarlyInitialize(); #endif #endif // Initialize all the modules scheduler.Init(); scheduler.Register(); // Initialize the job queue char *job_queue_param_name = param("JOB_QUEUE_LOG"); if (job_queue_param_name == NULL) { // the default place for the job_queue.log is in spool job_queue_name.sprintf( "%s/job_queue.log", Spool); } else { job_queue_name = job_queue_param_name; // convert char * to MyString free(job_queue_param_name); } // Make a backup of the job queue? if ( param_boolean_crufty("SCHEDD_BACKUP_SPOOL", false) ) { MyString hostname; UtcTime now(true); hostname = get_local_hostname(); MyString job_queue_backup; job_queue_backup.sprintf( "%s/job_queue.bak.%s.%ld", Spool, hostname.Value(), now.seconds() ); if ( copy_file( job_queue_name.Value(), job_queue_backup.Value() ) ) { dprintf( D_ALWAYS, "Failed to backup spool to '%s'\n", job_queue_backup.Value() ); } else { dprintf( D_FULLDEBUG, "Spool backed up to '%s'\n", job_queue_backup.Value() ); } } int max_historical_logs = param_integer( "MAX_JOB_QUEUE_LOG_ROTATIONS", DEFAULT_MAX_JOB_QUEUE_LOG_ROTATIONS ); InitJobQueue(job_queue_name.Value(),max_historical_logs); mark_jobs_idle(); // The below must happen _after_ InitJobQueue is called. if ( scheduler.autocluster.config() ) { // clear out auto cluster id attributes WalkJobQueue( (int(*)(ClassAd *))clear_autocluster_id ); } // // Update the SchedDInterval attributes in jobs if they // have it defined. This will be for JobDeferral and // CronTab jobs // WalkJobQueue( (int(*)(ClassAd *))::updateSchedDInterval ); // Initialize the dedicated scheduler stuff dedicated_scheduler.initialize(); // Do a timeout now at startup to get the ball rolling... scheduler.timeout(); #if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT) #if defined(HAVE_DLOPEN) // Tell all ScheddPlugins to initialze themselves ScheddPluginManager::Initialize(); // Tell all plugins to initialize themselves ClassAdLogPluginManager::Initialize(); #endif #endif }
//--------------------------------------------------------------------------- void writeSubmitFile(/* const */ SubmitDagDeepOptions &deepOpts, /* const */ SubmitDagShallowOptions &shallowOpts) { FILE *pSubFile = safe_fopen_wrapper_follow(shallowOpts.strSubFile.Value(), "w"); if (!pSubFile) { fprintf( stderr, "ERROR: unable to create submit file %s\n", shallowOpts.strSubFile.Value() ); exit( 1 ); } const char *executable = NULL; MyString valgrindPath; // outside if so executable is valid! if ( shallowOpts.runValgrind ) { valgrindPath = which( valgrind_exe ); if ( valgrindPath == "" ) { fprintf( stderr, "ERROR: can't find %s in PATH, aborting.\n", valgrind_exe ); exit( 1 ); } else { executable = valgrindPath.Value(); } } else { executable = deepOpts.strDagmanPath.Value(); } fprintf(pSubFile, "# Filename: %s\n", shallowOpts.strSubFile.Value()); fprintf(pSubFile, "# Generated by condor_submit_dag "); shallowOpts.dagFiles.rewind(); char *dagFile; while ( (dagFile = shallowOpts.dagFiles.next()) != NULL ) { fprintf(pSubFile, "%s ", dagFile); } fprintf(pSubFile, "\n"); fprintf(pSubFile, "universe\t= scheduler\n"); fprintf(pSubFile, "executable\t= %s\n", executable); fprintf(pSubFile, "getenv\t\t= True\n"); fprintf(pSubFile, "output\t\t= %s\n", shallowOpts.strLibOut.Value()); fprintf(pSubFile, "error\t\t= %s\n", shallowOpts.strLibErr.Value()); fprintf(pSubFile, "log\t\t= %s\n", shallowOpts.strSchedLog.Value()); #if !defined ( WIN32 ) fprintf(pSubFile, "remove_kill_sig\t= SIGUSR1\n" ); #endif fprintf(pSubFile, "+%s\t= \"%s =?= $(cluster)\"\n", ATTR_OTHER_JOB_REMOVE_REQUIREMENTS, ATTR_DAGMAN_JOB_ID ); // ensure DAGMan is automatically requeued by the schedd if it // exits abnormally or is killed (e.g., during a reboot) const char *defaultRemoveExpr = "( ExitSignal =?= 11 || " "(ExitCode =!= UNDEFINED && ExitCode >=0 && ExitCode <= 2))"; MyString removeExpr(defaultRemoveExpr); char *tmpRemoveExpr = param("DAGMAN_ON_EXIT_REMOVE"); if ( tmpRemoveExpr ) { removeExpr = tmpRemoveExpr; free(tmpRemoveExpr); } fprintf(pSubFile, "# Note: default on_exit_remove expression:\n"); fprintf(pSubFile, "# %s\n", defaultRemoveExpr); fprintf(pSubFile, "# attempts to ensure that DAGMan is automatically\n"); fprintf(pSubFile, "# requeued by the schedd if it exits abnormally or\n"); fprintf(pSubFile, "# is killed (e.g., during a reboot).\n"); fprintf(pSubFile, "on_exit_remove\t= %s\n", removeExpr.Value() ); fprintf(pSubFile, "copy_to_spool\t= %s\n", shallowOpts.copyToSpool ? "True" : "False" ); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Be sure to change MIN_SUBMIT_FILE_VERSION in dagman_main.cpp // if the arguments passed to condor_dagman change in an // incompatible way!! //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ArgList args; if ( shallowOpts.runValgrind ) { args.AppendArg("--tool=memcheck"); args.AppendArg("--leak-check=yes"); args.AppendArg("--show-reachable=yes"); args.AppendArg(deepOpts.strDagmanPath.Value()); } args.AppendArg("-f"); args.AppendArg("-l"); args.AppendArg("."); if ( shallowOpts.iDebugLevel != DEBUG_UNSET ) { args.AppendArg("-Debug"); args.AppendArg(shallowOpts.iDebugLevel); } args.AppendArg("-Lockfile"); args.AppendArg(shallowOpts.strLockFile.Value()); args.AppendArg("-AutoRescue"); args.AppendArg(deepOpts.autoRescue); args.AppendArg("-DoRescueFrom"); args.AppendArg(deepOpts.doRescueFrom); if(!deepOpts.always_use_node_log) { args.AppendArg("-dont_use_default_node_log"); } shallowOpts.dagFiles.rewind(); while ( (dagFile = shallowOpts.dagFiles.next()) != NULL ) { args.AppendArg("-Dag"); args.AppendArg(dagFile); } if(shallowOpts.iMaxIdle != 0) { args.AppendArg("-MaxIdle"); args.AppendArg(shallowOpts.iMaxIdle); } if(shallowOpts.iMaxJobs != 0) { args.AppendArg("-MaxJobs"); args.AppendArg(shallowOpts.iMaxJobs); } if(shallowOpts.iMaxPre != 0) { args.AppendArg("-MaxPre"); args.AppendArg(shallowOpts.iMaxPre); } if(shallowOpts.iMaxPost != 0) { args.AppendArg("-MaxPost"); args.AppendArg(shallowOpts.iMaxPost); } if(shallowOpts.bNoEventChecks) { // strArgs += " -NoEventChecks"; printf( "Warning: -NoEventChecks is ignored; please use " "the DAGMAN_ALLOW_EVENTS config parameter instead\n"); } if(!shallowOpts.bPostRun) { args.AppendArg("-DontAlwaysRunPost"); } if(deepOpts.bAllowLogError) { args.AppendArg("-AllowLogError"); } if(deepOpts.useDagDir) { args.AppendArg("-UseDagDir"); } if(deepOpts.suppress_notification) { args.AppendArg("-Suppress_notification"); } else { args.AppendArg("-Dont_Suppress_notification"); } if ( shallowOpts.doRecovery ) { args.AppendArg( "-DoRecov" ); } args.AppendArg("-CsdVersion"); args.AppendArg(CondorVersion()); if(deepOpts.allowVerMismatch) { args.AppendArg("-AllowVersionMismatch"); } if(shallowOpts.dumpRescueDag) { args.AppendArg("-DumpRescue"); } if(deepOpts.bVerbose) { args.AppendArg("-Verbose"); } if(deepOpts.bForce) { args.AppendArg("-Force"); } if(deepOpts.strNotification != "") { args.AppendArg("-Notification"); args.AppendArg(deepOpts.strNotification); } if(deepOpts.strDagmanPath != "") { args.AppendArg("-Dagman"); args.AppendArg(deepOpts.strDagmanPath); } if(deepOpts.strOutfileDir != "") { args.AppendArg("-Outfile_dir"); args.AppendArg(deepOpts.strOutfileDir); } if(deepOpts.updateSubmit) { args.AppendArg("-Update_submit"); } if(deepOpts.importEnv) { args.AppendArg("-Import_env"); } if( deepOpts.priority != 0 ) { args.AppendArg("-Priority"); args.AppendArg(deepOpts.priority); } MyString arg_str,args_error; if(!args.GetArgsStringV1WackedOrV2Quoted(&arg_str,&args_error)) { fprintf(stderr,"Failed to insert arguments: %s",args_error.Value()); exit(1); } fprintf(pSubFile, "arguments\t= %s\n", arg_str.Value()); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Be sure to change MIN_SUBMIT_FILE_VERSION in dagman_main.cpp // if the environment passed to condor_dagman changes in an // incompatible way!! //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EnvFilter env; if ( deepOpts.importEnv ) { env.Import( ); } env.SetEnv("_CONDOR_DAGMAN_LOG", shallowOpts.strDebugLog.Value()); env.SetEnv("_CONDOR_MAX_DAGMAN_LOG=0"); if ( shallowOpts.strScheddDaemonAdFile != "" ) { env.SetEnv("_CONDOR_SCHEDD_DAEMON_AD_FILE", shallowOpts.strScheddDaemonAdFile.Value()); } if ( shallowOpts.strScheddAddressFile != "" ) { env.SetEnv("_CONDOR_SCHEDD_ADDRESS_FILE", shallowOpts.strScheddAddressFile.Value()); } if ( shallowOpts.strConfigFile != "" ) { if ( access( shallowOpts.strConfigFile.Value(), F_OK ) != 0 ) { fprintf( stderr, "ERROR: unable to read config file %s " "(error %d, %s)\n", shallowOpts.strConfigFile.Value(), errno, strerror(errno) ); exit(1); } env.SetEnv("_CONDOR_DAGMAN_CONFIG_FILE", shallowOpts.strConfigFile.Value()); } MyString env_str; MyString env_errors; if(!env.getDelimitedStringV1RawOrV2Quoted(&env_str,&env_errors)) { fprintf(stderr,"Failed to insert environment: %s",env_errors.Value()); exit(1); } fprintf(pSubFile, "environment\t= %s\n",env_str.Value()); if(deepOpts.strNotification != "") { fprintf(pSubFile, "notification\t= %s\n", deepOpts.strNotification.Value()); } // Append user-specified stuff to submit file... // ...first, the insert file, if any... if (shallowOpts.appendFile != "") { FILE *aFile = safe_fopen_wrapper_follow(shallowOpts.appendFile.Value(), "r"); if (!aFile) { fprintf( stderr, "ERROR: unable to read submit append file (%s)\n", shallowOpts.appendFile.Value() ); exit( 1 ); } char *line; while ((line = getline(aFile)) != NULL) { fprintf(pSubFile, "%s\n", line); } fclose(aFile); } // ...now things specified directly on the command line. shallowOpts.appendLines.rewind(); char *command; while ((command = shallowOpts.appendLines.next()) != NULL) { fprintf(pSubFile, "%s\n", command); } fprintf(pSubFile, "queue\n"); fclose(pSubFile); }
TEST_F(use_program_test, has_correct_params) { glUseProgram(1); auto first_invocation = s_stub.function_calls().front(); ASSERT_EQ(first_invocation.param("program"), t_arg(1)); }
void AtmelSWIAnalyzerResults::GetTextsForPacketSegmentFrame(const Frame& f, DisplayBase display_base, std::vector<std::string>& texts) { const int BUFF_SIZE = 128; char number_str[BUFF_SIZE]; std::string tmpstr; texts.clear(); // get the I/O block int block_ndx(static_cast<int>(f.mData2 & 0xffffffff)); int block_offset(static_cast<int>(((f.mData2 >> 32) & 0xffffffff))); const SWI_Block& block(mBlocks[block_ndx]); SWI_PacketParam* param(PacketParams + f.mData1); switch (param->Type) { case PT_Opcode: AnalyzerHelpers::GetNumberString(block.Opcode, display_base, 8, number_str, BUFF_SIZE); texts.push_back(std::string("Opcode ") + param->Name + " (" + number_str + ")"); texts.push_back(number_str); texts.push_back(param->Name); texts.push_back(std::string("Opcode ") + param->Name); texts.push_back(std::string(param->Name) + " (" + number_str + ")"); break; case PT_RawBytes: { std::string array_str(GetByteArrayNumberStr(block.Data.begin() + block_offset, param->Length, display_base)); texts.push_back(std::string(param->Name) + " (" + array_str + ")"); texts.push_back(array_str); texts.push_back(param->Name); } break; case PT_Zone: { AnalyzerHelpers::GetNumberString(block.Opcode, display_base, 8, number_str, BUFF_SIZE); U8 zone = block.Data[block_offset] & 3; std::string zonestr("<unknown>"); if (zone == 0) zonestr = "Config"; else if (zone == 1) zonestr = "OTP"; else if (zone == 2) zonestr = "Data"; const char* lenstr; if (block.Data[block_offset] & 0x80) lenstr = "32 bytes"; else lenstr = "4 bytes"; texts.push_back("Zone " + zonestr + ", " + lenstr); texts.push_back(number_str); texts.push_back(std::string(param->Name) + " (" + number_str + ")"); } break; case PT_Byte: AnalyzerHelpers::GetNumberString(block.Data[block_offset], display_base, 8, number_str, BUFF_SIZE); texts.push_back(std::string(param->Name) + " (" + number_str + ")"); texts.push_back(param->Name); break; case PT_Status: AnalyzerHelpers::GetNumberString(block.Data[block_offset], display_base, 8, number_str, BUFF_SIZE); tmpstr = "<undefined>"; if (block.Data[block_offset] == 0x00) tmpstr = "Command executed successfully"; else if (block.Data[block_offset] == 0x01) tmpstr = "Checkmac miscompare"; else if (block.Data[block_offset] == 0x03) tmpstr = "Parse error"; else if (block.Data[block_offset] == 0x0F) tmpstr = "Execution error"; else if (block.Data[block_offset] == 0x11) tmpstr = "Wake received properly"; else if (block.Data[block_offset] == 0xFF) tmpstr = "CRC or communication error"; else tmpstr = "Unknown status code"; texts.push_back(std::string(param->Name) + " " + tmpstr + " (" + number_str + ")" ); texts.push_back(std::string(param->Name) + " " + tmpstr); texts.push_back(std::string(param->Name) + " (" + number_str + ")"); texts.push_back(tmpstr); texts.push_back(param->Name); break; case PT_Word: case PT_DWord: if (param->Type == PT_Word) { size_t val = (block.Data[block_offset + 1] << 8) | block.Data[block_offset]; AnalyzerHelpers::GetNumberString(val, display_base, 16, number_str, BUFF_SIZE); } else { size_t val = (block.Data[block_offset + 3] << 24) | (block.Data[block_offset + 2] << 16) | (block.Data[block_offset + 1] << 8) | block.Data[block_offset]; AnalyzerHelpers::GetNumberString(val, display_base, 32, number_str, BUFF_SIZE); } texts.push_back(std::string(param->Name) + " (" + number_str + ")"); texts.push_back(param->Name); texts.push_back(number_str); break; } }
int StructureManager::placeStructureFromDeed(CreatureObject* creature, StructureDeed* deed, float x, float y, int angle) { ManagedReference<Zone*> zone = creature->getZone(); //Already placing a structure? if (zone == NULL || creature->containsActiveSession(SessionFacadeType::PLACESTRUCTURE)) return 1; ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager(); String serverTemplatePath = deed->getGeneratedObjectTemplate(); if (deed->getFaction() != 0 && creature->getFaction() != deed->getFaction()) { creature->sendSystemMessage("You are not the correct faction"); return 1; } Reference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode())); //Check to see if this zone allows this structure. if (serverTemplate == NULL || !serverTemplate->isAllowedZone(zone->getZoneName())) { creature->sendSystemMessage("@player_structure:wrong_planet"); //That deed cannot be used on this planet. return 1; } if (!planetManager->isBuildingPermittedAt(x, y, creature)) { creature->sendSystemMessage("@player_structure:not_permitted"); //Building is not permitted here. return 1; } SortedVector<ManagedReference<ActiveArea*> > objects; zone->getInRangeActiveAreas(x, y, &objects, true); ManagedReference<CityRegion*> city; for (int i = 0; i < objects.size(); ++i) { ActiveArea* area = objects.get(i).get(); if (!area->isRegion()) continue; city = dynamic_cast<Region*>(area)->getCityRegion(); if (city != NULL) break; } SortedVector<ManagedReference<QuadTreeEntry*> > inRangeObjects; zone->getInRangeObjects(x, y, 128, &inRangeObjects, true); float placingFootprintLength0, placingFootprintWidth0, placingFootprintLength1, placingFootprintWidth1; if (!getStructureFootprint(serverTemplate, angle, placingFootprintLength0, placingFootprintWidth0, placingFootprintLength1, placingFootprintWidth1)) { float x0 = x + placingFootprintWidth0; float y0 = y + placingFootprintLength0; float x1 = x + placingFootprintWidth1; float y1 = y + placingFootprintLength1; BoundaryRectangle placingFootprint(x0, y0, x1, y1); //info("placing center x:" + String::valueOf(x) + " y:" + String::valueOf(y), true); //info("placingFootprint x0:" + String::valueOf(x0) + " y0:" + String::valueOf(y0) + " x1:" + String::valueOf(x1) + " y1:" + String::valueOf(y1), true); for (int i = 0; i < inRangeObjects.size(); ++i) { SceneObject* scene = inRangeObjects.get(i).castTo<SceneObject*>(); if (scene == NULL) continue; float l0 = -5; //Along the x axis. float w0 = -5; //Along the y axis. float l1 = 5; float w1 = 5; if (getStructureFootprint(scene->getObjectTemplate(), scene->getDirectionAngle(), l0, w0, l1, w1)) continue; float xx0 = scene->getPositionX() + (w0 + 0.1); float yy0 = scene->getPositionY() + (l0 + 0.1); float xx1 = scene->getPositionX() + (w1 - 0.1); float yy1 = scene->getPositionY() + (l1 - 0.1); BoundaryRectangle rect(xx0, yy0, xx1, yy1); //info("existing footprint xx0:" + String::valueOf(xx0) + " yy0:" + String::valueOf(yy0) + " xx1:" + String::valueOf(xx1) + " yy1:" + String::valueOf(yy1), true); // check 4 points of the current rect if (rect.containsPoint(x0, y0) || rect.containsPoint(x0, y1) || rect.containsPoint(x1, y0) || rect.containsPoint(x1, y1) ) { //info("existing footprint contains placing point", true); creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here.. return 1; } if (placingFootprint.containsPoint(xx0, yy0) || placingFootprint.containsPoint(xx0, yy1) || placingFootprint.containsPoint(xx1, yy0) || placingFootprint.containsPoint(xx1, yy1) || (xx0 == x0 && yy0 == y0 && xx1 == x1 && yy1 == y1)) { //info("placing footprint contains existing point", true); creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here. return 1; } } } int rankRequired = serverTemplate->getCityRankRequired(); if (city == NULL && rankRequired > 0) { creature->sendSystemMessage("@city/city:build_no_city"); // You must be in a city to place that structure. return 1; } if (city != NULL) { if (city->isZoningEnabled() && !city->hasZoningRights(creature->getObjectID())) { creature->sendSystemMessage("@player_structure:no_rights"); //You don't have the right to place that structure in this city. The mayor or one of the city milita must grant you zoning rights first. return 1; } if (rankRequired != 0 && city->getCityRank() < rankRequired) { StringIdChatParameter param("city/city", "rank_req"); // The city must be at least rank %DI (%TO) in order for you to place this structure. param.setDI(rankRequired); param.setTO("city/city", "rank" + String::valueOf(rankRequired)); creature->sendSystemMessage(param); return 1; } if (serverTemplate->isCivicStructure() && !city->isMayor(creature->getObjectID()) ) { creature->sendSystemMessage("@player_structure:cant_place_civic");//"This structure must be placed within the borders of the city in which you are mayor." return 1; } if (serverTemplate->isUniqueStructure() && city->hasUniqueStructure(serverTemplate->getServerObjectCRC())) { creature->sendSystemMessage("@player_structure:cant_place_unique"); //This city can only support a single structure of this type. return 1; } } Locker _lock(deed, creature); if(serverTemplate->isDerivedFrom("object/building/faction_perk/base/shared_factional_building_base.iff")){ Zone* zone = creature->getZone(); if(zone == NULL) return 1; GCWManager* gcwMan = zone->getGCWManager(); if(gcwMan == NULL) return 1; if(!gcwMan->canPlaceMoreBases(creature)) return 1; } //Ensure that it is the correct deed, and that it is in a container in the creature's inventory. if (!deed->isASubChildOf(creature)) { creature->sendSystemMessage("@player_structure:no_possession"); //You no longer are in possession of the deed for this structure. Aborting construction. return 1; } TemplateManager* templateManager = TemplateManager::instance(); ManagedReference<PlayerObject*> ghost = creature->getPlayerObject(); if (ghost != NULL) { String abilityRequired = serverTemplate->getAbilityRequired(); if (!abilityRequired.isEmpty() && !ghost->hasAbility(abilityRequired)) { creature->sendSystemMessage("@player_structure:" + abilityRequired); return 1; } int lots = serverTemplate->getLotSize(); if (!ghost->hasLotsRemaining(lots)) { StringIdChatParameter param("@player_structure:not_enough_lots"); param.setDI(lots); creature->sendSystemMessage(param); return 1; } } //Validate that the structure can be placed at the given coordinates: //Ensure that no other objects impede on this structures footprint, or overlap any city regions or no build areas. //Make sure that the player has zoning rights in the area. ManagedReference<PlaceStructureSession*> session = new PlaceStructureSession(creature, deed); creature->addActiveSession(SessionFacadeType::PLACESTRUCTURE, session); //Construct the structure. session->constructStructure(x, y, angle); //Remove the deed from it's container. deed->destroyObjectFromWorld(true); return 0; }
// Convert a Private Key object into an opaque key handle, using AES Key Wrap // with the long-lived aPersistentKey mixed with aAppParam to convert aPrivKey. // The key handle's format is version || saltLen || salt || wrappedPrivateKey static UniqueSECItem KeyHandleFromPrivateKey(const UniquePK11SlotInfo& aSlot, const UniquePK11SymKey& aPersistentKey, uint8_t* aAppParam, uint32_t aAppParamLen, const UniqueSECKEYPrivateKey& aPrivKey, const nsNSSShutDownPreventionLock&) { MOZ_ASSERT(aSlot); MOZ_ASSERT(aPersistentKey); MOZ_ASSERT(aAppParam); MOZ_ASSERT(aPrivKey); if (NS_WARN_IF(!aSlot || !aPersistentKey || !aPrivKey || !aAppParam)) { return nullptr; } // Generate a random salt uint8_t saltParam[kSaltByteLen]; SECStatus srv = PK11_GenerateRandomOnSlot(aSlot.get(), saltParam, sizeof(saltParam)); if (NS_WARN_IF(srv != SECSuccess)) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to generate a salt, NSS error #%d", PORT_GetError())); return nullptr; } // Prepare the HKDF (https://tools.ietf.org/html/rfc5869) CK_NSS_HKDFParams hkdfParams = { true, saltParam, sizeof(saltParam), true, aAppParam, aAppParamLen }; SECItem kdfParams = { siBuffer, (unsigned char*)&hkdfParams, sizeof(hkdfParams) }; // Derive a wrapping key from aPersistentKey, the salt, and the aAppParam. // CKM_AES_KEY_GEN and CKA_WRAP are key type and usage attributes of the // derived symmetric key and don't matter because we ignore them anyway. UniquePK11SymKey wrapKey(PK11_Derive(aPersistentKey.get(), CKM_NSS_HKDF_SHA256, &kdfParams, CKM_AES_KEY_GEN, CKA_WRAP, kWrappingKeyByteLen)); if (NS_WARN_IF(!wrapKey.get())) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to derive a wrapping key, NSS error #%d", PORT_GetError())); return nullptr; } UniqueSECItem wrappedKey(::SECITEM_AllocItem(/* default arena */ nullptr, /* no buffer */ nullptr, kWrappedKeyBufLen)); if (NS_WARN_IF(!wrappedKey)) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to allocate memory")); return nullptr; } UniqueSECItem param(PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP_PAD, /* default IV */ nullptr )); srv = PK11_WrapPrivKey(aSlot.get(), wrapKey.get(), aPrivKey.get(), CKM_NSS_AES_KEY_WRAP_PAD, param.get(), wrappedKey.get(), /* wincx */ nullptr); if (NS_WARN_IF(srv != SECSuccess)) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to wrap U2F key, NSS error #%d", PORT_GetError())); return nullptr; } // Concatenate the salt and the wrapped Private Key together mozilla::dom::CryptoBuffer keyHandleBuf; if (NS_WARN_IF(!keyHandleBuf.SetCapacity(wrappedKey.get()->len + sizeof(saltParam) + 2, mozilla::fallible))) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to allocate memory")); return nullptr; } // It's OK to ignore the return values here because we're writing into // pre-allocated space keyHandleBuf.AppendElement(SoftTokenHandle::Version1, mozilla::fallible); keyHandleBuf.AppendElement(sizeof(saltParam), mozilla::fallible); keyHandleBuf.AppendElements(saltParam, sizeof(saltParam), mozilla::fallible); keyHandleBuf.AppendSECItem(wrappedKey.get()); UniqueSECItem keyHandle(::SECITEM_AllocItem(nullptr, nullptr, 0)); if (NS_WARN_IF(!keyHandle)) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to allocate memory")); return nullptr; } if (NS_WARN_IF(!keyHandleBuf.ToSECItem(/* default arena */ nullptr, keyHandle.get()))) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to allocate memory")); return nullptr; } return keyHandle; }
void PartSysParser::ParseEmitter(const TabFileRecord& record) { auto systemName = record[COL_PARTSYS_NAME].AsString(); auto& system = mSpecs[tolower(systemName)]; // Create it on demand if (!system) { system = std::make_shared<PartSysSpec>(systemName); } // Add the emitter auto emitter = system->CreateEmitter(record[COL_EMITTER_NAME].AsString()); ParseOptionalFloat(record, COL_DELAY, "Delay", [&] (float value) { emitter->SetDelay(value / 30.0f); }); ParseLifespan(record, emitter); ParseParticleLifespan(record, emitter); ParseParticleRate(record, emitter); ParseOptionalEnum<PartSysEmitterSpace>(record, COL_EMITTER_SPACE, "emitter space", EmitterSpaceMapping, [&](auto space) { emitter->SetSpace(space); }); ParseEmitterNodeName(record, emitter); ParseOptionalEnum<PartSysCoordSys>(record, COL_EMITTER_COORD_SYS, "emitter coord sys", CoordSysMapping, [&](auto coordSys) { emitter->SetCoordSys(coordSys); }); ParseOptionalEnum<PartSysCoordSys>(record, COL_EMITTER_OFFSET_COORD_SYS, "emitter offset coord sys", CoordSysMapping, [&](auto coordSys) { emitter->SetOffsetCoordSys(coordSys); }); ParseOptionalEnum<PartSysParticleType>(record, COL_PARTICLE_TYPE, "particle type", ParticleTypeMapping, [&](PartSysParticleType type) { emitter->SetParticleType(type); }); ParseOptionalEnum<PartSysBlendMode>(record, COL_BLEND_MODE, "blend mode", BlendModeMapping, [&](auto mode) { emitter->SetBlendMode(mode); }); ParseMaterial(record, emitter); ParseOptionalEnum<PartSysCoordSys>(record, COL_PARTICLE_POS_COORD_SYS, "particle pos coord sys", CoordSysMapping, [&](auto coordSys) { emitter->SetParticlePosCoordSys(coordSys); }); ParseOptionalEnum<PartSysCoordSys>(record, COL_PARTICLE_VELOCITY_COORD_SYS, "particle velocity coord sys", CoordSysMapping, [&](auto coordSys) { emitter->SetParticleVelocityCoordSys(coordSys); }); ParseOptionalEnum<PartSysParticleSpace>(record, COL_PARTICLE_SPACE, "particle space", ParticleSpaceMapping, [&](auto space) { emitter->SetParticleSpace(space); }); ParseMesh(record, emitter); // Parse the bounding box ParseOptionalFloat(record, COL_BB_LEFT, "bb left", [&](float val) { emitter->SetBoxLeft(val); }); ParseOptionalFloat(record, COL_BB_TOP, "bb top", [&](float val) { emitter->SetBoxTop(val); }); ParseOptionalFloat(record, COL_BB_RIGHT, "bb right", [&](float val) { emitter->SetBoxRight(val); }); ParseOptionalFloat(record, COL_BB_BOTTOM, "bb bottom", [&](float val) { emitter->SetBoxBottom(val); }); for (int paramId = 0; paramId <= part_attractorBlend; paramId++) { int colIdx = 22 + paramId; auto col = record[colIdx]; if (col) { bool success; std::unique_ptr<PartSysParam> param(ParserParams::Parse((PartSysParamId) paramId, col, emitter->GetLifespan(), emitter->GetParticleLifespan(), success)); if (success) { emitter->SetParam((PartSysParamId)paramId, param); } else { logger->warn("Unable to parse particle system param {} for particle system {} and emitter {} with value {}", paramId, systemName, emitter->GetName(), col.AsString()); } } } }
// Convert an opaque key handle aKeyHandle back into a Private Key object, using // the long-lived aPersistentKey mixed with aAppParam and the AES Key Wrap // algorithm. static UniqueSECKEYPrivateKey PrivateKeyFromKeyHandle(const UniquePK11SlotInfo& aSlot, const UniquePK11SymKey& aPersistentKey, uint8_t* aKeyHandle, uint32_t aKeyHandleLen, uint8_t* aAppParam, uint32_t aAppParamLen, const nsNSSShutDownPreventionLock&) { MOZ_ASSERT(aSlot); MOZ_ASSERT(aPersistentKey); MOZ_ASSERT(aKeyHandle); MOZ_ASSERT(aAppParam); MOZ_ASSERT(aAppParamLen == SHA256_LENGTH); if (NS_WARN_IF(!aSlot || !aPersistentKey || !aKeyHandle || !aAppParam || aAppParamLen != SHA256_LENGTH)) { return nullptr; } // As we only support one key format ourselves (right now), fail early if // we aren't that length if (NS_WARN_IF(aKeyHandleLen != kVersion1KeyHandleLen)) { return nullptr; } if (NS_WARN_IF(aKeyHandle[0] != SoftTokenHandle::Version1)) { // Unrecognized version return nullptr; } uint8_t saltLen = aKeyHandle[1]; uint8_t* saltPtr = aKeyHandle + 2; if (NS_WARN_IF(saltLen != kSaltByteLen)) { return nullptr; } // Prepare the HKDF (https://tools.ietf.org/html/rfc5869) CK_NSS_HKDFParams hkdfParams = { true, saltPtr, saltLen, true, aAppParam, aAppParamLen }; SECItem kdfParams = { siBuffer, (unsigned char*)&hkdfParams, sizeof(hkdfParams) }; // Derive a wrapping key from aPersistentKey, the salt, and the aAppParam. // CKM_AES_KEY_GEN and CKA_WRAP are key type and usage attributes of the // derived symmetric key and don't matter because we ignore them anyway. UniquePK11SymKey wrapKey(PK11_Derive(aPersistentKey.get(), CKM_NSS_HKDF_SHA256, &kdfParams, CKM_AES_KEY_GEN, CKA_WRAP, kWrappingKeyByteLen)); if (NS_WARN_IF(!wrapKey.get())) { MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Failed to derive a wrapping key, NSS error #%d", PORT_GetError())); return nullptr; } uint8_t wrappedLen = aKeyHandleLen - saltLen - 2; uint8_t* wrappedPtr = aKeyHandle + saltLen + 2; ScopedAutoSECItem wrappedKeyItem(wrappedLen); memcpy(wrappedKeyItem.data, wrappedPtr, wrappedKeyItem.len); ScopedAutoSECItem pubKey(kPublicKeyLen); UniqueSECItem param(PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP_PAD, /* default IV */ nullptr )); CK_ATTRIBUTE_TYPE usages[] = { CKA_SIGN }; int usageCount = 1; UniqueSECKEYPrivateKey unwrappedKey( PK11_UnwrapPrivKey(aSlot.get(), wrapKey.get(), CKM_NSS_AES_KEY_WRAP_PAD, param.get(), &wrappedKeyItem, /* no nickname */ nullptr, /* discard pubkey */ &pubKey, /* not permanent */ false, /* non-exportable */ true, CKK_EC, usages, usageCount, /* wincx */ nullptr)); if (NS_WARN_IF(!unwrappedKey)) { // Not our key. MOZ_LOG(gNSSTokenLog, LogLevel::Debug, ("Could not unwrap key handle, NSS Error #%d", PORT_GetError())); return nullptr; } return unwrappedKey; }
void DBMSManager::config() { char *name = param("DBMSMANAGER_NAME"); if(name) { char *valid_name = build_valid_daemon_name(name); m_name = valid_name; free(name); delete [] valid_name; } else { char *default_name = default_daemon_name(); if(default_name) { m_name = default_name; delete [] default_name; } } InitPublicAd(); int update_interval = param_integer("UPDATE_INTERVAL", 60); if(m_public_ad_update_interval != update_interval) { m_public_ad_update_interval = update_interval; if(m_public_ad_update_timer >= 0) { daemonCore->Cancel_Timer(m_public_ad_update_timer); m_public_ad_update_timer = -1; } dprintf(D_FULLDEBUG, "Setting update interval to %d\n", m_public_ad_update_interval); m_public_ad_update_timer = daemonCore->Register_Timer( 0, m_public_ad_update_interval, (TimerHandlercpp)&DBMSManager::TimerHandler_UpdateCollector, "DBMSManager::TimerHandler_UpdateCollector", this); } /* register the database purging callback */ int purge_interval = param_integer("DATABASE_PURGE_INTERVAL", 86400); // 24 hours if(m_database_purge_interval != purge_interval) { m_database_purge_interval = purge_interval; if(m_database_purge_timer >= 0) { daemonCore->Cancel_Timer(m_database_purge_timer); m_database_purge_timer = -1; } dprintf(D_FULLDEBUG, "Setting database purge interval to %d\n", m_database_purge_interval); m_database_purge_timer = daemonCore->Register_Timer( 0, m_database_purge_interval, (TimerHandlercpp)&DBMSManager::TimerHandler_PurgeDatabase, "DBMSManager::TimerHandler_PurgeDatabase", this); } /* register the database reindexing callback */ int reindex_interval = param_integer("DATABASE_REINDEX_INTERVAL", 86400); // 24 hours if(m_database_reindex_interval != reindex_interval) { m_database_reindex_interval = reindex_interval; if(m_database_reindex_timer >= 0) { daemonCore->Cancel_Timer(m_database_reindex_timer); m_database_reindex_timer = -1; } dprintf(D_FULLDEBUG, "Setting database reindex interval to %d\n", m_database_reindex_interval); m_database_reindex_timer = daemonCore->Register_Timer( 0, m_database_reindex_interval, (TimerHandlercpp)&DBMSManager::TimerHandler_ReindexDatabase, "DBMSManager::TimerHandler_ReindexDatabase", this); } }
void QsCodeParser::quickifyFunction(ClassNode *quickClass, ClassNode *qtClass, FunctionNode *func, bool onBlackList) { if (func->metaness() == FunctionNode::Dtor) return; FunctionNode *kernelFunc = findKernelFunction( QStringList() << quickClass->name(), func->name()); QString quickName = func->name(); if (func->metaness() == FunctionNode::Ctor) quickName = quickClass->name(); FunctionNode *quickFunc = new FunctionNode(quickClass, quickName); quickFunc->setLocation(func->location()); if (onBlackList) { quickFunc->setAccess(Node::Protected); } else { if (kernelFunc != 0 && func->numOverloads() == 1 && (func->parameters().count() == 0 || func->parameters().last().defaultValue().isEmpty())) { kernelFunc->setAccess(Node::Private); } else { if (func->metaness() == FunctionNode::Plain) quickFunc->setAccess(Node::Protected); } } quickFunc->setReturnType(cpp2qs.convertedDataType(qsTre, func->returnType())); if (func->metaness() != FunctionNode::Slot) quickFunc->setMetaness(func->metaness()); quickFunc->setVirtualness(FunctionNode::ImpureVirtual); quickFunc->setOverload(func->isOverload()); QList<Parameter>::ConstIterator q = func->parameters().begin(); while (q != func->parameters().end()) { QString dataType = cpp2qs.convertedDataType(qsTre, (*q).leftType(), (*q).rightType()); if (dataType.isEmpty()) { dataType = "UNKNOWN"; quickFunc->setAccess(Node::Private); } Parameter param(dataType, "", (*q).name(), (*q).defaultValue().isEmpty() ? "" : "undefined"); quickFunc->addParameter(param); ++q; } if (func->doc().isEmpty()) { if (func->parent() != (InnerNode *) qtClass) { func = qtClass->findFunctionNode(func); if (func != 0) setQtDoc(quickFunc, func->doc()); } } else { setQtDoc(quickFunc, func->doc()); } }
#include "altitude_controller.h" #include <string.h> #include <Protocol/common.h> #include <utils/param.h> #define default_throttle_hover 0.45f static param quadcopter_max_climb_rate("maxC",5); static param quadcopter_max_descend_rate("maxD", 2); static param quadcopter_max_acceleration("maxA", 4.5); static param pid_quad_altitude[4] = // P, I, D, IMAX, // unit: 1/second, 1/seconds^2, 1, meter*second // convert altitude error(meter) to target climb rate(meter/second) { param("altP", 1.0f), param("altI", 0.0f), param("altD", 0.0f), param("altM", 0.0f), }; static param pid_quad_alt_rate[4] = // P, I, D, IMAX // unit: 1/second, 1/seconds^2, 1, meter*second // convert climb rate error(meter/second) to target acceleration(meter/second^2) { param("cliP", 5.0f), param("cliI", 0.0f), param("cliD", 0.0f), param("cliM", 0.0f), }; static param pid_quad_accel[4] = // P, I, D, IMAX // unit:
// ----------------------------------------- // entry point // ----------------------------------------- int main(int argc, char** argv) { #if AUDIO_STREAM StreamReplicator* audio_replicator = NULL; #endif // default parameters const char *dev_name = "/dev/video1"; int format = V4L2_PIX_FMT_H264; int width = 1280; int height = 720; int queueSize = 10; int fps = 30; int isp_fps = 30; int bitrate = 1024; //(Kbps) int mjpeg_qp = 120; int m2m_en = 1; int gop = fps; unsigned short rtpPortNum = 20000; unsigned short rtcpPortNum = rtpPortNum+1; unsigned char ttl = 5; struct in_addr destinationAddress; unsigned short rtspPort = 554; unsigned short rtspOverHTTPPort = 0; bool multicast = false; int verbose = 0; std::string outputFile; //bool useMmap = true; std::string url = "unicast"; std::string murl = "multicast"; bool useThread = true; in_addr_t maddr = INADDR_NONE; bool audio_en = false; // decode parameters int c = 0; //while ((c = getopt (argc, argv, "hW:H:Q:P:F:v::O:T:m:u:rsM:")) != -1) #if AUDIO_STREAM while ((c = getopt (argc, argv, "hb:W:H:g:Q:P:F:i:O:T:m:u:M:aj:")) != -1) #else while ((c = getopt (argc, argv, "hb:W:H:g:Q:P:F:i:O:T:m:u:M:j:")) != -1) #endif { switch (c) { case 'O': outputFile = optarg; break; //case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; case 'm': multicast = true; if (optarg) murl = optarg; break; case 'M': multicast = true; if (optarg) maddr = inet_addr(optarg); break; case 'g': gop = atoi(optarg); break; case 'b': bitrate = atoi(optarg); break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'Q': queueSize = atoi(optarg); break; case 'P': rtspPort = atoi(optarg); break; case 'T': rtspOverHTTPPort = atoi(optarg); break; case 'F': fps = atoi(optarg); break; case 'i': isp_fps = atoi(optarg); break; //case 'r': useMmap = false; break; //case 's': useThread = false; break; case 'u': url = optarg; break; #if AUDIO_STREAM case 'a': audio_en = true; break; #endif case 'j': format = V4L2_PIX_FMT_MJPEG; mjpeg_qp = atoi(optarg);break; case 'h': default: { std::cout << argv[0] << "Version:" << SNX_RTSP_SERVER_VERSION << std::endl; std::cout << "Usage :" << std::endl; std::cout << "\t " << argv[0] << " [-a] [-j mjpeg_qp] [-m] [-P RTSP port][-T RTSP/HTTP port][-Q queueSize] [-M groupaddress] [-b bitrate] [-W width] [-H height] [-F fps] [-i isp_fps] [device]" << std::endl; std::cout << "\t -Q length: Number of frame queue (default "<< queueSize << ")" << std::endl; std::cout << "\t RTSP options :" << std::endl; std::cout << "\t -u url : unicast url (default " << url << ")" << std::endl; std::cout << "\t -m url : multicast url (default " << murl << ")" << std::endl; std::cout << "\t -M addr : multicast group (default is a random address)" << std::endl; std::cout << "\t -P port : RTSP port (default "<< rtspPort << ")" << std::endl; std::cout << "\t -T port : RTSP over HTTP port (default "<< rtspOverHTTPPort << ")" << std::endl; std::cout << "\t V4L2 options :" << std::endl; //std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; //std::cout << "\t -s : V4L2 capture using live555 mainloop (default use a separated reading thread)" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -i isp_fps : ISP capture framerate (default "<< isp_fps << ")" << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t V4L2 H264 options :" << std::endl; std::cout << "\t -b bitrate : V4L2 capture bitrate kbps(default "<< bitrate << " kbps)" << std::endl; std::cout << "\t -g gop : V4L2 capture gop (default "<< gop << " )" << std::endl; std::cout << "\t device : V4L2 capture device (default "<< dev_name << ")" << std::endl; std::cout << "\t V4L2 MJPEG options :" << std::endl; std::cout << "\t -j mjpeg_qp : MJPEG streaming and qp (default is 60)" << std::endl; #if AUDIO_STREAM std::cout << "\t -a : enable A-law pcm streaming " << std::endl; std::cout << "\t H264 example : "<< argv[0] << " -a -Q 5 -u media/stream1 -P 554" << std::endl; #else std::cout << "\t H264 example : "<< argv[0] << " -Q 5 -u media/stream1 -P 554" << std::endl; #endif std::cout << "\t MJPEG example : "<< argv[0] << " -W 640 -H 480 -j 120 -Q 5 -u media/stream1 -P 554" << std::endl; exit(0); } } } if (optind<argc) { dev_name = argv[optind]; } // create live555 environment scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); // create RTSP server rtspServer = RTSPServer::createNew(*env, rtspPort); if (rtspServer == NULL) { //LOG(ERROR) << "Failed to create RTSP server: " << env->getResultMsg(); fprintf(stderr, "Failed to create RTSP server: %s \n", env->getResultMsg()); } else { // set http tunneling if (rtspOverHTTPPort) { rtspServer->setUpTunnelingOverHTTP(rtspOverHTTPPort); } // Init capture //LOG(NOTICE) << "Create V4L2 Source..." << dev_name; fprintf(stderr, "create Video source = %s \n", dev_name); V4L2DeviceParameters param(dev_name,format,width,height,fps, isp_fps, verbose, bitrate, m2m_en, gop, mjpeg_qp, queueSize ); videoCapture = createVideoCapure(param); #if AUDIO_STREAM if (audio_en) { audioCapture = createAudioCapure(); } #endif if (videoCapture) { int outputFd = -1; //int outputFd = createOutput(outputFile, videoCapture->getFd()); //LOG(NOTICE) << "Start V4L2 Capture..." << dev_name; fprintf(stderr, "Start V4L2 Capture... %s \n", dev_name); //videoCapture->captureStart(); snx98600_video_start(videoCapture); printf("\n\n------- V4L2 Infomation -------- \n"); printf("m2m_en: %d\n", videoCapture->m2m->m2m); printf("codec_dev: %s\n", videoCapture->m2m->codec_dev); printf("codec_fps: %d\n", videoCapture->m2m->codec_fps); if(videoCapture->m2m->m2m) printf("isp_fps: %d\n", videoCapture->m2m->isp_fps); printf("width: %d\n", videoCapture->m2m->width); printf("height: %d\n", videoCapture->m2m->height); printf("scale: %d\n", videoCapture->m2m->scale); printf("bit_rate: %d\n", videoCapture->m2m->bit_rate); printf("dyn_fps_en: %d\n", videoCapture->m2m->dyn_fps_en); if(videoCapture->m2m->dyn_fps_en) { printf("framerate: %d\n", videoCapture->rate_ctl->framerate); } printf("GOP: %d\n", videoCapture->rate_ctl->gop); printf("ds_font_num: %d\n", videoCapture->m2m->ds_font_num); printf("\n----------------------------- \n\n"); #if AUDIO_STREAM /* Start Audio Device */ if (audio_en) { int rc; if (audioCapture) { if ((rc = snx98600_record_audio_start(audioCapture))) { fprintf(stderr, "failed to start audio source: %s\n", strerror(rc)); } } } #endif /* Determind which Class to use */ if (format == V4L2_PIX_FMT_H264) videoES = H264_V4L2DeviceSource::createNew(*env, param, outputFd, useThread); else { videoES = V4L2DeviceSource::createNew(*env, param, outputFd, useThread); } /* check if create a Device source success */ if (videoES == NULL) { //LOG(FATAL) << "Unable to create source for device " << dev_name; fprintf(stderr, "Unable to create source for device %s \n", dev_name); } else { videoCapture->devicesource = videoES; // Setup the outpacket size; if (m2m_en) { //OutPacketBuffer::maxSize = (unsigned int)videoCapture->m2m->isp_buffers->length; OutPacketBuffer::maxSize = bitrate << 8; //2X Bitrate as the max packet size fprintf(stderr, "isp buffers: %u , outpack maxsize : %u\n", (unsigned int)videoCapture->m2m->isp_buffers->length, OutPacketBuffer::maxSize ); }else { OutPacketBuffer::maxSize = width * height * 3 / 2; } #if AUDIO_STREAM /* create Alsa Device source Class */ if (audio_en && audioCapture) { audioES = AlsaDeviceSource::createNew(*env, -1, queueSize, useThread); if (audioES == NULL) { fprintf(stderr, "Unable to create audio devicesource \n"); } else { audioCapture->devicesource = audioES; } } #endif replicator = StreamReplicator::createNew(*env, videoES, false); #if AUDIO_STREAM if (audio_en && audioCapture) audio_replicator = StreamReplicator::createNew(*env, audioES, false); #endif // Create Server Multicast Session if (multicast) { ServerMediaSubsession * multicast_video_subSession = NULL; ServerMediaSubsession * multicast_audio_subSession = NULL; if (maddr == INADDR_NONE) maddr = chooseRandomIPv4SSMAddress(*env); destinationAddress.s_addr = maddr; //LOG(NOTICE) << "Mutlicast address " << inet_ntoa(destinationAddress); fprintf(stderr, "Mutlicast address %s \n", inet_ntoa(destinationAddress)); multicast_video_subSession = MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, replicator,format,param); #if AUDIO_STREAM if (audio_en && audioCapture) multicast_audio_subSession = MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, audio_replicator,WA_PCMA,param); #endif addSession(rtspServer, murl.c_str(), multicast_video_subSession, multicast_audio_subSession); } ServerMediaSubsession * video_subSession = NULL; ServerMediaSubsession * audio_subSession = NULL; video_subSession = UnicastServerMediaSubsession::createNew(*env,replicator,format, param); #if AUDIO_STREAM if (audio_en && audioCapture) audio_subSession = UnicastServerMediaSubsession::createNew(*env,audio_replicator,WA_PCMA, param); #endif // Create Server Unicast Session addSession(rtspServer, url.c_str(), video_subSession, audio_subSession); // main loop signal(SIGINT,sighandler); env->taskScheduler().doEventLoop(&quit); fprintf(stderr, "Exiting.... \n"); #if AUDIO_STREAM if (audioES) { Medium::close(audioES); } #endif Medium::close(videoES); } #if AUDIO_STREAM if (audio_en && audioCapture) closeAudioCapure(audioCapture); #endif if (videoCapture) closeVideoCapure(videoCapture); //delete videoCapture; if (outputFd != -1) { close(outputFd); } } Medium::close(rtspServer); } env->reclaim(); delete scheduler; return 0; }
void DiscoveryQos::addCustomParameter(std::string name, std::string value) { types::CustomParameter param(name, value); customParameters[name] = param; }
void CondorQ::rawDBQuery(const char *dbconn, CondorQQueryType qType) { #ifndef HAVE_EXT_POSTGRESQL (void) dbconn; (void) qType; #else JobQueueDatabase *DBObj = NULL; const char *rowvalue; int ntuples; SQLQuery sqlquery; char *tmp; dbtype dt; tmp = param("QUILL_DB_TYPE"); if (tmp) { if (strcasecmp(tmp, "PGSQL") == 0) { dt = T_PGSQL; } } else { dt = T_PGSQL; // assume PGSQL by default } free(tmp); switch (dt) { case T_PGSQL: DBObj = new PGSQLDatabase(dbconn); break; default: break;; } if (!DBObj || (DBObj->connectDB() == QUILL_FAILURE)) { fprintf(stderr, "\n-- Failed to connect to the database\n"); return; } switch (qType) { case AVG_TIME_IN_QUEUE: sqlquery.setQuery(QUEUE_AVG_TIME, NULL); sqlquery.prepareQuery(); DBObj->execQuery(sqlquery.getQuery(), ntuples); /* we expect exact one row out of the query */ if (ntuples != 1) { fprintf(stderr, "\n-- Failed to execute the query\n"); return; } rowvalue = DBObj -> getValue(0, 0); if(strcmp(rowvalue,"") == 0) // result from empty job queue in pgsql { printf("\nJob queue is curently empty\n"); } else { printf("\nAverage time in queue for uncompleted jobs (in days hh:mm:ss)\n"); printf("%s\n", rowvalue); } DBObj -> releaseQueryResult(); break; default: fprintf(stderr, "Error: type of query not supported\n"); return; break; } if(DBObj) { delete DBObj; } #endif /* HAVE_EXT_POSTGRESQL */ }
Floats EzRestraint::get_parameters(std::string restype) { Floats param(3); if (restype == "ALA") { param[0] = -0.29; param[1] = 10.22; param[2] = 4.67; } else if (restype == "ASP") { param[0] = 1.19; param[1] = 14.25; param[2] = 8.98; } else if (restype == "GLU") { param[0] = 1.30; param[1] = 14.66; param[2] = 4.16; } else if (restype == "PHE") { param[0] = -0.80; param[1] = 19.67; param[2] = 7.12; } else if (restype == "GLY") { param[0] = -0.01; param[1] = 13.86; param[2] = 6.00; } else if (restype == "HIS") { param[0] = 0.75; param[1] = 12.26; param[2] = 2.77; } else if (restype == "ILE") { param[0] = -0.56; param[1] = 14.34; param[2] = 10.69; } else if (restype == "LYS") { param[0] = 1.66; param[1] = 11.11; param[2] = 2.09; } else if (restype == "LEU") { param[0] = -0.64; param[1] = 17.34; param[2] = 8.61; } else if (restype == "MET") { param[0] = -0.28; param[1] = 18.04; param[2] = 7.13; } else if (restype == "ASN") { param[0] = 0.89; param[1] = 12.78; param[2] = 6.28; } else if (restype == "PRO") { param[0] = 0.83; param[1] = 18.09; param[2] = 3.53; } else if (restype == "GLN") { param[0] = 1.21; param[1] = 10.46; param[2] = 2.59; } else if (restype == "ARG") { param[0] = 1.55; param[1] = 9.34; param[2] = 4.68; } else if (restype == "SER") { param[0] = 0.10; param[1] = 13.86; param[2] = 6.00; } else if (restype == "THR") { param[0] = 0.01; param[1] = 13.86; param[2] = 6.00; } else if (restype == "VAL") { param[0] = -0.47; param[1] = 11.35; param[2] = 4.97; } else if (restype == "TRP") { param[0] = -0.85; param[1] = 11.65; param[2] = 7.20; } else if (restype == "TYR") { param[0] = -0.42; param[1] = 13.04; param[2] = 6.20; } else { std::cout << "No such residue" << std::endl; } return param; }
zSphere::zSphere(float radius, int gridX, int gridY): //m_pVertex(0), //m_pTexcoord(0), m_samples(0) { m_radius = radius; m_grid_x = gridX+1; m_grid_y = gridY+1; //m_count = (m_grid_x+1)*(m_grid_y+1)*6; //m_pVertex = new float[(m_grid_x+1)*(m_grid_y+1)*6*3]; //m_pTexcoord = new float[(m_grid_x+1)*(m_grid_y+1)*6*2]; m_samples = new sphereSample[m_grid_x*m_grid_y]; float u, v; for(int j=0; j<m_grid_y; j++) { for(int i=0; i<m_grid_x; i++) { u = (float)i/(float)gridX; v = (float)j/(float)gridY; param(u, v, m_samples[m_grid_x*j+i].pos.x, m_samples[m_grid_x*j+i].pos.y, m_samples[m_grid_x*j+i].pos.z); m_samples[m_grid_x*j+i].col = XYZ(1,0,0); m_samples[m_grid_x*j+i].texcoord.x = u; m_samples[m_grid_x*j+i].texcoord.y = v; /* u = (float)i/(float)m_grid_x; v = float(j+1)/(float)m_grid_y; param(u, v, m_pVertex[(((m_grid_x+1)*j+i)*6+1)*3], m_pVertex[(((m_grid_x+1)*j+i)*6+1)*3+1], m_pVertex[(((m_grid_x+1)*j+i)*6+1)*3+2]); m_pTexcoord[(((m_grid_x+1)*j+i)*6+1)*2] = u; m_pTexcoord[(((m_grid_x+1)*j+i)*6+1)*2+1] = v; u = float(i+1)/(float)m_grid_x; v = float(j+1)/(float)m_grid_y; param(u, v, m_pVertex[(((m_grid_x+1)*j+i)*6+2)*3], m_pVertex[(((m_grid_x+1)*j+i)*6+2)*3+1], m_pVertex[(((m_grid_x+1)*j+i)*6+2)*3+2]); m_pTexcoord[(((m_grid_x+1)*j+i)*6+2)*2] = u; m_pTexcoord[(((m_grid_x+1)*j+i)*6+2)*2+1] = v; m_pVertex[(((m_grid_x+1)*j+i)*6+3)*3] = m_pVertex[(((m_grid_x+1)*j+i)*6+2)*3]; m_pVertex[(((m_grid_x+1)*j+i)*6+3)*3+1] = m_pVertex[(((m_grid_x+1)*j+i)*6+2)*3+1]; m_pVertex[(((m_grid_x+1)*j+i)*6+3)*3+2] = m_pVertex[(((m_grid_x+1)*j+i)*6+2)*3+2]; m_pTexcoord[(((m_grid_x+1)*j+i)*6+3)*2] = u; m_pTexcoord[(((m_grid_x+1)*j+i)*6+3)*2+1] = v; u = float(i+1)/(float)m_grid_x; v = float(j)/(float)m_grid_y; param(u, v, m_pVertex[(((m_grid_x+1)*j+i)*6+4)*3], m_pVertex[(((m_grid_x+1)*j+i)*6+4)*3+1], m_pVertex[(((m_grid_x+1)*j+i)*6+4)*3+2]); m_pTexcoord[(((m_grid_x+1)*j+i)*6+4)*2] = u; m_pTexcoord[(((m_grid_x+1)*j+i)*6+4)*2+1] = v; m_pVertex[(((m_grid_x+1)*j+i)*6+5)*3] = m_pVertex[(((m_grid_x+1)*j+i)*6)*3]; m_pVertex[(((m_grid_x+1)*j+i)*6+5)*3+1] = m_pVertex[(((m_grid_x+1)*j+i)*6)*3+1]; m_pVertex[(((m_grid_x+1)*j+i)*6+5)*3+2] = m_pVertex[(((m_grid_x+1)*j+i)*6)*3+2]; m_pTexcoord[(((m_grid_x+1)*j+i)*6+5)*2] = m_pTexcoord[(((m_grid_x+1)*j+i)*6)*2]; m_pTexcoord[(((m_grid_x+1)*j+i)*6+5)*2+1] = m_pTexcoord[(((m_grid_x+1)*j+i)*6)*2+1]; */ } } }
void JobQueueDBManager::config(bool reconfig) { char *tmp; MyString sql_str; int bndcnt = 0; const char *data_arr[3]; QuillAttrDataType data_typ[3]; if (param_boolean("QUILL_ENABLED", false) == false) { EXCEPT("Quill++ is currently disabled. Please set QUILL_ENABLED to " "TRUE if you want this functionality and read the manual " "about this feature since it requires other attributes to be " "set properly."); } //bail out if no SPOOL variable is defined since its used to //figure out the location of the job_queue.log file char *spool = param("SPOOL"); if(!spool) { EXCEPT("No SPOOL variable found in config file"); } jobQueueLogFile = (char *) malloc(_POSIX_PATH_MAX * sizeof(char)); snprintf(jobQueueLogFile,_POSIX_PATH_MAX * sizeof(char), "%s/job_queue.log", spool); /* Here we try to read the database parameters in config the db ip address format is <ipaddress:port> */ dt = getConfigDBType(); jobQueueDBIpAddress = param("QUILL_DB_IP_ADDR"); jobQueueDBName = param("QUILL_DB_NAME"); jobQueueDBUser = param("QUILL_DB_USER"); jobQueueDBConn = getDBConnStr(jobQueueDBIpAddress, jobQueueDBName, jobQueueDBUser, spool); dprintf(D_ALWAYS, "Using Job Queue File %s\n", jobQueueLogFile); dprintf(D_ALWAYS, "Using Database Type = Postgres\n"); dprintf(D_ALWAYS, "Using Database IpAddress = %s\n", jobQueueDBIpAddress?jobQueueDBIpAddress:""); dprintf(D_ALWAYS, "Using Database Name = %s\n", jobQueueDBName?jobQueueDBName:""); dprintf(D_ALWAYS, "Using Database User = %s\n", jobQueueDBUser?jobQueueDBUser:""); if(spool) { free(spool); spool = NULL; } // this function is also called when condor_reconfig is issued // and so we dont want to recreate all essential objects if(!reconfig) { prober = new ClassAdLogProber(); caLogParser = new ClassAdLogParser(); switch (dt) { case T_PGSQL: DBObj = new PGSQLDatabase(jobQueueDBConn); break; default: break;; } xactState = NOT_IN_XACT; QuillErrCode ret_st; ret_st = DBObj->connectDB(); if (ret_st == QUILL_FAILURE) { displayErrorMsg("config: unable to connect to DB--- ERROR"); EXCEPT("config: unable to connect to DB"); } /* the following will also throw an exception if the schema version is not correct */ DBObj->assertSchemaVersion(); tmp = param( "SCHEDD_NAME" ); if( tmp ) { scheddname = build_valid_daemon_name( tmp ); dprintf(D_FULLDEBUG, "scheddname %s built from param value %s\n", scheddname, tmp); free(tmp); } else { scheddname = default_daemon_name(); dprintf(D_FULLDEBUG, "scheddname built from default daemon name: %s\n", scheddname); } { /* create an entry in jobqueuepollinginfo if this schedd is the * first time being logged to database */ sql_str.formatstr("INSERT INTO jobqueuepollinginfo (scheddname, last_file_mtime, last_file_size) SELECT '%s', 0, 0 FROM dummy_single_row_table WHERE NOT EXISTS (SELECT * FROM jobqueuepollinginfo WHERE scheddname = '%s')", scheddname, scheddname); ret_st = DBObj->execCommand(sql_str.Value()); if (ret_st == QUILL_FAILURE) { dprintf(D_ALWAYS, "Insert JobQueuePollInfo --- ERROR [SQL] %s\n", sql_str.Value()); } } { /* create an entry in currency table if this schedd is the first * time being logged to database */ sql_str.formatstr("INSERT INTO currencies (datasource) SELECT '%s' FROM dummy_single_row_table WHERE NOT EXISTS (SELECT * FROM currencies WHERE datasource = '%s')", scheddname, scheddname); ret_st = DBObj->execCommand(sql_str.Value()); if (ret_st == QUILL_FAILURE) { dprintf(D_ALWAYS, "Insert Currency --- ERROR [SQL] %s\n", sql_str.Value()); } } ret_st = DBObj->commitTransaction(); if (ret_st == QUILL_FAILURE) { dprintf(D_ALWAYS, "Commit transaction failed in JobQueueDBManager::config\n"); } if (param_boolean("QUILL_MAINTAIN_DB_CONN", true) == false) { ret_st = DBObj->disconnectDB(); if (ret_st == QUILL_FAILURE) { dprintf(D_ALWAYS, "JobQueueDBManager:config: unable to disconnect database --- ERROR\n"); } } } //this function assumes that certain members have been initialized // (specifically prober and caLogParser) and so the order is important. setJobQueueFileName(jobQueueLogFile); }
bool SharedPortEndpoint::InitRemoteAddress() { // Why do we read SharedPortServer's address from a file rather // than getting it passed down to us via the environment or // having a (configurable) fixed port? Because the // SharedPortServer daemon may be listening via CCB, and its CCB // contact info may not be known as soon as it is started up // or may even change over time. // Why don't we just use a daemon client object to find the // address of the SharedPortServer daemon? Because daemon // client assumes we want the best address for _us_ to connect // to. That's not necessarily the public address that we want // to advertise for others to connect to. MyString shared_port_server_ad_file; if( !param(shared_port_server_ad_file,"SHARED_PORT_DAEMON_AD_FILE") ) { EXCEPT("SHARED_PORT_DAEMON_AD_FILE must be defined"); } FILE *fp = safe_fopen_wrapper_follow(shared_port_server_ad_file.Value(),"r"); if( !fp ) { dprintf(D_ALWAYS,"SharedPortEndpoint: failed to open %s: %s\n", shared_port_server_ad_file.Value(), strerror(errno)); return false; } int adIsEOF = 0, errorReadingAd = 0, adEmpty = 0; ClassAd *ad = new ClassAd(fp, "[classad-delimiter]", adIsEOF, errorReadingAd, adEmpty); ASSERT(ad); fclose( fp ); // avoid leaking ad when returning from this function counted_ptr<ClassAd> smart_ad_ptr(ad); if( errorReadingAd ) { dprintf(D_ALWAYS,"SharedPortEndpoint: failed to read ad from %s.\n", shared_port_server_ad_file.Value()); return false; } MyString public_addr; if( !ad->LookupString(ATTR_MY_ADDRESS,public_addr) ) { dprintf(D_ALWAYS, "SharedPortEndpoint: failed to find %s in ad from %s.\n", ATTR_MY_ADDRESS, shared_port_server_ad_file.Value()); return false; } Sinful sinful(public_addr.Value()); sinful.setSharedPortID( m_local_id.Value() ); // if there is a private address, set the shared port id on that too char const *private_addr = sinful.getPrivateAddr(); if( private_addr ) { Sinful private_sinful( private_addr ); private_sinful.setSharedPortID( m_local_id.Value() ); sinful.setPrivateAddr( private_sinful.getSinful() ); } // Next, look for alternate command strings std::string commandStrings; if (ad->EvaluateAttrString(ATTR_SHARED_PORT_COMMAND_SINFULS, commandStrings)) { m_remote_addrs.clear(); StringList sl(commandStrings.c_str()); sl.rewind(); const char *commandSinfulStr; while ((commandSinfulStr = sl.next())) { Sinful altsinful(commandSinfulStr); altsinful.setSharedPortID(m_local_id.Value()); char const *private_addr = sinful.getPrivateAddr(); if (private_addr) { Sinful private_sinful(private_addr); private_sinful.setSharedPortID(m_local_id.Value()); altsinful.setPrivateAddr(private_sinful.getSinful()); } m_remote_addrs.push_back(altsinful); } } m_remote_addr = sinful.getSinful(); return true; }