Example #1
0
ControllerManager::~ControllerManager() {
    emit(requestShutdown());
    m_pThread->wait();
    delete m_pThread;
    delete m_pControllerLearningEventFilter;
    delete m_pPresetInfoManager;
}
Example #2
0
void Initializer::initActivePlugin(const std::string& type,
                                   const std::string& name) const {
  // Use a delay, meaning the amount of milliseconds waited for extensions.
  size_t delay = 0;
  // The timeout is the maximum microseconds in seconds to wait for extensions.
  size_t timeout = atoi(FLAGS_extensions_timeout.c_str()) * 1000000;
  if (timeout < kExtensionInitializeLatencyUS * 10) {
    timeout = kExtensionInitializeLatencyUS * 10;
  }

  // Attempt to set the request plugin as active.
  Status status;
  do {
    status = Registry::setActive(type, name);
    if (status.ok()) {
      // The plugin was found, and is not active.
      return;
    }

    if (!Watcher::hasManagedExtensions()) {
      // The plugin was found locally, and is not active, problem.
      break;
    }
    // The plugin is not local and is not active, wait and retry.
    delay += kExtensionInitializeLatencyUS;
    ::usleep(kExtensionInitializeLatencyUS);
  } while (delay < timeout);

  LOG(ERROR) << "Cannot activate " << name << " " << type
             << " plugin: " << status.getMessage();
  requestShutdown(EXIT_CATASTROPHIC);
}
Example #3
0
void Initializer::initWatcher() const {
  // The watcher takes a list of paths to autoload extensions from.
  // The loadExtensions call will populate the watcher's list of extensions.
  osquery::loadExtensions();

  // Add a watcher service thread to start/watch an optional worker and list
  // of optional extensions from the autoload paths.
  if (Watcher::hasManagedExtensions() || !FLAGS_disable_watchdog) {
    Dispatcher::addService(std::make_shared<WatcherRunner>(
        *argc_, *argv_, !FLAGS_disable_watchdog));
  }

  // If there are no autoloaded extensions, the watcher service will end,
  // otherwise it will continue as a background thread and respawn them.
  // If the watcher is also a worker watchdog it will do nothing but monitor
  // the extensions and worker process.
  if (!FLAGS_disable_watchdog) {
    Dispatcher::joinServices();
    // Execution should only reach this point if a signal was handled by the
    // worker and watcher.
    auto retcode = 0;
    if (kHandledSignal > 0) {
      retcode = 128 + kHandledSignal;
    } else if (Watcher::getWorkerStatus() >= 0) {
      retcode = Watcher::getWorkerStatus();
    } else {
      retcode = EXIT_FAILURE;
    }
    requestShutdown(retcode);
  }
}
Example #4
0
// Do the real work associated with terminating a Linux task
void OsTaskLinux::doLinuxTerminateTask(UtlBoolean doForce)
{
   OsStatus res;
   pthread_t savedTaskId;

   OsSysLog::add(FAC_KERNEL, PRI_DEBUG,
                 "OsTaskLinux::doLinuxTerminateTask, deleting task thread: %x,"
                 " force = %d", (int)mTaskId, doForce);

   // if there is no low-level task, or entry in the name database, just return
   if ((mState != UNINITIALIZED) && ((int)mTaskId != 0))
   {
      // DEBUGGING HACK:  Suspend requestor if target is suspended $$$
      while (isSuspended())
      {
         suspend();
      }
      
      if (!doForce)
      {
         // We are being well behaved and will wait until the task is no longer
         // safe from deletes.  A task is made safe from deletes by acquiring
         // a read lock on its mDeleteGuard. In order to delete a task, the
         // application must acquire a write lock. This will only happen after
         // all of the read lock holders have released their locks.
         res = mDeleteGuard.acquireWrite();
         assert(res == OS_SUCCESS);
      }

      savedTaskId = mTaskId; // taskUnregister sets mTaskId to zero;
      taskUnregister();
      
      // Send the thread the actual cancellation request.
      if (mState == STARTED)
      {
         requestShutdown();
         /* maybe replace this with a call to waitUntilShutDown() ? */
         for(int i = 0; i < 10 && isShuttingDown(); i++)
         {
            delay(100);
         }
      }
      if (mState == SHUTTING_DOWN)
      {
         if (savedTaskId != 0)
         {
            pthread_cancel(savedTaskId);
         }
      }
      
      if (!doForce)
      {
         res = mDeleteGuard.releaseWrite();     // release the write lock
         assert(res == OS_SUCCESS);
      }
   }

   mState = UNINITIALIZED;
}
Example #5
0
ControllerManager::ControllerManager(ConfigObject<ConfigValue>* pConfig)
        : QObject(),
          m_pConfig(pConfig),
          // WARNING: Do not parent m_pControllerLearningEventFilter to
          // ControllerManager because the CM is moved to its own thread and runs
          // its own event loop.
          m_pControllerLearningEventFilter(new ControllerLearningEventFilter()),
          m_pollTimer(this) {
    qRegisterMetaType<ControllerPresetPointer>("ControllerPresetPointer");

    // Create controller mapping paths in the user's home directory.
    QString userPresets = userPresetsPath(m_pConfig);
    if (!QDir(userPresets).exists()) {
        qDebug() << "Creating user controller presets directory:" << userPresets;
        QDir().mkpath(userPresets);
    }
    QString localPresets = localPresetsPath(m_pConfig);
    if (!QDir(localPresets).exists()) {
        qDebug() << "Creating local controller presets directory:" << localPresets;
        QDir().mkpath(localPresets);
    }

    // Initialize preset info parsers
    m_pPresetInfoManager = new PresetInfoEnumerator(m_pConfig);

    // Instantiate all enumerators
    m_enumerators.append(new PortMidiEnumerator());
#ifdef __HSS1394__
    m_enumerators.append(new Hss1394Enumerator());
#endif
#ifdef __BULK__
    m_enumerators.append(new BulkEnumerator());
#endif
#ifdef __HID__
    m_enumerators.append(new HidEnumerator());
#endif

    m_pollTimer.setInterval(kPollIntervalMillis);
    connect(&m_pollTimer, SIGNAL(timeout()),
            this, SLOT(pollDevices()));

    m_pThread = new QThread;
    m_pThread->setObjectName("Controller");

    // Moves all children (including the poll timer) to m_pThread
    moveToThread(m_pThread);

    // Controller processing needs to be prioritized since it can affect the
    // audio directly, like when scratching
    m_pThread->start(QThread::HighPriority);

    connect(this, SIGNAL(requestSetUpDevices()),
            this, SLOT(slotSetUpDevices()));
    connect(this, SIGNAL(requestShutdown()),
            this, SLOT(slotShutdown()));
    connect(this, SIGNAL(requestSave(bool)),
            this, SLOT(slotSavePresets(bool)));
}
// stop the BDM thread
void BlockDataManagerThread::shutdownAndWait()
{
   requestShutdown();
   
   if (pimpl->tID)
   {
      pthread_join(pimpl->tID, nullptr);
      pimpl->tID=0;

   }
}
Example #7
0
void TaoListeningTask::shutdownListeners()
{
        requestShutdown();

        // For each client request shutdown
        int iteratorHandle = agentList.getIteratorHandle();
        TaoTransportAgent* pAgent = NULL;
        while ((pAgent = (TaoTransportAgent*)agentList.next(iteratorHandle)))
        {
                pAgent->requestShutdown();
        }
        agentList.releaseIteratorHandle(iteratorHandle);
}
Example #8
0
// Wait until the task is shut down and the run method has exited.
// Most sub classes of OsTask should call this method in
// the destructor before deleting any members which are
// accessed by the run method.
UtlBoolean OsTaskBase::waitUntilShutDown(int milliSecToWait)
{
   // If task is already shut down, just return.
   if (isShutDown())
      return TRUE;

   UtlString taskName = getName();

   if (isStarted() || isUnInitialized())
   {
      requestShutdown();  // ask the task to shut itself down
      yield();            // yield the CPU so the target task can terminate
   }

   // wait up to another nineteen seconds (20 total) for the task to terminate
   // printing out a console complaint every second
   if (isShuttingDown())
   {
      int i;

      // wait up to a second for the task to terminate.
      for (i = 0; (i < 10) && isShuttingDown(); i++)
         delay(milliSecToWait/200);         // wait 1/10 second

      for (i = 1; (i < 20) && isShuttingDown(); i++)
      {
         OsSysLog::add(FAC_KERNEL, PRI_WARNING, "Task: %s failed to terminate after %f seconds",
                  taskName.data(), (milliSecToWait * i) / 20000.0);
         delay(milliSecToWait/20);
      }

      // if still no response from the task, assume it is unresponsive and
      // destroy the object
      if (isShuttingDown())
      {
         OsSysLog::add(FAC_KERNEL, PRI_ERR, "Task: %s failed to terminate after %f seconds",
                  taskName.data(), milliSecToWait / 1000.0);
      }
   }

   // Do not exit if not shut down
   while (isShuttingDown())
   {
         OsSysLog::add(FAC_KERNEL, PRI_ERR, "Task: %s failed to terminate, waiting...",
                  taskName.data());
         delay(300000);
   }

   return(isShutDown());
}
void shutdownCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result)
{
  int num_params = 0;
  if (params.getType() == XmlRpc::XmlRpcValue::TypeArray)
    num_params = params.size();
  if (num_params > 1)
  {
    std::string reason = params[1];
    ROS_WARN("Shutdown request received.");
    ROS_WARN("Reason given for shutdown: [%s]", reason.c_str());
    requestShutdown();
  }

  result = xmlrpc::responseInt(1, "", 0);
}
Example #10
0
// Destructor
SipClient::~SipClient()
{
    Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                  "SipClient[%s]::~ called",
                  mName.data());

    // Tell the associated thread to shut itself down.
    requestShutdown();

    // Do not delete the event listers, as they are not subordinate.

    // Free the socket
    if(mClientSocket)
    {
        // Close the socket to unblock the run method
        // in case it is blocked in a waitForReadyToRead or
        // a read on the mClientSocket.  This should also
        // cause the run method to exit.
        if (!mbSharedSocket)
        {
           Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "SipClient[%s]::~ %p socket %p closing %s socket",
                         mName.data(), this,
                         mClientSocket, OsSocket::ipProtocolString(mSocketType));
           mClientSocket->close();
        }

        // Wait for the task to exit so that it does not
        // reference the socket or other members after they
        // get deleted.
        if(isStarted() || isShuttingDown())
        {
            waitUntilShutDown();
        }

        if (!mbSharedSocket)
        {
            delete mClientSocket;
        }
        mClientSocket = NULL;
    }
    else if(isStarted() || isShuttingDown())
    {
        // It should not get here but just in case
        waitUntilShutDown();
    }
}
Example #11
0
void Initializer::waitForWatcher() const {
  // If there are no autoloaded extensions, the watcher service will end,
  // otherwise it will continue as a background thread and respawn them.
  // If the watcher is also a worker watchdog it will do nothing but monitor
  // the extensions and worker process.
  if (!FLAGS_disable_watchdog) {
    Dispatcher::joinServices();
    // Execution should only reach this point if a signal was handled by the
    // worker and watcher.
    auto retcode = 0;
    if (kHandledSignal > 0) {
      retcode = 128 + kHandledSignal;
    } else if (Watcher::getWorkerStatus() >= 0) {
      retcode = Watcher::getWorkerStatus();
    } else {
      retcode = EXIT_FAILURE;
    }
    requestShutdown(retcode);
  }
}
Example #12
0
void Initializer::initActivePlugin(const std::string& type,
                                   const std::string& name) const {
  auto status = applyExtensionDelay(([type, name](bool& stop) {
    auto rs = RegistryFactory::get().setActive(type, name);
    if (rs.ok()) {
      // The plugin was found, and is now active.
      return rs;
    }

    if (!Watcher::hasManagedExtensions()) {
      // The plugin must be local, and is not active, problem.
      stop = true;
    }
    return rs;
  }));

  if (!status.ok()) {
    LOG(ERROR) << "Cannot activate " << name << " " << type
               << " plugin: " << status.getMessage();
    requestShutdown(EXIT_CATASTROPHIC);
  }
}
Example #13
0
void Initializer::requestShutdown(int retcode, const std::string& system_log) {
  systemLog(system_log);
  requestShutdown(retcode);
}
Example #14
0
// Handle a timer service request.
// Return TRUE if the request was handled, otherwise FALSE.
UtlBoolean OsTimerTask::handleMessage(OsMsg& rMsg)
{
   // Process a message.

   // If not an OS_TIMERTASK_COMMAND message, return FALSE to indicate it should be
   // passed to our superclass.
   if (rMsg.getMsgType() != OsMsg::OS_TIMERTASK_COMMAND)
   {
      return FALSE;
   }

   // Process an OS_TIMERTASK_COMMAND message.

   OsTimerTaskCommandMsg& message = dynamic_cast <OsTimerTaskCommandMsg&> (rMsg);

   // Process a OS_TIMER_SHUTDOWN message, which is special
   if (message.getMsgSubType() == OsTimerTaskCommandMsg::OS_TIMER_SHUTDOWN)
   {
      OsSysLog::add(FAC_KERNEL, PRI_INFO,
                    "OsTimerTask::handleMessage OS_TIMER_SHUTDOWN seen, mState = %d",
                    mState);
      // Verify that there are no other requests in the timer task's queue.
      assert(getMessageQueue()->isEmpty());

      // Stop all the timers in the timer queue.
      OsTimer* link;
      for (OsTimer* timer = mTimerQueue; timer; timer = link)
      {
         // This lock should never block, since the application should not
         // be accessing the timer.
         OsLock lock(timer->mBSem);

         // Check that the application and task states are the same.
         // If they aren't, the application is mucking with the timer.
         assert(timer->mTaskState == timer->mApplicationState);
         // Increment the state fields, to show the timer is stopped.
         timer->mTaskState =
            timer->mApplicationState = timer->mApplicationState + 1;

         // Get the link field.
         link = timer->mTimerQueueLink;

         // Clear the link field of the timer.
         timer->mTimerQueueLink = 0;
      }
      // Empty the timer queue.
      mTimerQueue = 0;

      // Change mState so the main loop will exit.
      requestShutdown();

      // Signal the event so our caller knows we're done.
      message.getEventP()->signal(0);
      OsSysLog::add(FAC_KERNEL, PRI_INFO,
                    "OsTimerTask::handleMessage OS_TIMER_SHUTDOWN seen, mState = %d",
                    mState);
      return TRUE;
   }

   OsTimer* timer = message.getTimerP();
#ifndef NDEBUG
   CHECK_VALIDITY(timer);
#endif
   unsigned int applicationState;
   OsTimer::Time expiresAt;
   UtlBoolean periodic;
   OsTimer::Interval period;
   {
      OsLock lock(timer->mBSem);

      // mDeleting may be true, if the destructor has started running.

      // Decrement the outstanding message count.
      timer->mOutstandingMessages--;

      // Get mApplicationState.
      applicationState = timer->mApplicationState;

      // Get the timing information.
      expiresAt = timer->mExpiresAt;
      periodic = timer->mPeriodic;
      period = timer->mPeriod;
   }	    

   // Determine whether the timer needs to be stopped.
   // (The comparison between applicationState and mTaskState is really
   // ">", taking into account wraparound.  But that is difficult to
   // implement, so given that mApplicationState is always >= mTaskState
   // by design, we can use "!=".)
   if (applicationState != timer->mTaskState &&
       OsTimer::isStarted(timer->mTaskState))
   {
      // Stop the timer.
      removeTimer(timer);
   }
   // Determine whether the timer needs to be started.
   if (applicationState != timer->mTaskState &&
       OsTimer::isStarted(applicationState))
   {
      // Start the timer.
      // Set the saved timing information.
      timer->mQueuedExpiresAt = expiresAt;
      timer->mQueuedPeriodic = periodic;
      timer->mQueuedPeriod = period;
      insertTimer(timer);
   }
	    
   // Update the task state.
   timer->mTaskState = applicationState;

   switch (message.getMsgSubType())
   {
   case OsTimerTaskCommandMsg::OS_TIMER_UPDATE:
      // No further processing is needed.
      break;

   case OsTimerTaskCommandMsg::OS_TIMER_UPDATE_SYNC:
      // If it is an UPDATE_SYNC message, signal the event.
      message.getEventP()->signal(0);
      break;

   case OsTimerTaskCommandMsg::OS_TIMER_UPDATE_DELETE:
      // If it is an UPDATE_DELETE, delete the timer.

      // Timer will not be accessed by any other thread, so we
      // can access it without locking.
#ifndef NDEBUG
      // Deletion in progress.
      assert(timer->mDeleting);
#endif
      // Timer should be stopped already.
      assert(OsTimer::isStopped(timer->mApplicationState));
      // No outstanding messages.
      assert(timer->mOutstandingMessages == 0);
#ifndef NDEBUG
      // Set mDeleting to FALSE to the destructor won't fail.
      timer->mDeleting = FALSE;
#endif

      // Use ordinary destructor to delete the timer.
      // Because of the state of the timer, it will not send a message to
      // the timer task.
      delete timer;
      break;

   default:
      // Catch invalid values.
      assert(FALSE);
   }

   return TRUE;
}
Example #15
0
void SipTlsServer::shutdownListener()
{
    requestShutdown();
    shutdownClients();
}
Example #16
0
OsPooledTask::~OsPooledTask()
{
  requestShutdown();
}
Example #17
0
/*********************************************
		SDL event loop
**********************************************/
void Application::processEvents(){

	SDL_Event event;
   
    while ( SDL_PollEvent( &event ) ){
    
	    switch( event.type ){
					      
		case SDL_VIDEORESIZE:
			mSurface.onResize(event.resize.w, event.resize.h);
		    break;
		
		case SDL_QUIT:
		    //handle quit requests
		    requestShutdown();
		    break;
		
		case SDL_MOUSEBUTTONDOWN:			
			onMouseEvent(event.button.button, event.type); 			
			break;	
			
		case SDL_MOUSEBUTTONUP:
			onMouseEvent(event.button.button, event.type); 
			break;	
			
		case SDL_KEYDOWN:
			onKeyEvent(event.key.keysym.sym, event.type);
			break;
		
		case SDL_KEYUP:
			onKeyEvent(event.key.keysym.sym, event.type);
			break;
		
		default:
		    break;
		}
	}
	
	/*
    if (!done){
    
    	//Do one frames worth of work and figure out the length of time
    	uint32_t startTime = SDL_GetTicks();
		renderMain();
		updateMain();
		uint32_t endTime = SDL_GetTicks();
		
		//Figure out the scaling factor for FPS-independent movement
		uint32_t diff = endTime - startTime;
		fTimeScale = (float)diff * fTimeScaleScale;
		
		//Every hour, do a cleanup
		if(fCleanupTimer < 0.0f){
			ps()->doPeriodicCleanup();				
			fCleanupTimer = CLEANUP_TIMER;
		}
		
		//Update our various timers
		fCleanupTimer -= fTimeScale;
		fUptime += fTimeScale;
		fParticleFPS = fTimeScale;
	}
	*/
	
}
Example #18
0
void Initializer::start() const {
  // Load registry/extension modules before extensions.
  osquery::loadModules();

  // Pre-extension manager initialization options checking.
  // If the shell or daemon does not need extensions and it will exit quickly,
  // prefer to disable the extension manager.
  if ((FLAGS_config_check || FLAGS_config_dump) &&
      !Watcher::hasManagedExtensions()) {
    FLAGS_disable_extensions = true;
  }

  // A watcher should not need access to the backing store.
  // If there are spurious access then warning logs will be emitted since the
  // set-allow-open will never be called.
  if (!isWatcher()) {
    DatabasePlugin::setAllowOpen(true);
    // A daemon must always have R/W access to the database.
    DatabasePlugin::setRequireWrite(tool_ == OSQUERY_TOOL_DAEMON);
    if (!DatabasePlugin::initPlugin()) {
      LOG(ERROR) << RLOG(1629) << binary_
                 << " initialize failed: Could not initialize database";
      auto retcode = (isWorker()) ? EXIT_CATASTROPHIC : EXIT_FAILURE;
      requestShutdown(retcode);
    }
  }

  // Bind to an extensions socket and wait for registry additions.
  // After starting the extension manager, osquery MUST shutdown using the
  // internal 'shutdown' method.
  osquery::startExtensionManager();

  // Then set the config plugin, which uses a single/active plugin.
  initActivePlugin("config", FLAGS_config_plugin);

  // Run the setup for all lazy registries (tables, SQL).
  Registry::setUp();

  if (FLAGS_config_check) {
    // The initiator requested an initialization and config check.
    auto s = Config::getInstance().load();
    if (!s.ok()) {
      std::cerr << "Error reading config: " << s.toString() << "\n";
    }
    // A configuration check exits the application.
    // Make sure to request a shutdown as plugins may have created services.
    requestShutdown(s.getCode());
  }

  if (FLAGS_database_dump) {
    dumpDatabase();
    requestShutdown();
  }

  // Load the osquery config using the default/active config plugin.
  auto s = Config::getInstance().load();
  if (!s.ok()) {
    auto message = "Error reading config: " + s.toString();
    if (tool_ == OSQUERY_TOOL_DAEMON) {
      LOG(WARNING) << message;
    } else {
      LOG(INFO) << message;
    }
  }

  // Initialize the status and result plugin logger.
  if (!FLAGS_disable_logging) {
    initActivePlugin("logger", FLAGS_logger_plugin);
  }
  initLogger(binary_);

  // Initialize the distributed plugin, if necessary
  if (!FLAGS_disable_distributed) {
    if (Registry::exists("distributed", FLAGS_distributed_plugin)) {
      initActivePlugin("distributed", FLAGS_distributed_plugin);
    }
  }

  // Start event threads.
  osquery::attachEvents();
  EventFactory::delay();
}
Example #19
0
void LoginState::requestQuit()
{
  requestShutdown();
}