/* Takes sinful address of startd and sends it the given cmd, along with the capability and an end_of_message. */ int send_cmd_to_startd(char *sin_host, char *capability, int cmd) { ReliSock* sock = NULL; Daemon startd (DT_STARTD, sin_host, NULL); if (!(sock = (ReliSock*)startd.startCommand(cmd, Stream::reli_sock, 20))) { dprintf( D_ALWAYS, "Can't connect to startd at %s\n", sin_host ); return -1; } // send the capability ClaimIdParser idp( capability ); dprintf(D_FULLDEBUG, "send capability %s\n", idp.publicClaimId() ); if(!sock->code(capability)){ dprintf( D_ALWAYS, "sock->code(%s) failed.\n", idp.publicClaimId() ); delete sock; return -3; } // send end of message if( !sock->end_of_message() ) { dprintf( D_ALWAYS, "end_of_message failed\n" ); delete sock; return -4; } dprintf( D_FULLDEBUG, "Sent command %d to startd at %s with cap %s\n", cmd, sin_host, idp.publicClaimId() ); delete sock; return 0; }
/** * * @param argc * @param argv * @return */ int main(int argc, char** argv) { bool foreground = false; // TODO: Check for foreground flag // TODO: Add other flags // Check startup flags try { po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Display this message") ("version,v", "Display version information") ("foreground,f", "Run in foreground, logging errors to console") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); // Display help message if (vm.count("help")) { cout << desc << "\n"; return 0; } // Display version information if (vm.count("version")) { printf("[%s] - Version %s\n", argv[0], VERSION); return 0; } if (vm.count("fg")) { foreground = true; } } catch (exception &e) { printf("[%s] Exception caught getting options: %s\n", argv[0], e.what()); return 1; } // Fork to background, if we weren't told not to do it if (!foreground) { fork(); } // Setup logging openlog("tievox", LOG_PERROR | LOG_PID | LOG_CONS, LOG_DAEMON); // Setup wiringPi, using physical pin numbers. wiringPiSetupPhys(); // Run daemon Daemon *daemon = new Daemon(); int result = daemon->Run(); // Cleanup after ourselves closelog(); return result; }
int main() { Daemon d; if(d.isUnique()) { daemon(0, 0); d.run(); } return 0; }
void *daemon_launch_thread_(void *arg) { Daemon *d = (Daemon *)arg; dprintf(DBG_MINOR, "Dummy::Sensor: Launching dummy simulator thread\n"); d->running = true; d->run(); d->running = false; pthread_exit(NULL); return NULL; }
void signal_handler(int sig) { switch (sig) { case SIGHUP: dmn.reup(); break; case SIGTERM: dmn.die(); break; } }
int CollectorList::resortLocal( const char *preferred_collector ) { // Find the collector in the list that is best suited for // this host. This is determined either by // a) preferred_collector passed in // b) the collector that has the same hostname as this negotiator char * tmp_preferred_collector = NULL; if ( !preferred_collector ) { // figure out our hostname for plan b) above MyString _hostname_str = get_local_fqdn(); const char * _hostname = _hostname_str.Value(); if (!(*_hostname)) { // Can't get our hostname??? f**k off return -1; } tmp_preferred_collector = strdup(_hostname); preferred_collector = tmp_preferred_collector; // So we know to free later } // First, pick out collector(s) that is on this host Daemon *daemon; SimpleList<Daemon*> prefer_list; this->list.Rewind(); while ( this->list.Next(daemon) ) { if ( same_host (preferred_collector, daemon->fullHostname()) ) { this->list.DeleteCurrent(); prefer_list.Prepend( daemon ); } } // Walk through the list of preferred collectors, // stuff 'em in the main "list" this->list.Rewind(); prefer_list.Rewind(); while ( prefer_list.Next(daemon) ) { this->list.Prepend( daemon ); } free(tmp_preferred_collector); // Warning, preferred_collector (may have) just became invalid, so do this just before returning. return 0; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); //listenStatus = 1; //if (localPortIsOpen(QHostAddress::LocalHost,9250) || localPortIsOpen(QHostAddress::LocalHost,9251)) torStatus = -1; //if (localPortIsOpen(QHostAddress::Any, 445)) listenStatus = 0; //Database::db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE")); //Database::db->setDatabaseName("db.sqlite"); //Database::setDB(); QThread *thread = new QThread; Daemon *Tor = new Daemon; Tor->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), Tor, SLOT(startTor())); QObject::connect(Tor, SIGNAL(finished()), thread, SLOT(quit()), Qt::DirectConnection); QObject::connect(thread, SIGNAL(finished()), Tor, SLOT(deleteLater())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); QThread *thread2 = new QThread; Daemon *daemon = new Daemon; daemon->moveToThread(thread2); QObject::connect(thread2, SIGNAL(started()), daemon, SLOT(startListener())); QObject::connect(daemon, SIGNAL(ListenerStarted()), daemon, SLOT(init())); QObject::connect(daemon, SIGNAL(finished()), thread2, SLOT(quit()), Qt::DirectConnection); QObject::connect(thread2, SIGNAL(finished()), daemon, SLOT(deleteLater())); QObject::connect(thread2, SIGNAL(finished()), thread2, SLOT(deleteLater())); thread2->start(); QThread *thread3 = new QThread; JobsManager *jobsmanager = new JobsManager; QObject::connect(thread3, SIGNAL(started()), jobsmanager, SLOT(worker())); jobsmanager->moveToThread(thread3); thread3->start(); Dialog *dialog = new Dialog(); dialog->show(); QTimer::singleShot(4000, dialog, SLOT(hide())); Systray *systray = new Systray(); QObject::connect(systray, SIGNAL(exit()), &a, SLOT(quit())); QObject::connect(jobsmanager, SIGNAL(update()), systray, SLOT(update())); return a.exec(); }
void signal_handler(int sig) { switch (sig) { case SIGHUP: syslog(LOG_INFO, "Reload conf file\n"); break; case SIGTERM: syslog(LOG_INFO, "Close daemon...\n"); dmn.die(); break; } }
void* Daemon::entry(void* data){ struct sync* td = (struct sync*)data; Daemon* daemon = td->daemon; /* setup self-pipe */ if ( pipe2(daemon->pipe, O_NONBLOCK) != 0 ){ int saved = errno; Log::fatal("main", "pipe2() returned %d: %s\n", saved, strerror(saved)); td->value = saved; sem_post(&td->semaphore); return NULL; } td->value = daemon->init(); sem_post(&td->semaphore); if ( td->value != 0 ){ return NULL; } if ( td->barrier ){ pthread_barrier_wait(td->barrier); } daemon->run(); daemon->cleanup(); /* close pipe */ close(daemon->pipe[0]); close(daemon->pipe[1]); /* free resources */ sem_destroy(&td->semaphore); free(td); return 0; }
int main(int argc, char **argv) { #ifdef DAEMON /* отделяемся от родительского процесса */ int pid = fork(); switch (pid) { case 0: // child { umask(0); //777 setsid(); // Создание нового SID для дочернего процесса /*Закрываем стандартные файловые дескрипторы*/ close (STDIN_FILENO); close (STDOUT_FILENO); close (STDERR_FILENO); signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); openlog("daemon", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); #endif // CODE dmn = Daemon(); dmn.start(); exit(0); #ifdef DAEMON break; } case -1: // error! exit(EXIT_FAILURE); /*Если с PID ’ ом в с е получилось , то родительский процесс можно завершить .*/ default:// parent return 0; } #endif }
int main( int argc, char *argv[] ) { char *machine_name = 0; char *log_name = 0; char *pool=0; int i; daemon_t type = DT_MASTER; myDistro->Init( argc, argv ); config(); for( i=1; i<argc; i++ ) { if(!strcmp(argv[i],"-help")) { usage(argv[0]); exit(0); } else if(!strcmp(argv[i],"-pool")) { i++; if(!argv[i]) { fprintf(stderr,"-pool requires an argument.\n\n"); usage(argv[0]); exit(1); } pool = argv[i]; } else if(!strcmp(argv[i],"-version")) { version(); exit(0); } else if(!strcmp(argv[i],"-debug")) { dprintf_set_tool_debug("TOOL", 0); } else if(argv[i][0]=='-') { type = stringToDaemonType(&argv[i][1]); if( type == DT_NONE || type == DT_DAGMAN) { usage(argv[0]); exit(1); } } else if(argv[i][0]!='-') { if(!machine_name) { machine_name = argv[i]; } else if(!log_name) { log_name = argv[i]; } else { fprintf(stderr,"Extra argument: %s\n\n",argv[i]); usage(argv[0]); exit(1); } } else { usage(argv[0]); exit(1); } } if( !machine_name || !log_name ) { usage(argv[0]); exit(1); } Daemon *daemon; ReliSock *sock; if (pool) { DCCollector col( pool ); if( ! col.addr() ) { fprintf( stderr, "Error: %s\n", col.error() ); exit(1); } daemon = new Daemon( type, machine_name, col.addr() ); } else { daemon = new Daemon( type, machine_name ); } dprintf(D_FULLDEBUG,"Locating daemon process on %s...\n",machine_name); if(!daemon->locate()) { fprintf(stderr,"Couldn't locate daemon on %s: %s\n",machine_name,daemon->error()); exit(1); } dprintf(D_FULLDEBUG,"Daemon %s is %s\n",daemon->hostname(),daemon->addr()); sock = (ReliSock*)daemon->startCommand( DC_FETCH_LOG, Sock::reli_sock); if(!sock) { fprintf(stderr,"couldn't connect to daemon %s at %s\n",daemon->hostname(),daemon->addr()); return 1; } int commandType = DC_FETCH_LOG_TYPE_PLAIN; if ((strcmp(log_name, "HISTORY") == 0) || (strcmp(log_name, "STARTD_HISTORY") == 0)) { commandType = DC_FETCH_LOG_TYPE_HISTORY; } if ((strcmp(log_name, "STARTD.PER_JOB_HISTORY_DIR") == 0) || (strcmp(log_name, "STARTD.PER_JOB_HISTORY_DIR") == 0)) { commandType = DC_FETCH_LOG_TYPE_HISTORY_DIR; } sock->put( commandType ); sock->put( log_name ); sock->end_of_message(); if (commandType == DC_FETCH_LOG_TYPE_HISTORY_DIR) { return handleHistoryDir(sock); } int result = -1; int exitcode = 1; const char *reason=NULL; filesize_t filesize; sock->decode(); sock->code(result); switch(result) { case -1: reason = "permission denied"; break; case DC_FETCH_LOG_RESULT_SUCCESS: result = sock->get_file(&filesize,1,0); if(result>=0) { exitcode = 0; } else { reason = "connection lost"; } break; case DC_FETCH_LOG_RESULT_NO_NAME: reason = "no log file by that name"; break; case DC_FETCH_LOG_RESULT_CANT_OPEN: reason = "server was unable to access it"; break; case DC_FETCH_LOG_RESULT_BAD_TYPE: reason = "server can't provide that type of log"; break; default: reason = "unknown error"; break; } if(exitcode!=0) { fprintf(stderr,"Couldn't fetch log: %s.\n",reason); } return exitcode; }
int main( int argc, char *argv[] ) { const char *filename=0; char *pool=0; int command=-1; int i; bool use_tcp = false; bool with_ack = false; bool allow_multiple = false; param_functions *p_funcs = NULL; myDistro->Init( argc, argv ); config(); p_funcs = get_param_functions(); for( i=1; i<argc; i++ ) { if(!strcmp(argv[i],"-help")) { usage(argv[0]); exit(0); } else if(!strcmp(argv[i],"-pool")) { i++; if(!argv[i]) { fprintf(stderr,"-pool requires an argument.\n\n"); usage(argv[0]); exit(1); } pool = argv[i]; } else if(!strncmp(argv[i],"-tcp",strlen(argv[i]))) { use_tcp = true; } else if(!strncmp(argv[i],"-multiple",strlen(argv[i]))) { // We don't set allow_multiple=true by default, because // existing users (e.g. glideinWMS) have stray blank lines // in the input file. allow_multiple = true; } else if(!strcmp(argv[i],"-version")) { version(); exit(0); } else if(!strcmp(argv[i],"-debug")) { // dprintf to console Termlog = 1; p_funcs = get_param_functions(); dprintf_config ("TOOL", p_funcs); } else if(argv[i][0]!='-' || !strcmp(argv[i],"-")) { if(command==-1) { command = getCollectorCommandNum(argv[i]); if(command==-1) { fprintf(stderr,"Unknown command name %s\n\n",argv[i]); usage(argv[0]); exit(1); } } else if(!filename) { filename = argv[i]; } else { fprintf(stderr,"Extra argument: %s\n\n",argv[i]); usage(argv[0]); exit(1); } } else { fprintf(stderr,"Unknown argument: %s\n\n",argv[i]); usage(argv[0]); exit(1); } } FILE *file; ClassAdList ads; Daemon *collector; Sock *sock; switch( command ) { case UPDATE_STARTD_AD_WITH_ACK: with_ack = true; break; } if( with_ack ) { use_tcp = true; } if(!filename || !strcmp(filename,"-")) { file = stdin; filename = "(stdin)"; } else { file = safe_fopen_wrapper_follow(filename,"r"); } if(!file) { fprintf(stderr,"couldn't open %s: %s\n",filename,strerror(errno)); return 1; } while(!feof(file)) { int eof=0,error=0,empty=0; char const *delim = "\n"; if( !allow_multiple ) { delim = "***"; } ClassAd *ad = new ClassAd(file,const_cast<char *>(delim),eof,error,empty); if(error) { fprintf(stderr,"couldn't parse ClassAd in %s\n",filename); delete ad; return 1; } if( empty ) { delete ad; break; } if( !allow_multiple && ads.Length() > 0 ) { fprintf(stderr,"ERROR: failed to parse '%s' as a ClassAd attribute\n",delim); delete ad; return 1; } ads.Insert(ad); } if(ads.Length() == 0) { fprintf(stderr,"%s is empty\n",filename); return 1; } CollectorList * collectors; if ( pool ) { collector = new Daemon( DT_COLLECTOR, pool, 0 ); collectors = new CollectorList(); collectors->append (collector); } else { collectors = CollectorList::create(); } bool had_error = false; collectors->rewind(); while (collectors->next(collector)) { dprintf(D_FULLDEBUG,"locating collector %s...\n", collector->name()); if(!collector->locate()) { fprintf(stderr,"couldn't locate collector: %s\n",collector->error()); had_error = true; continue; } dprintf(D_FULLDEBUG,"collector is %s located at %s\n", collector->hostname(),collector->addr()); sock = NULL; ClassAd *ad; int success_count = 0; int failure_count = 0; ads.Rewind(); while( (ad=ads.Next()) ) { // If there's no "MyAddress", generate one.. if( !ad->Lookup( ATTR_MY_ADDRESS ) ) { MyString tmp; tmp.formatstr( "<%s:0>", my_ip_string() ); ad->Assign( ATTR_MY_ADDRESS, tmp.Value() ); } if ( use_tcp ) { if( !sock ) { sock = collector->startCommand(command,Stream::reli_sock,20); } else { // Use existing connection. sock->encode(); sock->put(command); } } else { // We must open a new UDP socket each time. delete sock; sock = collector->startCommand(command,Stream::safe_sock,20); } int result = 0; if ( sock ) { result += ad->put( *sock ); result += sock->end_of_message(); } if ( result != 2 ) { fprintf(stderr,"failed to send classad to %s\n",collector->addr()); had_error = true; failure_count++; delete sock; sock = NULL; continue; } if( with_ack ) { sock->decode(); int ok = 0; if( !sock->get(ok) || !sock->end_of_message() ) { fprintf(stderr,"failed to get ack from %s\n",collector->addr()); had_error = true; failure_count++; delete sock; sock = NULL; continue; } // ack protocol does not allow for multiple updates, // so close the socket now delete sock; sock = NULL; } success_count++; } if( sock ) { CondorVersionInfo const *ver = sock->get_peer_version(); if( !ver || ver->built_since_version(7,7,3) ) { // graceful hangup so the collector knows we are done sock->encode(); command = DC_NOP; sock->put(command); sock->end_of_message(); } delete sock; sock = NULL; } printf("Sent %d of %d ad%s to %s.\n", success_count, success_count + failure_count, success_count+failure_count == 1 ? "" : "s", collector->name()); } delete collectors; return (had_error)?1:0; }
int main (int argc, char *argv[]) { #if !defined(WIN32) install_sig_handler(SIGPIPE, (SIG_HANDLER)SIG_IGN ); #endif // initialize to read from config file myDistro->Init( argc, argv ); myName = argv[0]; config(); dprintf_config_tool_on_error(0); // The arguments take two passes to process --- the first pass // figures out the mode, after which we can instantiate the required // query object. We add implied constraints from the command line in // the second pass. firstPass (argc, argv); // if the mode has not been set, it is STARTD_NORMAL if (mode == MODE_NOTSET) { setMode (MODE_STARTD_NORMAL, 0, DEFAULT); } // instantiate query object if (!(query = new CondorQuery (type))) { dprintf_WriteOnErrorBuffer(stderr, true); fprintf (stderr, "Error: Out of memory\n"); exit (1); } // if a first-pass setMode set a mode_constraint, apply it now to the query object if (mode_constraint && ! explicit_format) { query->addANDConstraint(mode_constraint); } // set pretty print style implied by the type of entity being queried // but do it with default priority, so that explicitly requested options // can override it switch (type) { #ifdef HAVE_EXT_POSTGRESQL case QUILL_AD: setPPstyle(PP_QUILL_NORMAL, 0, DEFAULT); break; #endif /* HAVE_EXT_POSTGRESQL */ case DEFRAG_AD: setPPstyle(PP_GENERIC_NORMAL, 0, DEFAULT); break; case STARTD_AD: setPPstyle(PP_STARTD_NORMAL, 0, DEFAULT); break; case SCHEDD_AD: setPPstyle(PP_SCHEDD_NORMAL, 0, DEFAULT); break; case MASTER_AD: setPPstyle(PP_MASTER_NORMAL, 0, DEFAULT); break; case CKPT_SRVR_AD: setPPstyle(PP_CKPT_SRVR_NORMAL, 0, DEFAULT); break; case COLLECTOR_AD: setPPstyle(PP_COLLECTOR_NORMAL, 0, DEFAULT); break; case STORAGE_AD: setPPstyle(PP_STORAGE_NORMAL, 0, DEFAULT); break; case NEGOTIATOR_AD: setPPstyle(PP_NEGOTIATOR_NORMAL, 0, DEFAULT); break; case GRID_AD: setPPstyle(PP_GRID_NORMAL, 0, DEFAULT); break; case GENERIC_AD: setPPstyle(PP_GENERIC, 0, DEFAULT); break; case ANY_AD: setPPstyle(PP_ANY_NORMAL, 0, DEFAULT); break; default: setPPstyle(PP_VERBOSE, 0, DEFAULT); } // set the constraints implied by the mode switch (mode) { #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: #endif /* HAVE_EXT_POSTGRESQL */ case MODE_DEFRAG_NORMAL: case MODE_STARTD_NORMAL: case MODE_MASTER_NORMAL: case MODE_CKPT_SRVR_NORMAL: case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: case MODE_COLLECTOR_NORMAL: case MODE_NEGOTIATOR_NORMAL: case MODE_STORAGE_NORMAL: case MODE_GENERIC_NORMAL: case MODE_ANY_NORMAL: case MODE_GRID_NORMAL: case MODE_HAD_NORMAL: break; case MODE_OTHER: // tell the query object what the type we're querying is query->setGenericQueryType(genericType); free(genericType); genericType = NULL; break; case MODE_STARTD_AVAIL: // For now, -avail shows you machines avail to anyone. sprintf (buffer, "%s == \"%s\"", ATTR_STATE, state_to_string(unclaimed_state)); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addORConstraint (buffer); break; case MODE_STARTD_RUN: sprintf (buffer, "%s == \"%s\"", ATTR_STATE, state_to_string(claimed_state)); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addORConstraint (buffer); break; case MODE_STARTD_COD: sprintf (buffer, "%s > 0", ATTR_NUM_COD_CLAIMS ); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addORConstraint (buffer); break; default: break; } if(javaMode) { sprintf( buffer, "%s == TRUE", ATTR_HAS_JAVA ); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addANDConstraint (buffer); projList.AppendArg(ATTR_HAS_JAVA); projList.AppendArg(ATTR_JAVA_MFLOPS); projList.AppendArg(ATTR_JAVA_VENDOR); projList.AppendArg(ATTR_JAVA_VERSION); } if(offlineMode) { query->addANDConstraint( "size( OfflineUniverses ) != 0" ); projList.AppendArg( "OfflineUniverses" ); // // Since we can't add a regex to a projection, explicitly list all // the attributes we know about. // projList.AppendArg( "HasVM" ); projList.AppendArg( "VMOfflineReason" ); projList.AppendArg( "VMOfflineTime" ); } if(absentMode) { sprintf( buffer, "%s == TRUE", ATTR_ABSENT ); if (diagnose) { printf( "Adding constraint %s\n", buffer ); } query->addANDConstraint( buffer ); projList.AppendArg( ATTR_ABSENT ); projList.AppendArg( ATTR_LAST_HEARD_FROM ); projList.AppendArg( ATTR_CLASSAD_LIFETIME ); } if(vmMode) { sprintf( buffer, "%s == TRUE", ATTR_HAS_VM); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addANDConstraint (buffer); projList.AppendArg(ATTR_VM_TYPE); projList.AppendArg(ATTR_VM_MEMORY); projList.AppendArg(ATTR_VM_NETWORKING); projList.AppendArg(ATTR_VM_NETWORKING_TYPES); projList.AppendArg(ATTR_VM_HARDWARE_VT); projList.AppendArg(ATTR_VM_AVAIL_NUM); projList.AppendArg(ATTR_VM_ALL_GUEST_MACS); projList.AppendArg(ATTR_VM_ALL_GUEST_IPS); projList.AppendArg(ATTR_VM_GUEST_MAC); projList.AppendArg(ATTR_VM_GUEST_IP); } // second pass: add regular parameters and constraints if (diagnose) { printf ("----------\n"); } secondPass (argc, argv); // initialize the totals object if (ppStyle == PP_CUSTOM && using_print_format) { if (pmHeadFoot & HF_NOSUMMARY) ppTotalStyle = PP_CUSTOM; } else { ppTotalStyle = ppStyle; } TrackTotals totals(ppTotalStyle); // fetch the query QueryResult q; if ((mode == MODE_STARTD_NORMAL) && (ppStyle == PP_STARTD_NORMAL)) { projList.AppendArg("Name"); projList.AppendArg("Machine"); projList.AppendArg("Opsys"); projList.AppendArg("Arch"); projList.AppendArg("State"); projList.AppendArg("Activity"); projList.AppendArg("LoadAvg"); projList.AppendArg("Memory"); projList.AppendArg("ActvtyTime"); projList.AppendArg("MyCurrentTime"); projList.AppendArg("EnteredCurrentActivity"); } else if( ppStyle == PP_VERBOSE ) { // Remove everything from the projection list if we're displaying // the "long form" of the ads. projList.Clear(); // but if -attributes was supplied, show only those attributes if ( ! dashAttributes.isEmpty()) { const char * s; dashAttributes.rewind(); while ((s = dashAttributes.next())) { projList.AppendArg(s); } } } if( projList.Count() > 0 ) { char **attr_list = projList.GetStringArray(); query->setDesiredAttrs(attr_list); deleteStringArray(attr_list); } // if diagnose was requested, just print the query ad if (diagnose) { ClassAd queryAd; // print diagnostic information about inferred internal state setMode ((Mode) 0, 0, NULL); setType (NULL, 0, NULL); setPPstyle ((ppOption) 0, 0, DEFAULT); printf ("----------\n"); q = query->getQueryAd (queryAd); fPrintAd (stdout, queryAd); printf ("----------\n"); fprintf (stderr, "Result of making query ad was: %d\n", q); exit (1); } // Address (host:port) is taken from requested pool, if given. char* addr = (NULL != pool) ? pool->addr() : NULL; Daemon* requested_daemon = pool; // If we're in "direct" mode, then we attempt to locate the daemon // associated with the requested subsystem (here encoded by value of mode) // In this case the host:port of pool (if given) denotes which // pool is being consulted if( direct ) { Daemon *d = NULL; switch( mode ) { case MODE_MASTER_NORMAL: d = new Daemon( DT_MASTER, direct, addr ); break; case MODE_STARTD_NORMAL: case MODE_STARTD_AVAIL: case MODE_STARTD_RUN: case MODE_STARTD_COD: d = new Daemon( DT_STARTD, direct, addr ); break; #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: d = new Daemon( DT_QUILL, direct, addr ); break; #endif /* HAVE_EXT_POSTGRESQL */ case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: d = new Daemon( DT_SCHEDD, direct, addr ); break; case MODE_NEGOTIATOR_NORMAL: d = new Daemon( DT_NEGOTIATOR, direct, addr ); break; case MODE_CKPT_SRVR_NORMAL: case MODE_COLLECTOR_NORMAL: case MODE_LICENSE_NORMAL: case MODE_STORAGE_NORMAL: case MODE_GENERIC_NORMAL: case MODE_ANY_NORMAL: case MODE_OTHER: case MODE_GRID_NORMAL: case MODE_HAD_NORMAL: // These have to go to the collector, anyway. break; default: fprintf( stderr, "Error: Illegal mode %d\n", mode ); exit( 1 ); break; } // Here is where we actually override 'addr', if we can obtain // address of the requested daemon/subsys. If it can't be // located, then fail with error msg. // 'd' will be null (unset) if mode is one of above that must go to // collector (MODE_ANY_NORMAL, MODE_COLLECTOR_NORMAL, etc) if (NULL != d) { if( d->locate() ) { addr = d->addr(); requested_daemon = d; } else { const char* id = d->idStr(); if (NULL == id) id = d->name(); dprintf_WriteOnErrorBuffer(stderr, true); if (NULL == id) id = "daemon"; fprintf(stderr, "Error: Failed to locate %s\n", id); fprintf(stderr, "%s\n", d->error()); exit( 1 ); } } } ClassAdList result; CondorError errstack; if (NULL != ads_file) { MyString req; // query requirements q = query->getRequirements(req); const char * constraint = req.empty() ? NULL : req.c_str(); if (read_classad_file(ads_file, result, constraint)) { q = Q_OK; } } else if (NULL != addr) { // this case executes if pool was provided, or if in "direct" mode with // subsystem that corresponds to a daemon (above). // Here 'addr' represents either the host:port of requested pool, or // alternatively the host:port of daemon associated with requested subsystem (direct mode) q = query->fetchAds (result, addr, &errstack); } else { // otherwise obtain list of collectors and submit query that way CollectorList * collectors = CollectorList::create(); q = collectors->query (*query, result, &errstack); delete collectors; } // if any error was encountered during the query, report it and exit if (Q_OK != q) { dprintf_WriteOnErrorBuffer(stderr, true); // we can always provide these messages: fprintf( stderr, "Error: %s\n", getStrQueryResult(q) ); fprintf( stderr, "%s\n", errstack.getFullText(true).c_str() ); if ((NULL != requested_daemon) && ((Q_NO_COLLECTOR_HOST == q) || (requested_daemon->type() == DT_COLLECTOR))) { // Specific long message if connection to collector failed. const char* fullhost = requested_daemon->fullHostname(); if (NULL == fullhost) fullhost = "<unknown_host>"; const char* daddr = requested_daemon->addr(); if (NULL == daddr) daddr = "<unknown>"; char info[1000]; sprintf(info, "%s (%s)", fullhost, daddr); printNoCollectorContact( stderr, info, !expert ); } else if ((NULL != requested_daemon) && (Q_COMMUNICATION_ERROR == q)) { // more helpful message for failure to connect to some daemon/subsys const char* id = requested_daemon->idStr(); if (NULL == id) id = requested_daemon->name(); if (NULL == id) id = "daemon"; const char* daddr = requested_daemon->addr(); if (NULL == daddr) daddr = "<unknown>"; fprintf(stderr, "Error: Failed to contact %s at %s\n", id, daddr); } // fail exit (1); } if (noSort) { // do nothing } else if (sortSpecs.empty()) { // default classad sorting result.Sort((SortFunctionType)lessThanFunc); } else { // User requested custom sorting expressions: // insert attributes related to custom sorting result.Open(); while (ClassAd* ad = result.Next()) { for (vector<SortSpec>::iterator ss(sortSpecs.begin()); ss != sortSpecs.end(); ++ss) { ss->expr->SetParentScope(ad); classad::Value v; ss->expr->Evaluate(v); stringstream vs; // This will properly render all supported value types, // including undefined and error, although current semantic // pre-filters classads where sort expressions are undef/err: vs << ((v.IsStringValue())?"\"":"") << v << ((v.IsStringValue())?"\"":""); ad->AssignExpr(ss->keyAttr.c_str(), vs.str().c_str()); // Save the full expr in case user wants to examine on output: ad->AssignExpr(ss->keyExprAttr.c_str(), ss->arg.c_str()); } } result.Open(); result.Sort((SortFunctionType)customLessThanFunc); } // output result prettyPrint (result, &totals); delete query; return 0; }
int Globals::run(int argc, char * * argv) { Daemon daemon; char * cp; char * sockarg; name(FilePath(argv[0]).filename()); // Parse arguments. config = FilePath("/etc") + name(); for (;;) { cp = *++argv; if (!--argc || *cp != '-' || !cp[1]) break; while (*++cp) switch (*cp) { case 'c': // Configuration file. if (!--argc) usage(); config = *++argv; break; case 'd': // Increase debug level. debuglvl++; break; case 'e': // Log to stderr only. stderrOnly = true; break; case 'g': // Group. if (!--argc) usage(); group = *++argv; break; case 'j': // Jail. if (!--argc) usage(); jail = *++argv; break; case 'l': // Log to stderr too. logstd = true; break; case 'n': // Do not detach. nodaemon = true; break; case 'u': // User. if (!--argc) usage(); user = *++argv; break; default: usage(); } } if (!cp) usage(); else if (--argc) usage(); sockarg = cp; // Daemonize. // Do not change user and/or group now, since we need full // permissions for sockets. try { daemon.program(name()); daemon.lock_file(FilePath(LOCKDIR) + daemon.program()); daemon.pid_file(FilePath(RUNDIR) + (daemon.program() + ".pid")); daemon.user(user); daemon.group(group); daemon.log_to_stderr(logstd); daemon.jail(jail); daemon.block_signals(); daemon.ignore_signals(); if (!nodaemon) daemon.detach(); daemon.close_all(!stderrOnly); daemon.open_log(LOG_PID | LOG_NDELAY, LOG_MAIL); ::signal(SIGABRT, SIG_DFL); ::signal(SIGTERM, SIG_DFL); ::signal(SIGINT, SIG_DFL); ::signal(SIGILL, SIG_DFL); ::signal(SIGIOT, SIG_DFL); ::signal(SIGBUS, SIG_DFL); ::signal(SIGFPE, SIG_DFL); ::signal(SIGSEGV, SIG_DFL); ::signal(SIGSTKFLT, SIG_DFL); daemon.unblock_signals(); if (!nodaemon) { if (!daemon.lock()) { log(name() + " already running: exit"); closelog(); return 1; } daemon.write_pid(); } } catch (std::exception& e) { die = true; log(e.what(), LOG_CRIT); closelog(); return 1; } try { daemon.go_home(); // Harden our umask so that the new socket gets created // securely. umask(0077); // Register to the milter interface. socket(sockarg); debug(debuglvl); if (initialize<Undervest>() != MI_SUCCESS) { log("Cannot initialize milter interface", LOG_CRIT); closelog(); return 1; } // If we need to set the uid/gid/jail, do it now. daemon.incarcerate(); daemon.change_identity(); // Start the scheduler. schedThread = std::thread(&Scheduler::run, std::ref(sched)); // Read configuration file and domain data. reload(); if (&(*conf) == NULL) { sched.stop(); return 1; } // Start a thread to monitor and process our signals. // Note: Signals SIGTERM, SIGHUP and SIGABRT are processed // by the milter library. sigThread = std::thread(&Globals::reloader, std::ref(*this)); // Enter the milter service loop. if (start(static_cast<void *>(this)) == MI_FAILURE) throw std::runtime_error("Cannot run the milter"); } catch (std::exception& e) { die = true; sched.stop(); log(e.what(), LOG_CRIT); if (!nodaemon) { daemon.delete_pid(); daemon.delete_lock(); } closelog(); return 1; } die = true; sched.stop(); if (!nodaemon) { daemon.delete_pid(); daemon.delete_lock(); } closelog(); return 0; }
int main( int argc, char *argv[] ) { char *pool=0; char *name=0; char *address=0; char *optional_config=0; int output_mode = -1; daemon_t dtype = DT_NONE; int i; ExtArray<MyString> worklist_name; ExtArray<int> worklist_number; int worklist_count = 0; Daemon * daemon = NULL; myDistro->Init( argc, argv ); config(); for( i=1; i<argc; i++ ) { if(!strncmp(argv[i],"-help",strlen(argv[i]))) { usage(argv[0]); exit(0); } else if(!strncmp(argv[i],"-quiet",strlen(argv[i]))) { if(output_mode == -1) { output_mode = 0; } else { fprintf(stderr,"ERROR: only one output mode may be specified.\n\n"); usage(argv[0]); exit(1); } } else if(!strncmp(argv[i],"-table",strlen(argv[i]))) { if(output_mode == -1) { output_mode = 10; } else { fprintf(stderr,"ERROR: only one output mode may be specified.\n\n"); usage(argv[0]); exit(1); } } else if(!strncmp(argv[i],"-verbose",strlen(argv[i]))) { if(output_mode == -1) { output_mode = 2; } else { fprintf(stderr,"ERROR: only one output mode may be specified.\n\n"); usage(argv[0]); exit(1); } } else if(!strncmp(argv[i],"-config",strlen(argv[i]))) { i++; if(!argv[i]) { fprintf(stderr,"ERROR: -config requires an argument.\n\n"); usage(argv[0]); exit(1); } optional_config = argv[i]; } else if(!strncmp(argv[i],"-pool",strlen(argv[i]))) { i++; if(!argv[i]) { fprintf(stderr,"ERROR: -pool requires an argument.\n\n"); usage(argv[0]); exit(1); } if(address) { fprintf(stderr,"ERROR: -address cannot be used with -pool or -name.\n\n"); usage(argv[0]); exit(1); } pool = argv[i]; } else if(!strncmp(argv[i],"-name",strlen(argv[i]))) { i++; if(!argv[i]) { fprintf(stderr,"ERROR: -name requires an argument.\n\n"); usage(argv[0]); exit(1); } if(address) { fprintf(stderr,"ERROR: -address cannot be used with -pool or -name.\n\n"); usage(argv[0]); exit(1); } name = argv[i]; } else if(!strncmp(argv[i],"-type",strlen(argv[i]))) { i++; if(!argv[i]) { fprintf(stderr,"ERROR: -type requires an argument.\n\n"); usage(argv[0]); exit(1); } dtype = stringToDaemonType(argv[i]); if( dtype == DT_NONE) { fprintf(stderr,"ERROR: unrecognized daemon type: %s\n\n", argv[i]); usage(argv[0]); exit(1); } } else if(!strncmp(argv[i],"-address",strlen(argv[i]))) { i++; if(!argv[i]) { fprintf(stderr,"ERROR: -address requires an argument.\n\n"); usage(argv[0]); exit(1); } if(pool || name) { fprintf(stderr,"ERROR: -address cannot be used with -pool or -name.\n\n"); usage(argv[0]); exit(1); } address = argv[i]; } else if(!strcmp(argv[i],"-version")) { version(); exit(0); } else if(!strcmp(argv[i],"-debug")) { // dprintf to console dprintf_set_tool_debug("TOOL", 0); } else if(argv[i][0]!='-' || !strcmp(argv[i],"-")) { // a special case if(strcasecmp("ALL", argv[i]) == 0) { worklist_name[worklist_count++] = "ALLOW"; worklist_name[worklist_count++] = "READ"; worklist_name[worklist_count++] = "WRITE"; worklist_name[worklist_count++] = "NEGOTIATOR"; worklist_name[worklist_count++] = "ADMINISTRATOR"; worklist_name[worklist_count++] = "OWNER"; worklist_name[worklist_count++] = "CONFIG"; worklist_name[worklist_count++] = "DAEMON"; worklist_name[worklist_count++] = "ADVERTISE_STARTD"; worklist_name[worklist_count++] = "ADVERTISE_SCHEDD"; worklist_name[worklist_count++] = "ADVERTISE_MASTER"; } else { // an individual item to act on worklist_name[worklist_count++] = argv[i]; } } else { fprintf(stderr,"ERROR: Unknown argument: %s\n\n",argv[i]); usage(argv[0]); exit(1); } } // 1 (normal) is the default if(output_mode == -1) { output_mode = 1; } // use some default if(worklist_count == 0) { if(output_mode) { fprintf( stderr, "WARNING: Missing <authz-level | command-name | command-int> argument, defaulting to DC_NOP\n"); } worklist_name[0] = "DC_NOP"; worklist_count++; } // convert each item bool all_okay = true; for (i=0; i<worklist_count; i++) { int c = getSomeCommandFromString(worklist_name[i].Value()); if (c == -1) { if(output_mode) { fprintf(stderr, "ERROR: Could not understand TOKEN \"%s\".\n", worklist_name[i].Value()); } all_okay = false; } else { worklist_number[i] = c; } } if (!all_okay) { exit(1); } // // LETS GET TO WORK! // if(dtype == DT_NONE) { dtype = DT_SCHEDD; } if(address) { daemon = new Daemon( DT_ANY, address, 0 ); } else { if (pool) { DCCollector col( pool ); if( ! col.addr() ) { fprintf( stderr, "ERROR: %s\n", col.error() ); exit(1); } daemon = new Daemon( dtype, name, col.addr() ); } else { daemon = new Daemon( dtype, name ); } } if (!(daemon->locate())) { if(output_mode) { fprintf(stderr, "ERROR: couldn't locate %s!\n", address?address:name); } delete daemon; exit(1); } // add a check for address being null even though locate() succeeded. // this happens if the address doesn't parse. if(!daemon->addr()) { fprintf(stderr, "ERROR: unable to parse sinful string: %s\n", address); delete daemon; exit(1); } // do we need to print headers? if(output_mode == 10) { printf (" Instruction Authentication Encryption Integrity Decision Identity\n"); } // load the supplied config if specified if (optional_config) { process_config_source( optional_config, 0, "special config", NULL, true); //process_config_source( optional_config, 0, "special config", get_local_hostname().Value(), true); // ZKM TODO FIXME check the success of loading the config } all_okay = true; for(i=0; i<worklist_count; i++) { // any item failing induces failure of whole program if (!do_item(daemon, worklist_name[i], worklist_number[i], output_mode)) { all_okay = false; } } delete daemon; return (all_okay ? 0 : 1); }
int main(int argc, char **argv) { openni::Device &device = __device; openni::VideoStream &depth = __depth, &color = __color; openni::Status rc; char *prefix = strrchr(argv[0], '/')+1; char *cfgfile = new char[prefix-argv[0]+strlen(rgbdsend::config_file_name)+1]; strncpy(cfgfile, argv[0], prefix-argv[0]+1); strcpy(cfgfile+(prefix-argv[0]), rgbdsend::config_file_name); Config conf; if(conf.read(cfgfile) != 1) { printf("Config: Falling back to builtin presets.\n"); conf.setDefaults(); } delete[] cfgfile; CURL *curl = init_curl(); Daemon daemon; daemon.init(conf.daemon_port, conf.daemon_timeout); atexit(atexit_handler); init_openni(&device, &depth, &color, conf); int dw, dh, cw, ch; int tmp1, tmp2; if(!depth.getCropping(&tmp1, &tmp2, &dw, &dh)) { dw = depth.getVideoMode().getResolutionX(); dh = depth.getVideoMode().getResolutionY(); } if(!color.getCropping(&tmp1, &tmp2, &cw, &ch)) { cw = color.getVideoMode().getResolutionX(); ch = color.getVideoMode().getResolutionY(); } printf("Resolution:\nDepth: %dx%d @ %d fps\nColor: %dx%d @ %d fps\n", dw, dh, depth.getVideoMode().getFps(), cw, ch, color.getVideoMode().getFps()); std::queue<char *> onilist; Command cmd; while(1) { timeval t; t.tv_sec = conf.daemon_timeout; t.tv_usec = 0; fd_set fds; FD_ZERO(&fds); FD_SET(daemon.sock, &fds); FD_SET(daemon.csock, &fds); int in = select((daemon.csock > daemon.sock ? daemon.csock : daemon.sock)+1, &fds, 0, 0, &t); if(FD_ISSET(daemon.sock, &fds)) daemon.acceptConnection(); if(FD_ISSET(daemon.csock, &fds)) { char b[5]; int r = daemon.receiveCommand(&cmd); if(r == 0) { printf("Daemon Error: Could not receive command.\n"); daemon.closeConnection(); continue; } if(r == 2) // keep alive continue; if(strncmp(cmd.header, "capt", 4) == 0) { printf("Received capture command.\n"); char *newfile = new char[rgbdsend::filename_bufsize]; if(record_oni(newfile, rgbdsend::filename_bufsize, depth, color, conf) == true) { onilist.push(newfile); } else { delete[] newfile; } daemon.sendCommand("okay", 0, 0); } else if(strncmp(cmd.header, "thmb", 4) == 0) { printf("Received thumbnail command.\n"); unsigned char *thumbbuf = NULL; long unsigned int size = 0; capture_thumbnail(&thumbbuf, &size, color); printf("Captured thumbnail. %ld bytes\n", size); daemon.sendCommand("stmb", thumbbuf, size); // delete[] thumbbuf; seems like libjpeg handles this. but I'm not sure. } else if(strncmp(cmd.header, "quit", 4) == 0) { daemon.closeConnection(); } else { printf("Daemon Error: Received undefined command.\n"); } } if(daemon.csock != -1 && in <= 0) { daemon.closeConnection(); } if(daemon.csock == -1 && !onilist.empty()) process_onis(onilist, curl, conf); } cleanup_curl(curl); cleanup_openni(device, depth, color); }
int main(int argc, char *argv[]) { Daemon *app = new Daemon(argc, argv); return app->run(); }