Beispiel #1
0
int
Sender::on_data_sent(ACE_Message_Block & mb,
                     const ACE_INET_Addr & remote)
{
  int nbytes = mb.length ();

  if (nbytes == 0)
    {
      mb.release();
      return 0;
    }
  
  if (this->io_count_r_ == 0)
    this->initiate_read();

  
  if (this->io_count_w_ == 0)
    {
      mb.rd_ptr(mb.base());
      mb.wr_ptr(mb.base() + nbytes);

      this->initiate_write(mb, remote);
    }
  
  return 0;
}
Beispiel #2
0
int
JAWS_TPOOL_Concurrency::getq (JAWS_Protocol_Handler *&ph)
{
  ph = 0;

  JAWS_CONCURRENCY_TASK *task = this;

  if (this->shutdown_task_ && task->msg_queue ()->message_count () == 0)
    return -1;

  ACE_Message_Block *mb = 0;

  int result = task->getq (mb);

  if (result != -1)
    {
      ph = (JAWS_Protocol_Handler *) mb->base ();

      if (ph == 0)
        {
          // Shutdown this task;
          this->shutdown_task_ = 1;
          if (this->number_of_threads_ && this->number_of_threads_-- > 1)
            {
              task->putq (mb);
              result = -1;
            }
        }
    }

  return result;
}
Beispiel #3
0
int
Sender::initiate_write (void)
{
  if ( this->msg_queue ()->message_count () < 20) // flow control
    {
      size_t nbytes = ACE_OS::strlen (send_buf_);

      ACE_Message_Block *mb = 0;
      ACE_NEW_RETURN (mb,
                      ACE_Message_Block (nbytes+8),
                      -1);

      mb->init (send_buf_, nbytes);
      mb->rd_ptr (mb->base ());
      mb->wr_ptr (mb->base ());
      mb->wr_ptr (nbytes);

      ACE_Time_Value tv = ACE_Time_Value::zero;

      int qcount =this->putq (mb, & tv);

      if (qcount <= 0)
        {
          ACE_Message_Block::release (mb);
          return -1;
        }
    }

  return initiate_io (ACE_Event_Handler::WRITE_MASK);
}
Beispiel #4
0
void
PConnection::trace_buffers(const Buffer_Info& buf_info,
                           size_t xfer_bytes,
                           bool   flg_read)
{
  int   iovcnt = buf_info.get_iov_count ();
  if (iovcnt < 0)   // ACE_Message_Block
    {
      ACE_Message_Block * mb = buf_info.get_message_block_ptr();

      for (int i=0; 
            xfer_bytes != 0 && mb != 0 ;
            mb = mb->cont (), ++i)
      {
        char * ptr = flg_read ? mb->wr_ptr () : mb->rd_ptr ();
        size_t len = flg_read ? mb->length () : (ptr - mb->base ());
        if (len > xfer_bytes)
            len = xfer_bytes;

        ptr -= len;
        xfer_bytes -=len;

        ACE_DEBUG ((LM_DEBUG,
          ACE_TEXT ("message_block [%d] length=%d:\n"), i, (int)len));

        ACE_HEX_DUMP ((LM_DEBUG, ptr, len));
      }
    }
  else if (iovcnt > 0) // iovec 
    {
      iovec *iov = buf_info.get_iov ();
      for (int i=0; xfer_bytes != 0 && i < iovcnt; ++i)
      {
        char * ptr = (char*) iov[i].iov_base;
        size_t len = iov[i].iov_len;
        if (len > xfer_bytes)
            len = xfer_bytes;

        ptr -= len;
        xfer_bytes -=len;

        ACE_DEBUG ((LM_DEBUG,
          ACE_TEXT ("iov[%d] length=%d:\n"), i, (int)len));

        ACE_HEX_DUMP ((LM_DEBUG, ptr, len));
      }
    }
  else // simple  buffer
    {
      char *ptr = buf_info.get_buffer ();
      ACE_DEBUG ((LM_DEBUG,
          ACE_TEXT ("buffer length=%d:\n"), (int)xfer_bytes));

      ACE_HEX_DUMP ((LM_DEBUG, ptr, xfer_bytes));
    }
  ACE_DEBUG ((LM_DEBUG,
    ACE_TEXT ("**** end of buffers ****************\n")));
}
Beispiel #5
0
void
TAO_ConstantDef_i::value_i (const CORBA::Any &value)
{
  CORBA::TypeCode_var my_tc =
    this->type_i ();

  CORBA::TypeCode_var val_tc = value.type ();

  CORBA::Boolean const equal_tc =
    my_tc.in ()->equal (val_tc.in ());

  if (!equal_tc)
    {
      return;
    }

  ACE_Message_Block *mb = 0;
  TAO::Any_Impl *impl = value.impl ();

  if (impl->encoded ())
    {
      TAO::Unknown_IDL_Type *unk =
        dynamic_cast<TAO::Unknown_IDL_Type *> (impl);

      mb = unk->_tao_get_cdr ().steal_contents ();
    }
  else
    {
      TAO_OutputCDR out;
      impl->marshal_value (out);
      TAO_InputCDR in (out);
      mb = in.steal_contents ();
    }
  ACE_Auto_Ptr<ACE_Message_Block> safe (mb);

  CORBA::TCKind kind = val_tc->kind ();

  switch (kind)
  {
    // The data for these types will be aligned to an 8-byte
    // boundary, while the rd_ptr may not.
    case CORBA::tk_double:
    case CORBA::tk_ulonglong:
    case CORBA::tk_longlong:
    case CORBA::tk_longdouble:
      mb->rd_ptr (ACE_ptr_align_binary (mb->rd_ptr (),
                                        ACE_CDR::MAX_ALIGNMENT));
      break;
    default:
      break;
  }

  mb->crunch ();
  this->repo_->config ()->set_binary_value (this->section_key_,
                                            "value",
                                            mb->base (),
                                            mb->length ());
}
Beispiel #6
0
int
DSession::post_message (void)
{
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, monitor, this->lock_, -1 );

  if (this->get_pending_r_() == 0 &&
      this->get_pending_w_() == 0)
      return 0;  // too late


  ACE_Message_Block *mb = 0;

  ACE_NEW_RETURN (mb,
                  ACE_Message_Block (80),
                  -1);

  char str[80];

  int len = ACE_OS::snprintf(str, 
                             sizeof(str),
                             "Message to %s=%d", 
                             this->get_name (),
                             this->index ());


  mb->rd_ptr(mb->base());
  mb->wr_ptr(mb->base() + len);
  ACE_OS::strcpy(mb->rd_ptr(), str);

  TRB_Asynch_User_Result result (this, 
                                 ACE_INVALID_HANDLE, // handle
                                 *mb,   
                                 0,  // bytes requested
                                 0,  // offset low
                                 0,  // offset high
                                 (const void*) this->index (),
                                 0,  // completion key
                                 0,  // priority
                                 0); // signal_number
  if (this->owner_.task().get_proactor(0)->post_completion (result) < 0)
    {
       mb->release ();
       ACE_ERROR_RETURN((LM_ERROR,
                       ACE_TEXT ("(%t) %s=%d attempt POST failed\n"),
                       this->get_name(),
                       this->index()),
                       -1);
    }

  this->post_count_ ++;
  return 0;
}
void
displayChain(ACE_Message_Block* chain)
{
  //std::cout << "DISPLAYING CHAIN" << std::endl;
  for (ACE_Message_Block* current = chain; current; current = current->cont()) {
    if (current->length() > 0) {
      //std::cout << "DISPLAYING BLOCK" << std::endl;
      ACE_TCHAR buffer[4096];
      ACE::format_hexdump(current->base(), current->length(), buffer, sizeof(buffer));
      std::cout << buffer << std::endl;
    }
  }
}
Beispiel #8
0
int
Sender::initiate_write_stream ()
{
  if (this->flg_cancel_ != 0)
    {
      return -1;
    }

  if (this->get_ref_cnt_w() != 0)
    {
      return 0; // todo: queue it
    }


  u_int blksize = this->config().s_blksize();
  u_int limit   = this->config().xfer_limit();
  u_int winsize = this->config().w_size();

  if (limit != 0 && this->total_snd_ >= limit)
    {
      this->shutdown_i ();
      return 0;
    }

  u_long delta = this->total_snd_- this->total_rcv_;
  if (delta > winsize)
     return 0;

  ACE_Message_Block *mb = 0;

  ACE_NEW_RETURN (mb,
                  ACE_Message_Block (blksize+1),
                  -1);

  mb->copy(complete_message);
  mb->copy("\0");
  mb->wr_ptr(mb->base() + blksize);
 

  if (this->stream_.write (*mb, mb->length ()) == -1)
    {
      mb->release ();
      this->cancel_i();
      return -1;
    }

  this->ref_cnt_w_++;
  this->total_w_++;
  return 0;
}
int CSenceManager::svc(void)
{
	ACE_Message_Block* mb = NULL;
	ACE_Time_Value xtime;

	ACE_OS::sleep(1);

	while(IsRun())
	{
		mb = NULL;
		//xtime = ACE_OS::gettimeofday() + ACE_Time_Value(0, MAX_MSG_PUTTIMEOUT);
		if(getq(mb, 0) == -1)
		{
			OUR_DEBUG((LM_ERROR,"[CMessageService::svc] PutMessage error errno = [%d].\n", errno));
			m_blRun = false;
			break;
		}
		if (mb == NULL)
		{
			continue;
		}

		//处理消息
		_QueueMessage* pQueueMessage = *((_QueueMessage**)mb->base());
		if (! pQueueMessage)
		{
			OUR_DEBUG((LM_ERROR,"[CMessageService::svc] mb msg == NULL CurrthreadNo=[0]!\n"));
			m_objMessageBlockPool.Delete(mb);
			m_objMessagePool.Delete(pQueueMessage);
			continue;
		}

		ACE_hrtime_t tvBegin = ACE_OS::gethrtime();
		ProcessMessage(pQueueMessage);
		m_u4TimeCost += (uint32)(ACE_OS::gethrtime() - tvBegin);
		m_u4ProCount++;

		if(m_u4ProCount == 6000)
		{
			OUR_DEBUG((LM_ERROR,"[CMessageService::svc]m_u4ProCount = %d,m_u4TimeCost = %d!\n", m_u4ProCount, m_u4TimeCost));
		}

		m_objMessageBlockPool.Delete(mb);
		m_objMessagePool.Delete(pQueueMessage);
	}

	OUR_DEBUG((LM_INFO,"[CSenceManager::svc] svc finish!\n"));
	return 0;
}
Beispiel #10
0
int CMessageService::svc(void)
{
    ACE_Message_Block* mb = NULL;

    //稍微休息一下,等一下其他线程再如主循环
    ACE_Time_Value tvSleep(0, MAX_MSG_SENDCHECKTIME*MAX_BUFF_1000);
    ACE_OS::sleep(tvSleep);

    while(IsRun())
    {
        mb = NULL;

        //xtime = ACE_OS::gettimeofday() + ACE_Time_Value(0, MAX_MSG_PUTTIMEOUT);
        if(getq(mb, 0) == -1)
        {
            OUR_DEBUG((LM_ERROR,"[CMessageService::svc] PutMessage error errno = [%d].\n", errno));
            m_blRun = false;
            break;
        }

        if(mb == NULL)
        {
            continue;
        }

        while(m_emThreadState != THREAD_RUN)
        {
            //如果模块正在卸载或者重载,线程在这里等加载完毕(等1ms)。
            ACE_Time_Value tvsleep(0, 1000);
            ACE_OS::sleep(tvsleep);
        }

        CMessage* msg = *((CMessage**)mb->base());

        if(! msg)
        {
            OUR_DEBUG((LM_ERROR,"[CMessageService::svc] mb msg == NULL CurrthreadNo=[%d]!\n", m_u4ThreadID));
            continue;
        }

        this->ProcessMessage(msg, m_u4ThreadID);

		//使用内存池,这块内存不必再释放
    }

    OUR_DEBUG((LM_INFO,"[CMessageService::svc] svc finish!\n"));
    return 0;
}
Beispiel #11
0
 virtual int svc () 
 {
   int stop = 0;          
   for (ACE_Message_Block *mb; !stop && getq (mb) != -1; ) 
   {
     if (mb->msg_type () == ACE_Message_Block::MB_STOP)
     {
       stop = 1;
     }
     else
     {  	      	    
 	    ACE_DEBUG ((LM_DEBUG, "%s",mb->base()));    	                           
     }
     put_next (mb);
   }
   return 0;
 }
