Ejemplo n.º 1
0
bool afqt::recvMessage( QTcpSocket * qSocket, af::Msg * msg)
{
   char * buffer = msg->buffer();
   int bytes = readdata( qSocket, buffer, af::Msg::SizeHeader, af::Msg::SizeBuffer);
   if( bytes < af::Msg::SizeHeader)
   {
      AFERROR("qtcom::recvMessage: read message header.\n");
      return false;
   }

   msg->readHeader( bytes);

   int msgtype = msg->type();
   int datalen = msg->int32();

   if( msgtype >= af::Msg::TDATA)
   {
      buffer = msg->buffer(); // buffer may be changed to fit new size
      int readlen = datalen - bytes + af::Msg::SizeHeader;
      if( readlen > 0)
      {
         bytes = readdata( qSocket, buffer+bytes, readlen, readlen);
         if( bytes < readlen)
         {
            AFERROR("qtcom::recvMessage: read message data.\n");
            msg->setInvalid();
            return false;
         }
      }
   }
   return true;
}
Ejemplo n.º 2
0
void Dialog::caseMessage( af::Msg * msg)
{
//AFINFO("void Dialog::caseMessage( Msg msg)\n");
    if( msg == NULL)
    {
        AFERROR("Dialog::caseMessage: msg == NULL\n");
        return;
    }
#ifdef AFOUTPUT
    msg->stdOut();
#endif
    switch( msg->type())
    {
    case af::Msg::TClientExitRequest:
    case af::Msg::TVersionMismatch:
    case af::Msg::TMagicMismatch:
    {
        emit stop();
        break;
    }
    case af::Msg::TTalkId:
    {
        if( talk->getId())
        {
            if( msg->int32() != talk->getId()) connectionLost();
        }
        else
        {
            if( msg->int32())
            {
                talk->setId( msg->int32());
                qthreadClientUp->setUpMsg( new af::Msg( af::Msg::TTalkUpdateId, talk->getId(), true));
            }
            else connectionLost();
        }
        break;
    }
    case af::Msg::TTalksList:
    {
        upOnline( *msg);
        break;
    }
    case af::Msg::TTalkData:
    {
        af::MCTalkmessage amsg( msg);
        std::string user, text;
        amsg.getUser( user);
        amsg.getText( text);
        appendMessage( afqt::stoq( user), afqt::stoq( text));
        break;
    }
    default:
        AFERROR("Dialog::caseMessage Unknown message recieved.\n");
        msg->stdOut();
    }
    delete msg;
}
Ejemplo n.º 3
0
MonitorWindow::MonitorWindow():
   connected(false),
   usersSelectionCount(0),
   initialized(false )
{
   qServer = new afqt::QServer( this);
   qthreadClientUp = new afqt::QThreadClientUp( this, false, af::Environment::getMonitorUpdatePeriod(), af::Environment::getMonitorConnectRetries());
   qthreadClientSend = new afqt::QThreadClientSend( this);
   if( qServer->isInitialized() == false )
   {
      AFERROR("MonitorWindow::MonitorWindow: Server initialization failed.\n");
      return;
   }
   username = afqt::stoq( af::Environment::getUserName());
   hostname = afqt::stoq( af::Environment::getHostName());
   setWindowTitle("MonitorWindow::" + username + "@" + hostname + ":(connecting...)");


   QMenu * viewMenu = menuBar()->addMenu("View");


   QDockWidget * dock;

   dock = new QDockWidget( "Renders", this);
   rendersList = new ListRenders( dock);
   dock->setWidget( rendersList);
   addDockWidget( Qt::LeftDockWidgetArea, dock);
   viewMenu->addAction( dock->toggleViewAction());

   dock = new QDockWidget( "Users", this);
   usersList = new ListUsers( dock);
   dock->setWidget( usersList);
   addDockWidget( Qt::RightDockWidgetArea, dock);
   viewMenu->addAction( dock->toggleViewAction());

   dock = new QDockWidget( "Jobs", this);
   jobsList = new ListJobs( dock);
   dock->setWidget( jobsList);
   addDockWidget( Qt::RightDockWidgetArea, dock);
   viewMenu->addAction( dock->toggleViewAction());

   nodesList[ MTRenders ] = rendersList;
   nodesList[ MTUsers   ] = usersList;
   nodesList[ MTJobs    ] = jobsList;

   connect( usersList,         SIGNAL( itemSelectionChanged()), this, SLOT( usersSelectionChanged()));

   connect( qServer,           SIGNAL( newMsg( af::Msg*)), this, SLOT( caseMessage( af::Msg*)));
   connect( qthreadClientUp,   SIGNAL( newMsg( af::Msg*)), this, SLOT( caseMessage( af::Msg*)));
   connect( qthreadClientSend, SIGNAL( newMsg( af::Msg*)), this, SLOT( caseMessage( af::Msg*)));
   connect( qthreadClientUp,   SIGNAL( connectionLost() ), this, SLOT( connectionLost()));
   connect( qthreadClientSend, SIGNAL( connectionLost() ), this, SLOT( connectionLost()));
   monitor = new MonitorHost();
   initialized = true;
   monitor->stdOut();
   sendRegister();
}
Ejemplo n.º 4
0
bool afqt::recvMessage( QTcpSocket * qSocket, af::Msg * msg)
{
	char * buffer = msg->buffer();
	int bytes = readdata( qSocket, buffer, af::Msg::SizeHeader, af::Msg::SizeBuffer);
	if( bytes < af::Msg::SizeHeader)
	{
		AFERROR("qtcom::recvMessage: read message header.\n");
		return false;
	}

//	msg->readHeader( bytes);
	// Header offset is variable on not binary header (for example HTTP)
	int header_offset = af::processHeader( msg, bytes);
	if( header_offset < 0)
		return false;

	if( msg->type() >= af::Msg::TDATA)
	{
		buffer = msg->buffer(); // buffer may be changed to fit new size
		bytes -= header_offset;
//		int readlen = msg->dataLen() - bytes + af::Msg::SizeHeader;
		int readlen = msg->dataLen() - bytes;
		if( readlen > 0)
		{
			//bytes = readdata( qSocket, buffer+bytes, readlen, readlen);
			bytes = readdata( qSocket, buffer + af::Msg::SizeHeader + bytes, readlen, readlen);
			//bytes = ::readdata( desc, buffer + af::Msg::SizeHeader + bytes, readlen, readlen);
			if( bytes < readlen)
			{
				AFERROR("qtcom::recvMessage: read message data.\n");
				msg->setInvalid();
				return false;
			}
		}
	}
	return true;
}
Ejemplo n.º 5
0
Dialog::Dialog():
    connected(false),
    init(false )
{
    qServer = new afqt::QServer( this);
    qthreadClientUp = new afqt::QThreadClientUp( this, false, af::Environment::getTalkUpdatePeriod(), af::Environment::getTalkConnectRetries());
    qthreadClientSend = new afqt::QThreadClientSend( this);

    if( qServer->isInitialized() == false )
    {
        AFERROR("Dialog::Dialog: Server initialization failed.\n");
        return;
    }

    username = af::Environment::getUserName();
    hostname = af::Environment::getHostName();
    setWindowTitle((std::string("Talk::") + username + "@" + hostname + ":(connecting...)").c_str());

    editor = new Editor(this);
    textView  = new TextView(  this, afqt::stoq( username));
    usersList = new UsersList( this, afqt::stoq( username));

    QHBoxLayout *hlayout = new QHBoxLayout( this);
    QVBoxLayout *vlayout = new QVBoxLayout();
    hlayout->addLayout( vlayout);
    hlayout->addWidget( usersList);
    vlayout->addWidget( textView);
    vlayout->addWidget( editor);

    connect( qServer,         SIGNAL( newMsg( af::Msg*)), this, SLOT( caseMessage( af::Msg*)));
    connect( qthreadClientUp, SIGNAL( newMsg( af::Msg*)), this, SLOT( caseMessage( af::Msg*)));
    connect( qthreadClientUp, SIGNAL( connectionLost() ), this, SLOT( connectionLost()));

    connect( editor, SIGNAL( sendMessage()), this, SLOT( sendMessage()));

    connect( textView,  SIGNAL( activated()), this, SLOT( activated()));
    connect( usersList, SIGNAL( activated()), this, SLOT( activated()));
    connect( editor,    SIGNAL( activated()), this, SLOT( activated()));

    tray = new Tray( this, QString::fromUtf8( username.c_str()));
    connect( tray, SIGNAL( hideRaiseDialog()), this, SLOT( hideRaiseDialog()));

    talk = new TalkHost();
    init = true;
    talk->stdOut();

    sendRegister();
}
Ejemplo n.º 6
0
void MonitorWindow::caseMessage( af::Msg *msg)
{
//AFINFO("void MonitorWindow::caseMessage( Msg msg)\n");
   if( msg == NULL)
   {
      AFERROR("MonitorWindow::caseMessage: msg == NULL\n");
      return;
   }
#ifdef AFOUTPUT
   msg->stdOut();
#endif
   switch( msg->type())
   {
   case af::Msg::TClientExitRequest:
   case af::Msg::TVersionMismatch:
   case af::Msg::TMagicMismatch:
   {
      emit stop();
      break;
   }
   case af::Msg::TMonitorId:
   {
      if( monitor->getId() != 0 )
      {
         if( msg->int32() != monitor->getId()) connectionLost();
      }
      else
      {
         if( msg->int32() == 0)
         {
            connectionLost();
         }
         else
         {
            monitor->setId( msg->int32());
            connectionEstablished();
            af::Msg * msg = new af::Msg( af::Msg::TMonitorUpdateId, monitor->getId(), true);
            qthreadClientUp->setUpMsg( msg);
         }
      }
      break;
   }
   default:
      for( int t = 0; t < MTLast; t++) if( nodesList[t]->caseMessage( msg)) break;
   }
   delete msg;
}
Ejemplo n.º 7
0
void Task::v_start( af::TaskExec * taskexec, int * runningtaskscounter, RenderAf * render, MonitorContainer * monitoring)
{
   if( m_block->m_data->isMultiHost())
   {
      if( m_run )
         ((TaskRunMulti*)(m_run))->addHost( taskexec, render, monitoring);
      else
         m_run = new TaskRunMulti( this, taskexec, m_progress, m_block, render, monitoring, runningtaskscounter);
      return;
   }
   if( m_run)
   {
      AFERROR("Task is already running.")
      delete taskexec;
      return;
   }
   m_run = new TaskRun( this, taskexec, m_progress, m_block, render, monitoring, runningtaskscounter);
}
Ejemplo n.º 8
0
int AfList::add( AfNodeSrv *node)
{
//   m_rw_lock.WriteLock();

   int index = -1;

	std::list<AfNodeSrv*>::iterator it = std::find( nodes_list.begin(), nodes_list.begin(), node);

   if( *it == node )
   {
      AFERROR("AfList::add: node already exists.\n");
      return index;
   }
   else
   {
      if( nodes_list.size() != 0 )
      {
         std::list<AfNodeSrv*>::iterator it = nodes_list.begin();
         std::list<AfNodeSrv*>::iterator end_it = nodes_list.end();
         bool lessPriorityFound = false;
         while( it != end_it)
         {
            index++;
            if( **it >= *node ) { it++; continue;}

            nodes_list.insert( it, node);

            lessPriorityFound = true;
            break;
         }
         if( lessPriorityFound == false )
            nodes_list.push_back( node);
      }
      else
         nodes_list.push_back( node);

      index++;
      node->m_lists.push_back( this);
   }

   return index;
}
Ejemplo n.º 9
0
AfContainerLock::AfContainerLock( AfContainer* afcontainer, LockType locktype):
   container(afcontainer),
   type(locktype)
{
   switch( type )
   {
      case READLOCK:
      {
         container->ReadLock();
         break;
      }
      case WRITELOCK:
      {
         container->WriteLock();
         break;
      }
      default:
         AFERROR("AfContainerLock::AfContainerLock: invalid lock type.");
   }
}
Ejemplo n.º 10
0
const QHostAddress afqt::toQAddress( const af::Address & address)
{
   QHostAddress qaddr;
   switch( address.getFamily())
   {
      case af::Address::IPv4:
      {
         uint32_t ipv4;
         memcpy( &ipv4, address.getAddrData(), 4);
         qaddr.setAddress( htonl(ipv4));
         break;
      }
      case af::Address::IPv6:
         qaddr.setAddress( (quint8*)(address.getAddrData()));
         break;
      default:
         AFERROR("Address::setQAddress: Unknown address family.\n");
   }
   return qaddr;
}
Ejemplo n.º 11
0
int AfList::add( AfNodeSolve *node)
{
	int index = -1;

	for( std::list<AfNodeSolve*>::const_iterator it = m_nodes_list.begin(); it != m_nodes_list.end(); it++)
		if( *it == node )
		{
			AFERROR("AfList::add: node already exists.");
			return index;
		}

	if( m_nodes_list.size() != 0 )
	{
		std::list<AfNodeSolve*>::iterator it = m_nodes_list.begin();
		std::list<AfNodeSolve*>::iterator end_it = m_nodes_list.end();
		bool lessPriorityFound = false;
		while( it != end_it)
		{
			index++;
			if((*it)->priority() >= node->priority())
			{
				it++;
				continue;
			}

			m_nodes_list.insert( it, node);

			lessPriorityFound = true;
			break;
		}
		if( lessPriorityFound == false )
			m_nodes_list.push_back( node);
	}
	else
		m_nodes_list.push_back( node);

	index++;
	node->m_lists.push_back( this);

	return index;
}
Ejemplo n.º 12
0
void af::jsonActionStart( std::ostringstream & i_str, const std::string & i_type, const std::string & i_mask, const std::vector<int> & i_ids)
{
	i_str << "{\"action\":{";
	i_str << "\n\"user_name\":\"" << af::Environment::getUserName() << "\"";
	i_str << ",\n\"host_name\":\"" << af::Environment::getHostName() << "\"";
	i_str << ",\n\"type\":\"" << i_type << "\"";
	if( i_mask.size())
		i_str << ",\n\"mask\":\"" << i_mask << "\"";
	else
	{
		i_str << ",\n\"ids\":[";
		if( i_ids.size() == 0 )
		{
			AFERROR("af::jsonActionStart: And mask and ids are empty.")
		}
		for( int i = 0; i < i_ids.size(); i++)
		{
			if( i ) i_str << ",";
			i_str << i_ids[i];
		}
		i_str << "]";
	}
}
Ejemplo n.º 13
0
int afqt::readdata( QTcpSocket * qSocket, char* data, int len_min, int len_max)
{
   AFINFA("qtcom::readdata: trying to recieve %d bytes.\n", len_min);
   int bytes = 0;
   while( bytes < len_min)
   {
      qSocket->waitForReadyRead( WAITFORREADYREAD);
      int r = qSocket->read( data+bytes, len_max);
      if( r < 0)
      {
         AFERRPE("qtcom::readdata::read");
         return 0;
      }
      if( r == 0)
      {
         AFERROR("qtcom::readdata:: read 0 bytes.\n");
         return 0;
      }
      bytes += r;
      AFINFA("qtcom::readdata::read %d bytes.\n", r);
   }
   return bytes;
}
Ejemplo n.º 14
0
bool afqt::connect( const af::Address & address, QTcpSocket * qSocket)
{
   if( qSocket->state() != QAbstractSocket::ConnectedState)
   {
//      QHostAddress addr;
//      address->setQAddress( addr);
//      qSocket->connectToHost( addr, address->getPortHBO());
      qSocket->connectToHost( afqt::toQAddress( address), address.getPortHBO());
      if( qSocket->waitForConnected( WAITFORCONNECTED) == false)
      {
         AFERROR("afqt::connect: Can't connect to address:")
         printf(" %s", address.v_generateInfoString().c_str());
         printf(" Q = %s", afqt::toQAddress( address).toString().toUtf8().data());
         printf("\n");
         return false;
      }
   }
   else
   {
      AFERROR("afqt::connect: Socket seems to be already connected.\n")
   }
   return true;
}
Ejemplo n.º 15
0
void AfList::moveNodes( const std::vector<int32_t> & i_list, int i_type)
{
#ifdef AFOUTPUT
printf("AfList::moveNodes:\n");
#endif
//
//    ensure in proper type
//
   switch ( i_type)
   {
      case MoveUp: case MoveDown: case MoveTop: case MoveBottom: break;
      default:
         AFERRAR("AfList::moveNodes: Invalid type = %d\n", i_type);
         return;
   }
//
//    return if no nodes ids to move
//
   if( i_list.size() == 0)
   {
      AFERROR("AfList::moveNodes: Move nodes ids list is empty.\n");
      return;
   }

//
//    creating move nodes list
//
	std::list<AfNodeSrv*> move_list;
	std::list<AfNodeSrv*>::iterator it_begin = nodes_list.begin();
	std::list<AfNodeSrv*>::iterator it_end   = nodes_list.end();
	std::list<AfNodeSrv*>::iterator it = it_begin;
   while( it != it_end)
   {
      for( unsigned n = 0; n < i_list.size(); n++)
      {
         if( (*it)->m_node->m_id == i_list[n] )
         {
#ifdef AFOUTPUT
//printf("Found a node \"%s\"-%d\n", (*it)->getName().c_str(), (*it)->m_node->m_id);
printf("Found a node \"%s\"-%d\n", (*it)->m_node->m_name.c_str(), (*it)->m_node->m_id );
#endif
            move_list.push_back( *it);
            break;
         }
      }
      it++;
   }
//
//    return if it os no nodes to move
//
   if( move_list.size() == 0 )
   {
      AFERROR("AfList::moveNodes: Can't find nodes with such ids.\n");
      return;
   }

//
//    moving nodes in move list
//
	std::list<AfNodeSrv*>::iterator it_move_begin = move_list.begin();
	std::list<AfNodeSrv*>::iterator it_move_end   = move_list.end();
	std::list<AfNodeSrv*>::iterator it_move;
   if(( i_type == MoveDown) || ( i_type == MoveTop)) it_move = it_move_end;
   else it_move = it_move_begin;

   for(;;)
   {
      AfNodeSrv * node;
      if(( i_type == MoveDown) || ( i_type == MoveTop))
      {
         if( it_move == it_move_begin ) break;
         it_move--;
         node = *it_move;
      }
      else
      {
         if( it_move == it_move_end ) break;
         node = *it_move;
         it_move++;
      }
#ifdef AFOUTPUT
//printf("Processing node \"%s\"-%d\n", node->getName().c_str(), node->getId());
printf("Processing node \"%s\"-%d\n",  node->m_node->m_name.c_str(), node->m_node->m_id );
#endif
      std::list<AfNodeSrv*>::iterator it_insert = nodes_list.begin();
      while( it_insert != it_end)
      {
         if((*it_insert) == node) break;
         it_insert++;
      }
      if( it_insert == it_end)
      {
         AFERRAR("AfList::moveNodes: Lost node - \"%s\" - %d.\n", node->m_node->m_name.c_str(), node->m_node->m_id);
         continue;
      }

      switch ( i_type)
      {
         case MoveUp:
         {
#ifdef AFOUTPUT
printf("AfList::MoveUp:\n");
#endif
            if( it_insert == it_begin)
            {
#ifdef AFOUTPUT
printf("Node is already at top.\n");
#endif
               continue;
            }
            it_insert--;
            if( **it_insert != *node)
            {
#ifdef AFOUTPUT
printf("Node above has another priority\n");
#endif
               continue;
            }
            break;
         }
         case MoveDown:
         {
#ifdef AFOUTPUT
printf("AfList::MoveDown:\n");
#endif
            it_insert++;
            if( it_insert == it_end)
            {
#ifdef AFOUTPUT
printf("Node is already at bottom.\n");
#endif
               continue;
            }
            if( **it_insert != *node )
            {
#ifdef AFOUTPUT
printf("Node below has another priority\n");
#endif
               continue;
            }
            it_insert++;
            break;
         }
         case MoveTop:
         {
#ifdef AFOUTPUT
printf("AfList::MoveTop:\n");
#endif
            if( it_insert == it_begin)
            {
#ifdef AFOUTPUT
printf("Node is already at top.\n");
#endif
               continue;
            }
            for(;;)
            {
               it_insert--;
               if( **it_insert != *node )
               {
                  it_insert++;
                  break;
               }
               if( it_insert == it_begin) break;
            }
            break;
         }
         case MoveBottom:
         {
            it_insert++;
            if( it_insert == it_end)
            {
#ifdef AFOUTPUT
printf("Node is already at bottom.\n");
#endif
               continue;
            }
#ifdef AFOUTPUT
printf("AfList::MoveBottom:\n");
#endif
            for(;;)
            {
               if( **it_insert != *node ) break;
               it_insert++;
               if( it_insert == it_end) break;
            }
            break;
         }
      }
      if( it_insert == it_end)
      {
#ifdef AFOUTPUT
printf("Pushing node back\n");
#endif
         nodes_list.remove( node);
         nodes_list.push_back( node);
         continue;
      }
      AfNodeSrv * node_move = (*it_insert);
      if( node_move == NULL)
      {
         AFERROR("AfList::moveNodes: node_move == NULL\n");
         continue;
      }

      if( node_move == node )
      {
#ifdef AFOUTPUT
printf("Node is already at it's position.\n");
#endif
         continue;
      }

#ifdef AFOUTPUT
//printf("Inserting at \"%s\"-%d\n", node_move->getName().c_str(), node_move->getId());
printf("Inserting at \"%s\"-%d\n", node_move->m_node->m_name.c_str(), node_move->m_node->m_id );
#endif
      nodes_list.remove( node);
      nodes_list.insert( it_insert, node);
   }
}
Ejemplo n.º 16
0
Archivo: main.cpp Proyecto: RISEFX/cgru
int main(int argc, char *argv[])
{
	Py_InitializeEx(0);

   // Set signals handlers:
#ifdef WINNT
	signal( SIGINT,  sig_int);
	signal( SIGTERM, sig_int);
	signal( SIGSEGV, sig_int);
#else
	struct sigaction actint;
	bzero( &actint, sizeof(actint));
	actint.sa_handler = sig_int;
	sigaction( SIGINT,  &actint, NULL);
	sigaction( SIGTERM, &actint, NULL);
	sigaction( SIGSEGV, &actint, NULL);
	// SIGPIPE signal catch:
	struct sigaction actpipe;
	bzero( &actpipe, sizeof(actpipe));
	actpipe.sa_handler = sig_pipe;
	sigaction( SIGPIPE, &actpipe, NULL);
#endif

	// Initialize environment and try to append python path:
	af::Environment ENV( af::Environment::AppendPythonPath | af::Environment::SolveServerName, argc, argv);
	if( !ENV.isValid())
	{
		AFERROR("main: Environment initialization failed.\n");
		exit(1);
	}

	// Fill command arguments:
	ENV.addUsage("-nimby", "Set initial state to 'nimby'.");
	ENV.addUsage("-NIMBY", "Set initial state to 'NIMBY'.");
	ENV.addUsage( std::string("-cmd") + " [command]", "Run command only, do not connect to server.");
	ENV.addUsage("-res", "Check host resources only and quit.");
	ENV.addUsage("-nor", "No output redirection.");
	// Help mode, usage is alredy printed, exiting:
	if( ENV.isHelpMode() )
		return 0;

	// Check resources and exit:
	if( ENV.hasArgument("-res"))
	{
		af::Host host;
		af::HostRes hostres;
		GetResources( host, hostres, true);
		af::sleep_msec(100);
		GetResources( host, hostres);
		printf("\n");
		host.v_stdOut( true);
		hostres.v_stdOut( true);
		Py_Finalize();
		return 0;
	}

	// Run command and exit
	if( ENV.hasArgument("-cmd"))
	{
		std::string command;
		ENV.getArgument("-cmd", command);
		printf("Test command mode:\n%s\n", command.c_str());

		pid_t m_pid;
		int status;
		pid_t pid = 0;
		#ifdef WINNT
		PROCESS_INFORMATION m_pinfo;
    	if( af::launchProgram( &m_pinfo, command, "", 0, 0, 0))
			m_pid = m_pinfo.dwProcessId;
		DWORD result = WaitForSingleObject( m_pinfo.hProcess, 0);
		if ( result == WAIT_OBJECT_0)
		{
			GetExitCodeProcess( m_pinfo.hProcess, &result);
			status = result;
			pid = m_pid;
		}
		else if ( result == WAIT_FAILED )
		{
			pid = -1;
		}
		#else
		m_pid = af::launchProgram( command, "", 0, 0, 0);
		pid = waitpid( m_pid, &status, 0);
		#endif

		Py_Finalize();
		return 0;
	}

	// Create temp directory, if it does not exist:
	if( af::pathMakePath( ENV.getStoreFolder(), af::VerboseOn ) == false) return 1;

	RenderHost * render = RenderHost::getInstance();

	uint64_t cycle = 0;
	while( AFRunning)
	{
		// Update machine resources:
		if( cycle % af::Environment::getRenderUpResourcesPeriod() == 0)
			render->getResources();

		// Let tasks to do their work:
		render->refreshTasks();

		// Update server (send info and receive an answer):
		af::Msg * answer = render->updateServer();

		// React on a server answer:
		msgCase( answer, *render);

		// Close windows on windows:
		#ifdef WINNT
		render->windowsMustDie();
		#endif

		// Increment cycle:
		cycle++;
		#ifdef AFOUTPUT
		printf("=============================================================\n\n");
		#endif

		// Sleep till the next heartbeat:
		if( AFRunning )
			af::sleep_sec( af::Environment::getRenderHeartbeatSec());
	}

	delete render;

	Py_Finalize();

    AF_LOG << "Exiting render.";

	return 0;
}
Ejemplo n.º 17
0
Archivo: main.cpp Proyecto: RISEFX/cgru
void sig_pipe(int signum)
{
	AFERROR("AFRender SIGPIPE");
}
Ejemplo n.º 18
0
/** This is a main run cycle thread entry point
**/
void threadRunCycle( void * i_args)
{
   AFINFO("ThreadRun::run:")
   ThreadArgs * a = (ThreadArgs*)i_args;

while( AFRunning)
{
#ifdef _DEBUG
printf("...................................\n");
#endif
/**/
   {
//
// Lock containers:
//
AFINFO("ThreadRun::run: Locking containers...")
      AfContainerLock jLock( a->jobs,     AfContainerLock::WRITELOCK);
      AfContainerLock lLock( a->renders,  AfContainerLock::WRITELOCK);
      AfContainerLock mlock( a->monitors, AfContainerLock::WRITELOCK);
      AfContainerLock tlock( a->talks,    AfContainerLock::WRITELOCK);
      AfContainerLock ulock( a->users,    AfContainerLock::WRITELOCK);

//
// Messages reaction:
//
AFINFO("ThreadRun::run: React on incoming messages:")

   /*
      Process all messages in our message queue. We do it without
      waiting so that the job solving below can run just after.
      NOTE: I think this should be a waiting operation in a different
      thread. The job solving below should be put asleep using a
      semaphore and woke up when something changes. We need to avoid
      the Sleep() function below.
   */

   af::Msg *message;
   while( message = a->msgQueue->popMsg( af::AfQueue::e_no_wait) )
   {
      threadRunCycleCase( a, message );
   }

//
// Refresh data:
//
AFINFO("ThreadRun::run: Refreshing data:")
      a->talks    ->refresh( NULL,        a->monitors);
      a->monitors ->refresh( NULL,        a->monitors);
      a->jobs     ->refresh( a->renders,  a->monitors);
      a->renders  ->refresh( a->jobs,     a->monitors);
      a->users    ->refresh( NULL,        a->monitors);

//
// Jobs sloving:
//
		{
      AFINFO("ThreadRun::run: Solving jobs:")
      RenderContainerIt rendersIt( a->renders);
      std::list<int> rIds;
      {
         // ask every ready render to produce a task
         for( RenderAf *render = rendersIt.render(); render != NULL; rendersIt.next(), render = rendersIt.render())
         {
            if( render->isReady())
            {
               // store render Id if it produced a task
               if( a->users->solve( render, a->monitors))
               {
                  rIds.push_back( render->getId());
                  continue;
               }
            }
            // Render not solved, needed to update render status
            render->notSolved();
         }
      }

      // cycle on renders, which produced a task
		static const int renders_cycle_limit = 100000;
		int renders_cycle = 0;
		while( rIds.size())
		{
			renders_cycle++;
			if( renders_cycle > renders_cycle_limit )
			{
				AFERROR("Renders solve cycles limit reached.");
				break;
			}
         AFINFA("ThreadRun::run: Renders on cycle: %d", int(rIds.size()))
         std::list<int>::iterator rIt = rIds.begin();
         while( rIt != rIds.end())
         {
            RenderAf * render = rendersIt.getRender( *rIt);
            if( render->isReady())
            {
               if( a->users->solve( render, a->monitors))
               {
                  rIt++;
                  continue;
               }
            }
            // delete render id from list if it can't produce a task
            rIt = rIds.erase( rIt);
         }
      }
		}

//
// Wake-On-Lan:
//
		{
		AFINFO("ThreadRun::run: Wake-On-Lan:")
		RenderContainerIt rendersIt( a->renders);
		{
			for( RenderAf *render = rendersIt.render(); render != NULL; rendersIt.next(), render = rendersIt.render())
			{
				if( render->isWOLWakeAble())
				{
					if( a->users->solve( render, a->monitors))
					{
						render->wolWake( a->monitors, std::string("Automatic waking by a job."));
						continue;
					}
				}
			}
		}
		}

//
// Dispatch events to monitors:
//
AFINFO("ThreadRun::run: dispatching monitor events:")
      a->monitors->dispatch();

//
// Free Containers:
//
AFINFO("ThreadRun::run: deleting zombies:")
      a->talks    ->freeZombies();
      a->monitors ->freeZombies();
      a->renders  ->freeZombies();
      a->jobs     ->freeZombies();
      a->users    ->freeZombies();

   }

//
// Sleeping
//
AFINFO("ThreadRun::run: sleeping...")
   af::sleep_sec( 1);
}
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
   Py_InitializeEx(0);
   uint32_t env_flags = af::Environment::AppendPythonPath;
#ifdef WINNT
   env_flags = env_flags | af::Environment::Verbose; // Verbose environment initialization
#else
//
// interrupt signal catch:
   struct sigaction actint;
   bzero( &actint, sizeof(actint));
   actint.sa_handler = sig_int;
   sigaction( SIGINT,  &actint, NULL);
   sigaction( SIGTERM, &actint, NULL);
   sigaction( SIGSEGV, &actint, NULL);
// SIGPIPE signal catch:
   struct sigaction actpipe;
   bzero( &actpipe, sizeof(actpipe));
   actpipe.sa_handler = sig_pipe;
   sigaction( SIGPIPE, &actpipe, NULL);
#endif
   af::Environment ENV( env_flags, argc, argv);  // Silent environment initialization

   if( !ENV.isValid())
   {
      AFERROR("main: Environment initialization failed.")
      exit(1);
   }

   afqt::init( ENV.getWatchWaitForConnected(), ENV.getWatchWaitForReadyRead(), ENV.getWatchWaitForBytesWritten());
   afqt::QEnvironment QENV( "watch");
   if( !QENV.isValid())
   {
      AFERROR("main: QEnvironment initialization failed.")
      exit(1);
   }

   QApplication app(argc, argv);
   app.setWindowIcon( QIcon( afqt::stoq( ENV.getCGRULocation()) + "/icons/afwatch.png"));
	#if QT_VERSION >= 0x050000
	app.setStyle("fusion");
	#else
	app.setStyle("plastique");
	#endif

	MonitorHost monitor;

   Dialog dialog;
   if( !dialog.isInitialized())
   {
      AFERROR("main: Dialog initialization failed.")
      exit(1);
   }

   Watch watch( &dialog, &app);

   dialog.show();
   QObject::connect( &dialog, SIGNAL( stop()), &app, SLOT( quit()));

   int status = app.exec();

   af::destroy();
   Py_Finalize();

   AFINFA("main: QApplication::exec: returned status = %d", status)

   return status;
}
Ejemplo n.º 20
0
#include "monitorhost.h"
#include "watch.h"

#include <QApplication>
#include <QtGui/QIcon>

#define AFOUTPUT
#undef AFOUTPUT
#include "../include/macrooutput.h"

#ifndef WINNT
//####################### interrupt signal handler ####################################
#include <signal.h>
void sig_pipe(int signum)
{
   AFERROR("afanasy:: SIGPIPE:")
}
void sig_int(int signum)
{
   qApp->quit();
}
//#####################################################################################
#endif

int main(int argc, char *argv[])
{
   Py_InitializeEx(0);
   uint32_t env_flags = af::Environment::AppendPythonPath;
#ifdef WINNT
   env_flags = env_flags | af::Environment::Verbose; // Verbose environment initialization
#else