int ZigbeeSerialportService::send(ZigbeeRequest  *req)
{
    {
        ACE_Message_Block *b = new ACE_Message_Block(req->size());
        ACE_OS::memcpy(b->base(), req->base(), req->size());

        b->msg_type(ZIGBEE_SERIAL_PORT_CMD_SEND_REQ);

        if (task_->message_queue.enqueue_tail(b) == -1 )
        {
            ACE_DEBUG((LM_DEBUG, "ZigbeeSerialportService faild to input node block into queue\n"));
        }

        delete req;
    }

    return 0;
}
Beispiel #13
0
ACE_Method_Request *
ACE_Activation_Queue::dequeue (ACE_Time_Value *tv)
{
  ACE_Message_Block *mb = 0;

  // Dequeue the message.
  if (this->queue_->dequeue_head (mb, tv) != -1)
    {
      // Get the next <Method_Request>.
      ACE_Method_Request *mr =
        reinterpret_cast<ACE_Method_Request *> (mb->base ());
      // Delete the message block.
      mb->release ();
      return mr;
    }
  else
    return 0;
}
Beispiel #14
0
int 
Sender::initiate_write_stream (void)
{
  ACE_Guard<ACE_Recursive_Thread_Mutex> locker (mutex_);   

  welcome_message_.rd_ptr(welcome_message_.base ());
  welcome_message_.wr_ptr(welcome_message_.base ());
  welcome_message_.wr_ptr (ACE_OS::strlen (data));
	
  if (this->ws_.write (welcome_message_,
                       welcome_message_.length ()) == -1)
    ACE_ERROR_RETURN((LM_ERROR,
                      "%p\n",
                      "ACE_Asynch_Write_Stream::write"),
                     -1);
  io_count_++;
  return 0;
}
bool CSenceManager::PutMessage(uint32 u4CommandID, _CommandInfo& objCommandInfo)
{
	_QueueMessage* pQueueMessage = m_objMessagePool.Create();
	if(NULL == pQueueMessage)
	{
		OUR_DEBUG((LM_INFO,"[CSenceManager::PutMessage] m_objMessagePool not enougth!\n"));
		return false;
	}

	pQueueMessage->m_u4CommandID = u4CommandID;
	pQueueMessage->m_objData    = objCommandInfo;

	ACE_Message_Block* pmb = m_objMessageBlockPool.Create(sizeof(_QueueMessage*));
	if(NULL == pmb)
	{
		OUR_DEBUG((LM_INFO,"[CSenceManager::PutMessage] m_objMessageBlockPool not enougth!\n"));
		m_objMessagePool.Delete(pQueueMessage);
		return false;
	}

	_QueueMessage** ppMessage = (_QueueMessage **)pmb->base();
	*ppMessage = pQueueMessage;

	//判断队列是否是已经最大
	int nQueueCount = (int)msg_queue()->message_count();
	if(nQueueCount >= (int)QUEUE_COUNT)
	{
		OUR_DEBUG((LM_ERROR,"[CSenceManager::PutMessage] Queue is Full nQueueCount = [%d].\n", nQueueCount));
		m_objMessageBlockPool.Delete(pmb);
		m_objMessagePool.Delete(pQueueMessage);
		return false;
	}

	ACE_Time_Value xtime = ACE_OS::gettimeofday();
	if(this->putq(pmb, &xtime) == -1)
	{
		OUR_DEBUG((LM_ERROR,"[CSenceManager::PutMessage] Queue putq  error nQueueCount = [%d] errno = [%d].\n", nQueueCount, errno));
		m_objMessageBlockPool.Delete(pmb);
		m_objMessagePool.Delete(pQueueMessage);
		return false;
	}

	return true;
}
Beispiel #16
0
int
JAWS_THYBRID_Concurrency::getq (JAWS_Protocol_Handler *&ph)
{
  ph = 0;

  JAWS_CONCURRENCY_TASK *task = this;

  if (this->shutdown_task_ && task->msg_queue ()->message_count () == 0)
    return -1;

  int getting = ++(this->getting_);

  if (getting > this->min_number_of_threads_)
    {
      if (task->msg_queue ()->message_count () == 0)
        {
          --(this->getting_);
          return -1;
        }
    }

  ACE_Message_Block *mb = 0;
  int result = task->getq (mb);

  if (result != -1)
    {
      ph = (JAWS_Protocol_Handler *) mb->base ();

      if (ph == 0)
        {
          // Shutdown this task;
          this->shutdown_task_ = 1;
          if (this->getting_ > 1)
            {
              task->putq (mb);
              result = -1;
            }

        }
    }

  --(this->getting_);
  return result;
}
Beispiel #17
0
int
Sender::on_open (const ACE_INET_Addr & local,
                 const ACE_INET_Addr & remote)
{
   ACE_UNUSED_ARG(local);
   ACE_Message_Block *mb = 0;

   ACE_NEW_RETURN (mb,
                  ACE_Message_Block (cfg.s_blksize()+1),
                  -1);

   mb->rd_ptr(mb->base());
   mb->wr_ptr(mb->base() + cfg.s_blksize());
   
   ACE_OS::strncpy(mb->rd_ptr(), complete_message,cfg.s_blksize());
   *mb->wr_ptr() = '\0'; 
 
   return this->on_data_sent(*mb, remote);
}
Beispiel #18
0
bool CLogManager::Dispose_Queue()
{
    ACE_Message_Block* mb = NULL;
    ACE_OS::last_error(0);

    if (getq(mb, 0) == -1)
    {
        OUR_DEBUG((LM_ERROR, "[CLogManager::svc] get error errno = [%d].\n", ACE_OS::last_error()));
        m_blRun = false;
        return false;
    }
    else if (mb->msg_type() == ACE_Message_Block::MB_STOP)
    {
        m_mutex.acquire();
        mb->release();
        this->msg_queue()->deactivate();
        m_cond.signal();
        m_mutex.release();
        m_blRun = false;
        return true;
    }
    else
    {
        _LogBlockInfo* pLogBlockInfo = *((_LogBlockInfo**)mb->base());

        if (!pLogBlockInfo)
        {
            OUR_DEBUG((LM_ERROR, "[CLogManager::svc] CLogManager mb log == NULL!\n"));
            return true;
        }

        if (0 != ProcessLog(pLogBlockInfo))
        {
            OUR_DEBUG((LM_ERROR, "[CLogManager::svc] ProcessLog is false.\n"));
        }

        //回收日志块
        m_objLogBlockPool.ReturnBlockInfo(pLogBlockInfo);
    }

    return true;
}
Beispiel #19
0
int Sender::initiate_write_stream (void)
{
  ACE_GUARD_RETURN (MyMutex, locker, m_Mtx, -1);

  welcome_message_.rd_ptr( welcome_message_.base ());
  welcome_message_.wr_ptr( welcome_message_.base ());
  welcome_message_.wr_ptr (ACE_OS::strlen (data));

  if (this->ws_.write (welcome_message_,
                       welcome_message_.length ()
                       ) == -1)
    {
      ACE_ERROR_RETURN((LM_ERROR,
                        "%p\n",
                        "ACE_Asynch_Write_File::write"),
                       -1);
    }

  nIOCount++ ;
  return 0;
}
Beispiel #20
0
ACE_Message_Block * 
SndProtocol::create_message()
{
  u_int blksize = this->get_connection()->config().s_blksize();
  u_int limit   = this->get_connection()->config().xfer_limit();
  u_int winsize = this->get_connection()->config().w_size();

  if (limit != 0 && this->get_connection()->get_total_snd () >= limit)
    return 0;

  // flow control
  if ((u_long)(this->get_connection()->get_total_snd () - 
               this->get_connection()->get_total_rcv () > winsize))
    return 0 ; 

  ACE_Message_Block *mb = this->get_connection()->alloc_msg();
   
  mb->copy  (complete_message);
  mb->wr_ptr(mb->base() + blksize); // mb->space());

  
  return mb;
}
Beispiel #21
0
int ZigbeeRequest::get()
{
    ACE_Message_Block *b = new ACE_Message_Block(this->size());

    if(b)
    {
        ACE_OS::memcpy(b->base(), this->base(), this->size());
        b->msg_type(EventNotifyHandler::EventSerialportSendData);

        if ( -1 == _zigbeeHelper::instance()->eventQ()->putQ(b))
        {
            b->release();
        }

        delete this;
    }
    else
    {
        delete this;
    }

    return 0;
}
Beispiel #22
0
template <class T> int
ACE_Future_Set<T>::next_readable (ACE_Future<T> &future,
                                  ACE_Time_Value *tv)
{
  if (this->is_empty ())
    return 0;

  ACE_Message_Block *mb = 0;
  FUTURE_REP *future_rep = 0;

  // Wait for a "readable future" signal from the message queue.
  if (this->future_notification_queue_->dequeue_head (mb,
                                                      tv) != -1)
    {
      // Extract future rep from the message block.
      future_rep = reinterpret_cast<FUTURE_REP *> (mb->base ());

      // Delete the message block.
      mb->release ();
    }
  else
    return 0;

  // Remove the hash map entry with the specified future rep from our map.
  FUTURE_HOLDER *future_holder;
  if (this->future_map_.find (future_rep,
                              future_holder) != -1)
    {
      future = future_holder->item_;
      this->future_map_.unbind (future_rep);
      delete future_holder;
      return 1;
    }

  return 0;
}
Beispiel #23
0
ACE_Message_Block::ACE_Message_Block (const ACE_Message_Block &mb,
                                      size_t align)
  :flags_ (0),
   data_block_ (0)
{
  ACE_TRACE ("ACE_Message_Block::ACE_Message_Block");

  if (ACE_BIT_DISABLED (mb.flags_,
                        ACE_Message_Block::DONT_DELETE))
    {
      if (this->init_i (0,         // size
                        MB_NORMAL, // type
                        0,         // cont
                        0,         // data
                        0,         // allocator
                        0,         // locking strategy
                        0,         // flags
                        0,         // priority
                        ACE_Time_Value::zero,     // execution time
                        ACE_Time_Value::max_time, // absolute time of deadline
                        mb.data_block ()->duplicate (), // data block
                        mb.data_block ()->data_block_allocator (),
                        mb.message_block_allocator_) == -1)
        ACE_ERROR ((LM_ERROR,
                    ACE_TEXT ("ACE_Message_Block")));
#if !defined (ACE_LACKS_CDR_ALIGNMENT)
      // Align ourselves
      char *start = ACE_ptr_align_binary (this->base (),
                                          align);
#else
      char *start = this->base ();
#endif /* ACE_LACKS_CDR_ALIGNMENT */

      // Set our rd & wr pointers
      this->rd_ptr (start);
      this->wr_ptr (start);

    }
  else
    {
      if (this->init_i (0,         // size
                        MB_NORMAL, // type
                        0,         // cont
                        0,         // data
                        0,         // allocator
                        0,         // locking strategy
                        0,         // flags
                        0,         // priority
                        ACE_Time_Value::zero,     // execution time
                        ACE_Time_Value::max_time, // absolute time of deadline
                        mb.data_block ()->clone_nocopy (),// data block
                        mb.data_block ()->data_block_allocator (),
                        mb.message_block_allocator_) == -1)
        ACE_ERROR ((LM_ERROR,
                    ACE_TEXT ("ACE_Message_Block")));

#if !defined (ACE_LACKS_CDR_ALIGNMENT)
      // Align ourselves
      char *start = ACE_ptr_align_binary (this->base (),
                                          align);
#else
      char *start = this->base ();
#endif /* ACE_LACKS_CDR_ALIGNMENT */

      // Set our rd & wr pointers
      this->rd_ptr (start);
      this->wr_ptr (start);

#if !defined (ACE_LACKS_CDR_ALIGNMENT)
      // Get the alignment offset of the incoming ACE_Message_Block
      start = ACE_ptr_align_binary (mb.base (),
                                    align);
#else
      start = mb.base ();
#endif /* ACE_LACKS_CDR_ALIGNMENT */

      // Actual offset for the incoming message block assuming that it
      // is also aligned to the same "align" byte
      size_t const wr_offset = mb.wr_ptr_ - (start - mb.base ());

      // Copy wr_offset amount of data in to <this->data_block>
      (void) ACE_OS::memcpy (this->wr_ptr (),
                             start,
                             wr_offset);

      // Dont move the write pointer, just leave it to the application
      // to do what it wants

    }
#if defined (ACE_LACKS_CDR_ALIGNMENT)
  ACE_UNUSED_ARG (align);
#endif /* ACE_LACKS_CDR_ALIGNMENT */
}
Beispiel #24
0
/* Now we come to the svc() method.  As I said, this is being executed
   in each thread of the Thread_Pool.  Here, we pull messages off of
   our built-in ACE_Message_Queue and cause them to do work.  */
int
Thread_Pool::svc (void)
{
    /* The getq() method takes a reference to a pointer.  So... we need
      a pointer to give it a reference to.  */
    ACE_Message_Block *mb;

    /* Create the guard for our active thread counter object.  No matter
      where we choose to return() from svc(), we now know that the
      counter will be decremented.  */
    Counter_Guard counter_guard (active_threads_);

    /* Get messages from the queue until we have a failure.  There's no
      real good reason for failure so if it happens, we leave
      immediately.  */
    while (this->getq (mb) != -1)
    {
        /* A successful getq() will cause "mb" to point to a valid
          refernce-counted ACE_Message_Block.  We use our guard object
          here so that we're sure to call the release() method of that
          message block and reduce it's reference count.  Once the count
          reaches zero, it will be deleted.  */
        Message_Block_Guard message_block_guard (mb);

        /* As noted before, the ACE_Message_Block stores it's data as a
          char*.  We pull that out here and later turn it into an
          ACE_Event_Handler* */
        char *c_data = mb->base ();

        /* We've chosen to use a "null" value as an indication to leave.
          If the data we got from the queue is not null then we have
          some work to do.  */
        if (c_data)
        {
            /* Once again, we go to great lengths to emphasize the fact
              that we're casting pointers around in rather impolite
              ways.  We could have cast the char* directly to an
              ACE_Event_Handler* but then folks might think that's an OK
              thing to do.

              (Note: The correct way to use an ACE_Message_Block is to
              write data into it.  What I should have done was create a
              message block big enough to hold an event handler pointer
              and then written the pointer value into the block.  When
              we got here, I would have to read that data back into a
              pointer.  While politically correct, it is also a lot of
              work.  If you're careful you can get away with casting
              pointers around.)  */
            void *v_data = (void *) c_data;

            ACE_Event_Handler *handler = (ACE_Event_Handler *) v_data;

            /* Now that we finally have an event handler pointer, invoke
              it's handle_input() method.  Since we don't know it's
              handle, we just give it a default.  That's OK because we
              know that we're not using the handle in the method anyway.  */
            if (handler->handle_input (ACE_INVALID_HANDLE) == -1)
            {
                /* Tell the handler that it's time to go home.  The
                  "normal" method for shutting down a handler whose
                  handler failed is to invoke handle_close().  This will
                  take care of cleaning it up for us.  Notice how we use
                  the handler's get_handle() method to populate it's
                  "handle" parameter.  Convenient isn't it?  */
                handler->handle_close (handler->get_handle (), 0);

                /* Also notice that we don't exit the svc() method here!
                  The first time I did this, I was exiting.  After a few
                  clients disconnect you have an empty thread pool.
                  Hard to do any more work after that...  */
            }
        }
        else
            /* If we get here, we were given a message block with "null"
               data.  That is our signal to leave, so we return(0) to
               leave gracefully.  */
            return 0;		// Ok, shutdown request

        // message_block_guard goes out of scope here and releases the
        // message_block instance.
    }

    return 0;
}
Beispiel #25
0
static int
iterator_test (void)
{
  const int ITERATIONS = 5;
  ACE_TCHAR buffer[ITERATIONS][BUFSIZ];
  // Use queue size from of 32 Kb (more if using wide-char), instead of the
  // default of 16 Kb (defined by ACE_Message_Queue_Base::DEFAULT_HWM),
  // so that the test runs on machines with 8Kb pagesizes.

  //  QUEUE queue (32 * 1024 * sizeof (ACE_TCHAR));
  QUEUE queue (sizeof(buffer));

  int i;

  for (i = 0; i < ITERATIONS; i++)
    {
      ACE_OS::sprintf (buffer[i],
                       ACE_TEXT ("%d"),
                       i + 1);

      ACE_Message_Block *entry = 0;
      ACE_NEW_RETURN (entry,
                      ACE_Message_Block ((char *) buffer[i],
                                         sizeof buffer[i]),
                      -1);

      if (queue.is_full ())
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("QUEUE:: the message queue is full on iteration %u!\n"),
                           i + 1),
                          -1);

      if (queue.enqueue (entry) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("QUEUE::enqueue\n")),
                          -1);
    }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("\nForward Iterations\n")));
  {
    ITERATOR iterator (queue);

    for (ACE_Message_Block *entry = 0;
         iterator.next (entry) != 0;
         iterator.advance ())
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("%s\n"),
                  entry->base ()));
  }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("\nReverse Iterations\n")));
  {
    REVERSE_ITERATOR iterator (queue);

    for (ACE_Message_Block *entry = 0;
         iterator.next (entry) != 0;
         iterator.advance ())
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("%s\n"),
                  entry->base ()));
  }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("\nForward Iterations\n")));
  {
    QUEUE::ITERATOR iterator (queue);

    for (ACE_Message_Block *entry = 0;
         iterator.next (entry) != 0;
         iterator.advance ())
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("%s\n"),
                  entry->base ()));
  }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("\nReverse Iterations\n")));
  {
    QUEUE::REVERSE_ITERATOR iterator (queue);

    for (ACE_Message_Block *entry = 0;
         iterator.next (entry) != 0;
         iterator.advance ())
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("%s\n"),
                  entry->base ()));
  }

  return 0;
}
Beispiel #26
0
int
MP_Worker::svc(void)
{
	ACE_DEBUG((LM_DEBUG, ACE_TEXT ("(%t) starting up \n")));
	ACE_Message_Block* mb;

	MIME_Entity e;

	int n_eml_http_1 = 0;
	int n_eml_http_n = 0;
	int n_eml_phone = 0;
	FILE* fp;
	fp = ::fopen("d:\\_spam_\\http.log", "w");

	// pattern hash
	std::set< ACE_UINT32 > pat_set;
	int n_dup = 0;

	while(this->msg_queue()->dequeue_head(mb) != -1)
	{
		if ( ACE_OS::strlen(mb->base()) == 0 )
		{
			ACE_DEBUG(( 
				LM_DEBUG, 
				ACE_TEXT("(%t) shutting down\n")
				));
			break;
		}

		///*
		ACE_DEBUG(( 
			LM_DEBUG, 
			ACE_TEXT("(%t) %s\n"), 
			(mb->base())
			));
		//*/

		//::printf("open eml:%s\n", mb->base());
		fwrite(mb->base(), mb->size()-1, 1, fp); // mb->size()-1 to trim '\0' at the end
		fwrite("\n", 1, 1, fp);

		FILE* fp2 = ::fopen("d:\\_spam_\\_log_\\utf-8.txt", "a");
		//fwrite("\xEF\xBB\xBF", 3, 1, fp2);
		::fwrite(mb->base(), mb->size()-1, 1, fp2); // mb->size()-1 to trim '\0' at the end
		::fwrite("\r\n", 2, 1, fp2);
		::fclose(fp2);

		e.import_file(mb->base());
		//e.dump();
		//e.dump_body();

		std::set< std::string > url_set;
		//MIME_Analyzer::get_url(e, url_set);
		//MIME_Analyzer::get_phone(e);
		MIME_Analyzer::dump_body(e); // also log utf-8 txt in this function
		//getchar();

		///*
		// handle dup pattern hash
		ACE_UINT32 hash_val = MIME_Analyzer::get_hash(e);
		if ( pat_set.find(hash_val) != pat_set.end() )
		{
			std::string dup_file(ACE::basename(mb->base(), '/'));
			char prefix[10];
			::sprintf(prefix, "%.8X_", hash_val);
			prefix[9] = 0;
			dup_file = prefix + dup_file;
			dup_file = "d:/_spam_/_dup_/" + dup_file;

			//ACE_OS::rename(mb->base(), dup_file.c_str());
			ACE_OS::unlink(mb->base());

			++n_dup;
			//::printf("%s\n", dup_file.c_str());
		}
		else
		{
			pat_set.insert(hash_val);
		}
		//*/

		// display url_set
		if ( !url_set.empty() )
		{
			//printf("n_url: %d\n", url_set.size());
			std::set< std::string >::iterator iter;
			for(iter = url_set.begin(); iter != url_set.end(); ++iter)
			{
				//printf("%s\n", (*iter).c_str());
				fwrite((*iter).c_str(), (*iter).size(), 1, fp);
				fwrite("\n", 1, 1, fp);
			}
			fwrite("\n", 1, 1, fp);

			if ( url_set.size() == 1 ) ++n_eml_http_1;
			else ++n_eml_http_n;
		}
		else
		{
			//if ( MIME_Util::get_phone(e) > 0 ) ++n_eml_phone;
		}
		
		/*
		ACE_DEBUG(( 
			LM_DEBUG, 
			ACE_TEXT("(%t) %s\n"), 
			e.get_content_type().c_str()
			));
		//*/

		delete mb;

		//ACE_OS::sleep(1);
		//getchar();
	}

	printf("n_eml_http_1:%d\n", n_eml_http_1);
	printf("n_eml_http_n:%d\n", n_eml_http_n);
	printf("n_eml_http_total:%d\n", n_eml_http_1 + n_eml_http_n);
	printf("n_eml_phone:%d\n", n_eml_phone);
	fclose(fp);

	printf("n_dup:%d\n", n_dup);

	return 0;
}
int SerialportTask::svc (void)
{
    ACE_DEBUG((LM_DEBUG,
                "Create zigbee serialport Service thread\n"));

    ACE_Time_Value last_time = ACE_OS::gettimeofday();
    ACE_Time_Value current_time = ACE_OS::gettimeofday();

    while( !thread_exit_flag)
    {
        ACE_Message_Block *b = 0;

        if (message_queue.dequeue_head(b) == -1 )
        {
            ACE_DEBUG((LM_DEBUG, "faile get block from queue\n"));
            continue;
        }

        //ACE_DEBUG((LM_DEBUG, "*** get type[%x] size[%d] ****\n", b->msg_type(),
        //message_queue.message_count()));

        switch(b->msg_type())
        {
            case ZIGBEE_SERIAL_PORT_CMD_EXIT_THREAD:
            {
                thread_exit_flag = 1;
            }
            break;

            case ZIGBEE_SERIAL_PORT_CMD_CONNECT_PORT:
            {
               owner_->connecting_serial_port();
            }
            break;

            case ZIGBEE_SERIAL_PORT_CMD_SEND_REQ:
            {
               current_time = ACE_OS::gettimeofday();

               // each command cant send togather. when the time expired
               // send it
               if ( current_time.msec() > last_time.msec() + 1500 )
               {
                    owner_->send_req((unsigned char*)b->base(), b->size());

                    last_time = ACE_OS::gettimeofday();
               }
               else
               {
                    // re-enter queue to wait time expired
                    message_queue.enqueue_tail(b);
                    b = 0;
               }

            }
            break;

            case ZIGBEE_SERIAL_PORT_CMD_GET_RES:
            {
                owner_->get_response();
            }
            break;

            default:
                break;

        }

        if (b)
        {
            b->release();
        }
    }

    ACE_DEBUG((LM_DEBUG,
                "Return from zigbee serialport Service thread\n"));

    return 0;

}
Beispiel #28
0
int
JAWS_Parse_Headers::parse_headers (JAWS_Header_Info *info,
                                   ACE_Message_Block &mb)
{
  for (;;)
    {
      if (mb.rd_ptr () == mb.wr_ptr ())
          break;

      char *p = mb.rd_ptr ();

      if (info->end_of_line ()
          && (*p != ' ' && *p != '\t'))
        {
          int r = this->parse_header_name (info, mb);
          if (r == 1)
            return info->end_of_headers ();
          continue;
        }
      else
        {
          int r = this->parse_header_value (info, mb);
          if (r == 1)
            {
              if (info->end_of_headers ())
                return 1;
              break;
            }
          continue;
        }
    }

  // If we arrive here, it means either there is nothing more to read,
  // or parse_header_value ran into difficulties (like maybe the
  // header value was too long).

  if (mb.rd_ptr () != mb.base ())
    {
      mb.crunch ();
      return 0;
    }
  else if (mb.length () < mb.size ())
    {
      return 0;
    }
  else if (mb.length () == mb.size ())
    {
      // This is one of those cases that should rarely ever happen.
      // If we get here, the header type name is over 8K long.  We
      // flag this as a bad thing.

      // In HTTP/1.1, I have to remember that a bad request means the
      // connection needs to be closed and the client has to
      // reinitiate the connection.

      info->status (JAWS_Header_Info::STATUS_CODE_TOO_LONG);
      return 1;
    }
  else if (mb.length () > mb.size ())
    {
      ACE_DEBUG ((LM_DEBUG, "JAWS_Parse_Headers: buffer overrun!!\n"));
      info->status (JAWS_Header_Info::STATUS_CODE_TOO_LONG);
      return 1;
    }

  ACE_DEBUG ((LM_DEBUG, "JAWS_Parse_Headers -- shouldn't be here!\n"));
  return 1;
}
Beispiel #29
0
/*****************************************************************************
 Function:    handleMediaFrame
 Description: 拼完一帧PS数据后处理媒体数据
 Input:       rtpFrameList PS数据包列表
 Output:      
 Return:      N/A
*****************************************************************************/
void CPs2EsProcessor::handleMediaFrame(RTP_FRAME_LIST_T &rtpFrameList)
{
	if(NULL == m_pExtendHeader )
	{
		ERROR_LOG("m_pExtendHeader is NULL");
		return;
	}
	if(NULL == m_pRtpFrameCache)
	{
		ERROR_LOG("m_pRtpFrameCache is NULL");
		return;
	}
    if (rtpFrameList.empty())
    {
        ERROR_LOG("Handle PS media frame abnormal , the frame list is empty");
        return;
    }

    if (MAX_RTP_PACKET_COUNT < rtpFrameList.size())
    {
        ERROR_LOG("Handle PS media frame abnormal , the frame list exceeds the Threshold[1024], the rtp packet count: %d",rtpFrameList.size());
        return;
    }

    // 新的一帧到达,缓存应该是空的
    if (m_pWritePos != m_pRtpFrameCache)
    {
        m_pWritePos = m_pRtpFrameCache;
        //BP_RUN_LOG_INF("Handle PS media frame abnormal",            "Write postion not in cache head, serviceID=%s.", m_strServiceID.c_str());
    }

    // 将收到的一帧PS数据拷贝至缓冲区
    ACE_Message_Block* pRtpBlock = NULL;
    bool bFirst = true;
    CRtpPacket rtpPacket;
    unsigned int unCacheSize = RTP_FRAME_CACHE_SIZE;
    int iRet = IVS_SUCCEED;
    for (RTP_FRAME_LIST_T_ITER iter = rtpFrameList.begin(); iter != rtpFrameList.end(); ++iter)
    {
        pRtpBlock = *iter;
        iRet = rtpPacket.ParsePacket(pRtpBlock->rd_ptr(), pRtpBlock->length());
        if (IVS_SUCCEED != iRet)
        {
            m_pWritePos = m_pRtpFrameCache;
            m_pExtendHeader->reset();
            ERROR_LOG("Parse rtp packet fail ,retcode:%d",iRet);
            return;
        }

        if (bFirst)
        {
            if (1 == rtpPacket.GetExtension())
            {
                if(NULL != rtpPacket.GetMuExtData())
                {
                    m_pExtendHeader->copy((char *)rtpPacket.GetMuExtData(), sizeof(RTP_EXTENSION_DATA_MU_S));
                }
                else if(NULL != rtpPacket.GetExtData())
                {
                    m_pExtendHeader->copy((char *)rtpPacket.GetExtData(), sizeof(RTP_EXTENSION_DATA_S));
                }
                else
                {
                   ERROR_LOG("Error extension label");
                }
            }

            if (m_bAppendExtInfo)
            {
                REAL_RECORD_TIME* realRecordTime = (REAL_RECORD_TIME*)(pRtpBlock->base());
                if (NULL != realRecordTime)
                {
                    m_uiRealRecordSecond = realRecordTime->uiSecond;
                    m_uiRealRecordMSecond = realRecordTime->uiMSecond;
                    uint32_t* pStreamRate = (uint32_t*)(pRtpBlock->base() + sizeof(REAL_RECORD_TIME));
                    m_uiReserved = *pStreamRate;
                }
                else
                {
                    ERROR_LOG("Error real record time info");
                }
            }

            bFirst = false;
        }

        // 移除RTP消息头
        pRtpBlock->rd_ptr(rtpPacket.GetHeadLen());

        if (unCacheSize >= pRtpBlock->length())
        {
            memcpy(m_pWritePos, pRtpBlock->rd_ptr(), pRtpBlock->length());
            m_pWritePos += pRtpBlock->length();
            unCacheSize -= pRtpBlock->length();
        }
        else
        {
            // 缓冲区长度不够
            ERROR_LOG("Current frame is too big exceed cache size 1.5M , will discard part data,  rtp package list size=%d,curr rtp package length &d",rtpFrameList.size(),rtpPacket.GetPacketLen());
            m_pWritePos = m_pRtpFrameCache;
            m_pExtendHeader->reset();
            return;
        }
    }

    // 将PS数据转换成ES数据
    int iVideoLen = 0;
    int iAudioLen = 0;
    int iTotalLen = m_pWritePos - m_pRtpFrameCache;
    unsigned char *pFrame = NULL;
    if (NRU_ZERO > iTotalLen || RTP_FRAME_CACHE_SIZE < iTotalLen)
    {
        m_pWritePos = m_pRtpFrameCache;
        m_pExtendHeader->reset();
         ERROR_LOG("Parse PS packet to ES fail and discard curr frame , ulVideoTimeTick:%d,iTotalLen:%d",m_ulVideoTimeTick,iTotalLen);
        return;
    }

    iRet = HSPspkt2ESFrm((unsigned char*)m_pRtpFrameCache, iTotalLen,
                                         pFrame, iVideoLen, iAudioLen);
    if (IVS_SUCCEED != iRet)
    {
        m_pWritePos = m_pRtpFrameCache;
        m_pExtendHeader->reset();
        ERROR_LOG("Parse PS packet to ES fail and discard curr frame,  ulVideoTimeTick:%d",m_ulVideoTimeTick);
        return;
    }

    if ((NRU_ZERO > iVideoLen || RTP_FRAME_CACHE_SIZE < iVideoLen)
        || (NRU_ZERO > iAudioLen || MAX_AUDIO_LENGTH < iAudioLen))
    {
        m_pWritePos = m_pRtpFrameCache;
        m_pExtendHeader->reset();
        ERROR_LOG("Parse PS packet to ES fail and discard curr frame, ulVideoTimeTick: %d,iVideoLen:%d,iAudioLen:%d",m_ulVideoTimeTick,iVideoLen,iAudioLen);
        return;
    }

    if (0 != iVideoLen)
    {
        (void)sendVideoFrame((char *)pFrame, iVideoLen);
    }

    if (0 != iAudioLen)
    {
        (void)sendAudioFrame((char *)(pFrame + iVideoLen), iAudioLen);
    }

    // 重置缓冲区写位置
    m_pWritePos = m_pRtpFrameCache;

    m_pExtendHeader->reset();
    return;
}