Exemple #1
0
int
ACE_System_Time::get_local_system_time (ACE_Time_Value &time_out)
{
  ACE_TRACE ("ACE_System_Time::get_local_system_time");
  time_out.set (ACE_OS::time (0), 0);
  return 0;
}
int 
main (int argc, char *argv[])
{
  // First you need a handler for the timeout.
  My_Handler my_handler;

  // This is the timeout period in seconds.
  ACE_Time_Value period (ACE_DEFAULT_TIMEOUT);

  if (argc > 1)
    period.set (ACE_OS::atoi (argv[1]));

  // Set up the periodic interval timer.
  if (ACE_Reactor::instance ()->schedule_timer 
      (&my_handler, 
       "hello",
       period,
       period) == -1)
    ACE_ERROR_RETURN ((LM_DEBUG,
                       "%p\n",
                       "schedule_timer"),
                      -1);

  // Set up an ACE signal handler.

  if (ACE_Reactor::instance ()->register_handler 
      (SIGINT,
       &my_handler) == -1)
    ACE_ERROR_RETURN ((LM_DEBUG,
                       "%p\n",
                       "register_handler"),
                      -1);

  // Set up a non-ACE signal handler.  When this goes off, the Reactor
  // should return from its <run_event_loop> method.
  ACE_Sig_Action sig ((ACE_SignalHandler) my_signal_function,
                      SIGQUIT);
  ACE_UNUSED_ARG (sig);

  ACE_DEBUG ((LM_DEBUG, 
	      "starting event loop that runs until you've typed ^C a total of 10 times or ^\\ once.\n"));

  // This call executes the reactor events until we're finished.
  int result = ACE_Reactor::run_event_loop ();

  ACE_DEBUG ((LM_DEBUG,
              "result = %d\n",
              result));

  // Make sure to remove my_handler before exiting main() since
  // otherwise weird things can happen...
  if (ACE_Reactor::instance ()->cancel_timer (&my_handler) == -1)
    ACE_ERROR_RETURN ((LM_DEBUG,
                       "%p\n",
                       "cancel_timer"),
                      -1);
  return 0;
}
Exemple #3
0
int
parse_args (int argc, ACE_TCHAR *argv[])
{
  ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:p:ci:s:f:"));
  int c;

  while ((c = get_opts ()) != -1)
    switch (c)
      {
      case 'f':
        filter = get_opts.opt_arg ();
        break;
      case 'k':
        monitor_ior = get_opts.opt_arg ();
        break;
      case 'p':
        {
          if (monitor_point == 0)
            {
              ACE_NEW_THROW_EX (monitor_point,
                                ::Monitor::NameList,
                                CORBA::NO_MEMORY ());
            }

          monitor_point->length (monitor_point->length () + 1);
          (*monitor_point)[monitor_point->length () - 1] =
            CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR(get_opts.opt_arg ()));
          break;
        }
      case 'c':
        mp_clear = true;
        break;
      case 'i':
        n_iterations = ACE_OS::atoi (get_opts.opt_arg ());
        break;
      case 's':
        sleep_time.set(ACE_OS::atoi (get_opts.opt_arg ()), 0);
        break;
      case '?':
      default:
        ACE_ERROR_RETURN ((LM_ERROR,
                           "usage:  %s "
                           "-k <ior> "
                           "-p <point> "
                           "-i <iterations> "
                           "-c clear "
                           "-s <sleeptime> "
                           "-f <filter> "
                           "\n",
                           argv [0]),
                          -1);
      }

  // Indicates successful parsing of the command line
  return 0;
}
Exemple #4
0
int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("Reactor_Notify_Test"));

  int test_result = 0;       // Innocent until proven guilty

  if (0 == run_notify_purge_test ())
    {
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("purge_pending_notifications test OK\n")));
    }
  else
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("purge_pending_notifications test FAIL\n")));
      test_result = 1;
    }

#if defined (ACE_HAS_THREADS)
  if (0 != run_quiet_notify_test ())
    test_result = 1;

  ACE_Time_Value timeout (SHORT_TIMEOUT);

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) running tests with notify pipe enabled")
              ACE_TEXT (" and time-out = %d seconds\n"),
              timeout.sec ()));
  run_test (0, timeout);

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) running tests with notify pipe disabled")
              ACE_TEXT (" and time-out = %d seconds\n"),
              timeout.sec ()));
  run_test (1, timeout);

  timeout.set (LONG_TIMEOUT, 0);
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) running tests with reactor notification ")
              ACE_TEXT ("pipe enabled\n")
              ACE_TEXT (" and time-out = %d seconds\n"),
              timeout.sec ()));
  run_test (0, timeout);

#else
  ACE_ERROR ((LM_INFO,
              ACE_TEXT ("threads not supported on this platform\n")));
#endif /* ACE_HAS_THREADS */
  ACE_END_TEST;
  return test_result;
}
Exemple #5
0
void yarp::os::impl::sleepThread(ACE_Time_Value& sleep_period)
{
#ifdef YARP_HAS_ACE
    if (sleep_period.usec() < 0 || sleep_period.sec() < 0)
        sleep_period.set(0,0);
    ACE_OS::sleep(sleep_period);
#else
    if (sleep_period.tv_usec < 0 || sleep_period.tv_sec < 0) {
        sleep_period.tv_usec = 0;
        sleep_period.tv_sec = 0;
    }
    usleep(sleep_period.tv_sec * 1000000 + sleep_period.tv_usec );
#endif
}
Exemple #6
0
void
EC_Schedule::build_supplier_qos (
      int i,
      RtecEventChannelAdmin::SupplierQOS& qos,
      int& shutdown_event_type)
{
  char name[128];
  ACE_OS::sprintf (name, "EC_Schedule::Supplier::%04x", i);

  RtecScheduler::handle_t rt_info =
    this->scheduler_->create (name);

  ACE_Time_Value tv (0, this->burst_pause_);
  RtecScheduler::Period_t rate = tv.usec () * 10;

  // The execution times are set to reasonable values, but
  // actually they are changed on the real execution, i.e. we
  // lie to the scheduler to obtain right priorities; but we
  // don't care if the set is schedulable.
  tv.set (0, 2000);
  TimeBase::TimeT time;
  ORBSVCS_Time::Time_Value_to_TimeT (time, tv);
  this->scheduler_->set (rt_info,
                         RtecScheduler::VERY_HIGH_CRITICALITY,
                         time, time, time,
                         rate,
                         RtecScheduler::VERY_LOW_IMPORTANCE,
                         time,
                         1,
                         RtecScheduler::OPERATION);

  int type_start = this->supplier_type_start_ + i*this->supplier_type_shift_;
  int supplier_id = i + 1;
  shutdown_event_type = type_start + this->supplier_type_count_;

  ACE_SupplierQOS_Factory qos_factory;
  for (int j = 0; j != this->supplier_type_count_; ++j)
    qos_factory.insert (supplier_id,
                        type_start + j,
                        rt_info, 1);

  qos_factory.insert (supplier_id,
                      shutdown_event_type,
                      rt_info, 1);

  qos = qos_factory.get_SupplierQOS ();
}
  virtual void push_structured_event(CosNotification::StructuredEvent const& event)
    throw(CosEventComm::Disconnected)
  {
    cout << "domain_name: " << event.header.fixed_header.event_type.domain_name
	 << "  type_name: " << event.header.fixed_header.event_type.type_name << " " << flush;

    if (false) {
    Miro::Client client;
    DynamicAny::DynAnyFactory_var daf =
      client.resolveInit<DynamicAny::DynAnyFactory>("DynAnyFactory");
    DynamicAny::DynAny_var da = daf->create_dyn_any(event.remainder_of_body);
    
    CORBA::TypeCode_var tc = da->type();

    if (tc->kind() == CORBA::tk_struct) {
      CORBA::String_var name = tc->name();
      CORBA::String_var id = tc->id();

      DynamicAny::DynStruct_var ds =
	DynamicAny::DynStruct::_narrow(da);

      for (CORBA::ULong i = 0; i < ds->component_count(); ++i) {
	DynamicAny::DynAny_var member = ds->current_component();
	CORBA::String_var name = ds->current_member_name();
	if (std::string("timestamp") == name.in()) {
	  long long int i =  member->get_ulonglong();
	  ACE_Time_Value t;
	  ORBSVCS_Time::Absolute_TimeT_to_Time_Value(t, i);
	  cout << "latency: " << ACE_OS::gettimeofday() - t << endl;
	  break;
	}
	ds->next();
      }
    }
    else {
      cerr << "unknown event layout" << endl;
    }
    }
    ACE_Time_Value t;
    t.set(time_out);
    ACE_OS::sleep(t);

    cout << "waking up after sleep" << endl;
  }
int 
parseArgs(int& argc, char* argv[])
{
  int rc = 0;
  int c;

  ACE_Get_Opt get_opts (argc, argv, "c:t:?");
  
  while ((c = get_opts()) != -1) {
    switch (c) {
      break;
    case 'c':
      channelName = get_opts.optarg;
      break;
    case 'v':
      verbose = true;
      break;
    case 't':
      timeout.set(atof(get_opts.optarg));
    case '?':
    default:
      rc = 1;
    }
  }


  if (rc) {
    cerr << "usage: " << argv[0] << "[-t timeout [-c channel_name] [-v?]" << endl
	 << "  -c <channel name> name of the event channel (default: NotifyEventChannel)" << endl
	 << "  -t <sec> timeout (default: 5s)" << endl
	 << "  -v verbose mode" << endl
	 << "  -? help: emit this text and stop" << endl;
  }

  if (verbose) {
    cerr << "timeout: " << timeout << endl
	 << "channel name: " << channelName << endl;
  }

  return rc;
}
int CoAPWrapper::time_out(ACE_Time_Value& tm)
{
    struct timeval tv, *timeout;
    int result;
    coap_tick_t now;
    coap_queue_t *nextpdu;
    coap_context_t  *ctx;
    
    if (coap_ctx_ == 0 )
        return 0;

    ctx = coap_ctx_;
    nextpdu = coap_peek_next( ctx );

    coap_ticks(&now);
    while ( nextpdu && nextpdu->t <= now )
    {
        coap_retransmit( ctx, coap_pop_next( ctx ) );
        nextpdu = coap_peek_next( ctx );
    }

    if ( nextpdu && nextpdu->t <= now + COAP_RESOURCE_CHECK_TIME )
    {
        /* set timeout if there is a pdu to send before our automatic timeout occurs */
        tv.tv_usec = ((nextpdu->t - now) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND;
        tv.tv_sec = (nextpdu->t - now) / COAP_TICKS_PER_SECOND;
        timeout = &tv;
    }
    else
    {
        tv.tv_usec = 0;
        tv.tv_sec = COAP_RESOURCE_CHECK_TIME;
        timeout = &tv;
    }

    tm.set(*timeout);

    return 0;
}
int SocketTwoWayStream::open(const Contact& address) {
    if (address.getPort()==-1) {
        return -1;
    }
    String host = address.getHost();
#ifdef YARP_HAS_ACE
    ACE_SOCK_Connector connector;
    if (address.getHost() == "localhost") {
        // ACE does not like localhost.  At all.
        NameConfig config;
        host = config.getHostName(true);
    }
    ACE_INET_Addr addr(address.getPort(),host.c_str());
    ACE_Time_Value openTimeout;
    ACE_Time_Value *timeout = NULL;
    if (address.hasTimeout()) {
        openTimeout.set(address.getTimeout());
        timeout = &openTimeout;
    }
    int result = connector.connect(stream,addr,timeout,ACE_Addr::sap_any,1);
#else
    TcpConnector connector;
    int result = connector.connect(stream, address);
#endif
    if (result>=0) {
        happy = true;
    } else {
        YARP_SPRINTF2(Logger::get(),
                      debug,
                      "TCP connection to tcp://%s:%d failed to open",
                      host.c_str(),
                      address.getPort());
    }
    updateAddresses();
    return result;
}
Exemple #11
0
int PlatConnMgrEx::send_recv(const void * send_buf, int send_len
    , void * recv_buf, int recv_len, const unsigned int uin)
{
    int ip_idx = get_ip_idx(uin);
    int index = get_index(ip_idx, uin);
    ACE_SOCK_Stream* conn = get_conn(index, ip_idx);
    if (conn == NULL)
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get conn failed"
            ",can't get a useful conn"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    ACE_Guard<ACE_Thread_Mutex> guard(conn_lock_[ip_idx][index]);// 加锁需要放在获取的后面 
    if (conn_[ip_idx][index] == NULL) // 加锁后增加一次非法判断 
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv failed"
            ",conn is null"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    conn_use_flag_[ip_idx][index] = 1;
    
    //清除原缓冲 add by awayfang 2010-03-02 
    ACE_Time_Value zero;
    zero.set(0);
    int max_recv_len = recv_len;
    int tmp_ret = conn_[ip_idx][index]->recv(recv_buf, max_recv_len, &zero);//不等待直接返返回
    // 检测到连接关闭时, 重建连接
    if((tmp_ret < 0 && errno != ETIME)   // 连接上无数据的情况,会返回超时,不需重连 
        || tmp_ret == 0)                 // 连接已经被对端关闭, 处于close wait状态
    {
        ACE_DEBUG((LM_INFO, "[%D] PlatConnMgrEx send_recv connection close detected,"
            "uin=%u,ip=%s,index=%d\n", uin, ip_[ip_idx], index));
        init_conn(index, ip_idx);
	 if(conn_[ip_idx][index] == NULL)
        {
            ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv reconnect failed,"
                "index=%d,ip_idx=%d\n", index, ip_idx));
            return -1;
        }
    }
    
    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv msg"
        ",index=%d,ip_idx=%d,uin=%u\n", index, ip_idx, uin));
    int ret = conn_[ip_idx][index]->send(send_buf, send_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv send msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_SEND_FAIL);
        return ret;
    }
	// 
    ret = conn_[ip_idx][index]->recv(recv_buf, recv_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv recv msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_RECV_FAIL);
        return ret;
    }

    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv msg succ"
        ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
        
    conn_use_flag_[ip_idx][index] = 0;//退出前清理使用状态
    return ret;
    
}
Exemple #12
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  ACE_UNUSED_ARG (config_run);

  //TAO_EC_Default_Factory::init_svcs ();

  TAO_EC_Kokyu_Factory::init_svcs ();


  try
    {
      // ORB initialization boiler plate...
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      if (parse_args (argc, argv) == -1)
        {
          ACE_ERROR ((LM_ERROR,
                      "Usage: Service [-o IOR_file_name]\n"));
          return 1;
        }

      CORBA::Object_var object =
        orb->resolve_initial_references ("RootPOA");
      PortableServer::POA_var poa =
        PortableServer::POA::_narrow (object.in ());
      PortableServer::POAManager_var poa_manager =
        poa->the_POAManager ();
      poa_manager->activate ();

      // ****************************************************************

      // Create an scheduling service
      POA_RtecScheduler::Scheduler* sched_impl = 0;

      if (ACE_OS::strcasecmp(sched_type.c_str(), "rms") == 0)
        {
          ACE_DEBUG ((LM_DEBUG, "Creating RMS scheduler\n"));
          ACE_NEW_RETURN (sched_impl,
                          RECONFIG_RMS_SCHED_TYPE,
                          1);
        }
      else if (ACE_OS::strcasecmp(sched_type.c_str(), "muf") == 0)
        {
          ACE_DEBUG ((LM_DEBUG, "Creating MUF scheduler\n"));
          ACE_NEW_RETURN (sched_impl,
                          RECONFIG_MUF_SCHED_TYPE,
                          1);
        }

      RtecScheduler::Scheduler_var scheduler =
        sched_impl->_this ();

      // ****************************************************************
      TAO_EC_Event_Channel_Attributes attributes (poa.in (),
                                                  poa.in ());
      attributes.scheduler = scheduler.in (); // no need to dup

      TAO_EC_Event_Channel ec_impl (attributes);
      RtecEventChannelAdmin::EventChannel_var event_channel =
        ec_impl._this ();
      // ****************************************************************

      // Create a consumer, intialize its RT_Info structures, and
      // connnect to the event channel....

      Consumer consumer_impl1, consumer_impl2;

      RtecScheduler::handle_t consumer1_rt_info =
        scheduler->create ("consumer1");

      RtecScheduler::handle_t consumer2_rt_info =
        scheduler->create ("consumer2");

      //consumer's rate will get propagated from the supplier.
      //so no need to specify a period here. Specifying
      //criticality is crucial since it propagates from
      //consumer to supplier.
      ACE_Time_Value tv (0,0);
      TimeBase::TimeT tmp;
      ORBSVCS_Time::Time_Value_to_TimeT (tmp, tv);
      scheduler->set (consumer1_rt_info,
                      RtecScheduler::VERY_LOW_CRITICALITY,
                      tmp, tmp, tmp,
                      time_val_to_period (tv),
                      RtecScheduler::VERY_LOW_IMPORTANCE,
                      tmp,
                      0,
                      RtecScheduler::OPERATION);

      scheduler->set (consumer2_rt_info,
                      RtecScheduler::VERY_HIGH_CRITICALITY,
                      tmp, tmp, tmp,
                      time_val_to_period (tv),
                      RtecScheduler::VERY_HIGH_IMPORTANCE,
                      tmp,
                      0,
                      RtecScheduler::OPERATION);

      ACE_ConsumerQOS_Factory consumer_qos1, consumer_qos2;
      //consumer_qos.start_disjunction_group ();
      // The types int the range [0,ACE_ES_EVENT_UNDEFINED) are
      // reserved for the EC...
      consumer_qos1.insert_type (ACE_ES_EVENT_UNDEFINED,
                                consumer1_rt_info);

      RtecEventChannelAdmin::ConsumerQOS qos =
        consumer_qos1.get_ConsumerQOS ();
/*
      for (int i=0;i<qos.dependencies.length (); ++i)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "consumer_qos1[%d] event.header.type = %d, "
                      "consumer_qos1[%d] rt_info = %d, "
                      "consumer_qos1[%d] event.header.source = %d\n",
                      i,qos.dependencies[i].event.header.type,
                      i,qos.dependencies[i].rt_info,
                      i,qos.dependencies[i].event.header.source));
        }
*/

      consumer_qos2.insert_type (ACE_ES_EVENT_UNDEFINED + 1,
                                consumer2_rt_info);

      // The canonical protocol to connect to the EC
      RtecEventChannelAdmin::ConsumerAdmin_var consumer_admin =
        event_channel->for_consumers ();

      RtecEventChannelAdmin::ProxyPushSupplier_var supplier_proxy1 =
        consumer_admin->obtain_push_supplier ();

      RtecEventChannelAdmin::ProxyPushSupplier_var supplier_proxy2 =
        consumer_admin->obtain_push_supplier ();

      RtecEventComm::PushConsumer_var consumer1 =
        consumer_impl1._this ();

      RtecEventComm::PushConsumer_var consumer2 =
        consumer_impl2._this ();

      ACE_DEBUG ((LM_DEBUG, "connecting consumers\n"));
      ACE_DEBUG ((LM_DEBUG, "connecting consumer1\n"));
      supplier_proxy1->connect_push_consumer (consumer1.in (),
                                             consumer_qos1.get_ConsumerQOS ());

      ACE_DEBUG ((LM_DEBUG, "connecting consumer2\n"));
      supplier_proxy2->connect_push_consumer (consumer2.in (),
                                             consumer_qos2.get_ConsumerQOS ());

      ACE_DEBUG ((LM_DEBUG, "consumers connected\n"));

      // ****************************************************************

      RtecScheduler::handle_t supplier1_rt_info =
        scheduler->create ("supplier1");

      RtecScheduler::handle_t supplier2_rt_info =
        scheduler->create ("supplier2");

      RtecEventComm::EventSourceID supplier_id1 = 1, supplier_id2 = 2;
      ACE_SupplierQOS_Factory supplier_qos1, supplier_qos2;
      supplier_qos1.insert (supplier_id1,
                           ACE_ES_EVENT_UNDEFINED,
                           supplier1_rt_info,
                           1 /* number of calls, but what does that mean? */);
      supplier_qos2.insert (supplier_id2,
                           ACE_ES_EVENT_UNDEFINED + 1,
                           supplier2_rt_info,
                           1 /* number of calls, but what does that mean? */);

      // The canonical protocol to connect to the EC
      RtecEventChannelAdmin::SupplierAdmin_var supplier_admin =
        event_channel->for_suppliers ();

      RtecEventChannelAdmin::ProxyPushConsumer_var consumer_proxy1 =
        supplier_admin->obtain_push_consumer ();

      RtecEventChannelAdmin::ProxyPushConsumer_var consumer_proxy2 =
        supplier_admin->obtain_push_consumer ();

      Supplier supplier_impl1(supplier_id1, consumer_proxy1.in ());
      Supplier supplier_impl2(supplier_id2, consumer_proxy2.in ());

      RtecEventComm::PushSupplier_var supplier1 =
        supplier_impl1._this ();

      RtecEventComm::PushSupplier_var supplier2 =
        supplier_impl2._this ();

      ACE_DEBUG ((LM_DEBUG, "connecting suppliers\n"));
      ACE_DEBUG ((LM_DEBUG, "connecting supplier1\n"));
      consumer_proxy1->connect_push_supplier (supplier1.in (),
                                             supplier_qos1.get_SupplierQOS ());

      ACE_DEBUG ((LM_DEBUG, "connecting supplier2\n"));
      consumer_proxy2->connect_push_supplier (supplier2.in (),
                                             supplier_qos2.get_SupplierQOS ());
      ACE_DEBUG ((LM_DEBUG, "suppliers connected\n"));

      // ****************************************************************

      //Timer Registration part

      //Timeout consumers for the two suppliers.
      Timeout_Consumer timeout_consumer_impl1(&supplier_impl1);
      Timeout_Consumer timeout_consumer_impl2(&supplier_impl2);

      RtecScheduler::handle_t supplier1_timeout_consumer_rt_info =
        scheduler->create ("supplier1_timeout_consumer");

      //Period = 1sec
      tv.set (1,0);
      ORBSVCS_Time::Time_Value_to_TimeT (tmp, tv);

      scheduler->set (supplier1_timeout_consumer_rt_info,
                      RtecScheduler::VERY_LOW_CRITICALITY,
                      tmp, tmp, tmp,
                      time_val_to_period (tv),
                      RtecScheduler::VERY_LOW_IMPORTANCE,
                      tmp,
                      0,
                      RtecScheduler::OPERATION);

      RtecScheduler::handle_t supplier2_timeout_consumer_rt_info =
        scheduler->create ("supplier2_timeout_consumer");

      //Period = 3sec
      tv.set (3, 0);
      ORBSVCS_Time::Time_Value_to_TimeT (tmp, tv);

      scheduler->set (supplier2_timeout_consumer_rt_info,
                      RtecScheduler::VERY_HIGH_CRITICALITY,
                      tmp, tmp, tmp,
                      time_val_to_period (tv),
                      RtecScheduler::VERY_HIGH_IMPORTANCE,
                      tmp,
                      0,
                      RtecScheduler::OPERATION);

      ACE_ConsumerQOS_Factory timer_qos1, timer_qos2;
      timer_qos1.insert_time (ACE_ES_EVENT_INTERVAL_TIMEOUT,
                              10000000, //in 100s of nanosec
                              supplier1_timeout_consumer_rt_info);
      timer_qos2.insert_time (ACE_ES_EVENT_INTERVAL_TIMEOUT,
                              30000000, //in 100s of nanosec
                              supplier2_timeout_consumer_rt_info);

      RtecEventChannelAdmin::ProxyPushSupplier_var timeout_supplier_proxy1 =
        consumer_admin->obtain_push_supplier ();

      RtecEventChannelAdmin::ProxyPushSupplier_var timeout_supplier_proxy2 =
        consumer_admin->obtain_push_supplier ();

      RtecEventComm::PushConsumer_var safe_timeout_consumer1 =
        timeout_consumer_impl1._this ();

      RtecEventComm::PushConsumer_var safe_timeout_consumer2 =
        timeout_consumer_impl2._this ();

      ACE_DEBUG ((LM_DEBUG, "connecting timeout consumers\n"));
      timeout_supplier_proxy1->
        connect_push_consumer (safe_timeout_consumer1.in (),
                               timer_qos1.get_ConsumerQOS ());

      timeout_supplier_proxy2->
        connect_push_consumer (safe_timeout_consumer2.in (),
                               timer_qos2.get_ConsumerQOS ());

      ACE_DEBUG ((LM_DEBUG, "timeout consumers connected\n"));

      // ****************************************************************
      //Registering dependency between timeout consumers and our suppliers
      //with the scheduler

      scheduler->add_dependency (supplier1_timeout_consumer_rt_info,
                                 supplier1_rt_info,
                                 1,
                                 RtecBase::TWO_WAY_CALL);

      scheduler->add_dependency (supplier2_timeout_consumer_rt_info,
                                 supplier2_rt_info,
                                 1,
                                 RtecBase::TWO_WAY_CALL);

      // ****************************************************************

      // At this point the consumer and supplier are connected to the
      // EC, they have provided their QoS info to the Scheduling
      // Service and the EC has informed the Scheduler about the
      // dependencies between them.
      // We can now compute the schedule for this configuration...

      // The schedule is returned in this variables....

      ACE_DEBUG ((LM_DEBUG, "Computing schedule\n"));
      RtecScheduler::RT_Info_Set_var infos;
      RtecScheduler::Config_Info_Set_var configs;
      RtecScheduler::Dependency_Set_var dependencies;
      RtecScheduler::Scheduling_Anomaly_Set unsafe_anomalies;
      RtecScheduler::Scheduling_Anomaly_Set_var anomalies;

      scheduler->get_rt_info_set (infos.out() );
      scheduler->get_dependency_set (dependencies.out() );
      scheduler->get_config_info_set (configs.out() );

      ACE_DEBUG ((LM_DEBUG, "Printing intermediate results\n"));
      ACE_Scheduler_Factory::dump_schedule (infos.in (),
                                            dependencies.in (),
                                            configs.in (),
                                            unsafe_anomalies,
                                            ACE_TEXT("schedule.out"));

      // Obtain the range of valid priorities in the current
      // platform, the scheduler hard-code this values in the
      // generated file, but in the future we may just use the
      // "logical" priorities and define the mapping to OS
      // priorities at run-time.
      int min_os_priority =
        ACE_Sched_Params::priority_min (ACE_SCHED_FIFO,
                                        ACE_SCOPE_THREAD);
      int max_os_priority =
        ACE_Sched_Params::priority_max (ACE_SCHED_FIFO,
                                        ACE_SCOPE_THREAD);
      scheduler->compute_scheduling (min_os_priority,
                                     max_os_priority,
                                     infos.out (),
                                     dependencies.out (),
                                     configs.out (),
                                     anomalies.out ());

      // Dump the schedule to a file..
      ACE_Scheduler_Factory::dump_schedule (infos.in (),
                                            dependencies.in (),
                                            configs.in (),
                                            anomalies.in (),
                                            ACE_TEXT("schedule.out"));

      // ****************************************************************
      ACE_DEBUG ((LM_DEBUG, "Pushing events\n"));

      ACE_hthread_t thr_handle;
      ACE_Thread::self (thr_handle);

      int prio = ACE_Sched_Params::priority_max (ACE_SCHED_FIFO);
      ACE_OS::thr_setprio (thr_handle, prio);

//     // Generate a few events....
//       RtecEventComm::EventSet event1 (1);
//       event1.length (1);
//       event1[0].header.type   = ACE_ES_EVENT_UNDEFINED;
//       event1[0].header.source = supplier_id1;
//       event1[0].header.ttl    = 1;

//       RtecEventComm::EventSet event2 (1);
//       event2.length (1);
//       event2[0].header.type   = ACE_ES_EVENT_UNDEFINED + 1;
//       event2[0].header.source = supplier_id2;
//       event2[0].header.ttl    = 1;

//       for (int i = 0; i != 200; ++i)
//         {
//           if (i % 2 == 0)
//             {
//               consumer_proxy1->push (event1);
//             }
//           else
//             {
//               consumer_proxy2->push (event2);
//             }

//           ACE_Time_Value rate (0, 10000);
//           ACE_OS::sleep (rate);
//         }

      ACE_DEBUG ((LM_DEBUG, "(%t) activating EC\n"));
      ec_impl.activate ();
      ACE_DEBUG ((LM_DEBUG, "EC activated\n"));

      orb->run ();

      // ****************************************************************

      // We should do a lot of cleanup (disconnect from the EC,
      // deactivate all the objects with the POA, etc.) but this is
      // just a simple demo so we are going to be lazy.

    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Service");
      return 1;
    }
  return 0;
}
Exemple #13
0
int Publisher_impl::Worker::svc (void)
{
  double data = 0.0;
  bool doShutdown = false;
  unsigned long iteration = 0;
  ACE_Time_Value tv;
  tv.set(0.01);
  while (!terminated)
    {
      data += 0.01;
      ++iteration;
      {
        ACE_GUARD_RETURN (TAO_SYNCH_MUTEX, ace_mon, this->mutex, 0);
        doShutdown = subscribers.size() > 0;
        for (vector<_Subscriber>::iterator iter = subscribers.begin();
             iter != subscribers.end(); ++iter)
          {
            if (!iter->unsubscribed)
              {
                doShutdown = false;
                try
                  {
                    if (!CORBA::is_nil(iter->subscriber.in ()))
                      iter->subscriber->onData(data);
                    else
                      iter->unsubscribed = true;
                    ++iter->count;
                  }
                catch (...)
                  {
                    iter->unsubscribed = true;
                  }
              }
          }
      }
      if (iteration % 200 == 0)
        {
          ACE_GUARD_RETURN (TAO_SYNCH_MUTEX, ace_mon, this->mutex, 0);
          for (vector<_Subscriber>::iterator iter = subscribers.begin();
               iter != subscribers.end(); ++iter)
            {
              if (!iter->unsubscribed)
                {
                  try
                    {
                      iter->subscriber->isAlive();
                    }
                  catch (...)
                    {
                      iter->unsubscribed = true;
                    }
                }
            }
        }
      if (doShutdown)
        owner->shutdown();
      else
        ACE_OS::sleep(tv);
    }
  return 0;
}
Exemple #14
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  int err = 0;
  CosNaming::Name the_name (0);
  CORBA::ORB_var orb;

  try
    {
      // Contact the orb
      orb = CORBA::ORB_init (argc, argv);

      // Scan through the command line options
      bool
        failed = false,
        quiet = false,
        destroy = false;
      const ACE_TCHAR *const pname = argv[0];
      const ACE_TCHAR *nameService = 0;
      ACE_TCHAR kindsep = ACE_TEXT('.');
      ACE_TCHAR ctxsep[] = ACE_TEXT("/");
      ACE_TCHAR *name = 0;
      ACE_Time_Value
        rtt = ACE_Time_Value::zero;

      if (0 < argc)
        {
          while (0 < --argc)
            {
              ++argv;
              if (0 == ACE_OS::strcmp (*argv, ACE_TEXT ("--ns")))
                {
                  if (!--argc)
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                 "Error: --ns requires an argument\n"));
                      failed= true;
                    }
                  else
                    {
                      ++argv;
                      if (nameService)
                        {
                          ACE_DEBUG ((LM_DEBUG,
                                     "Error: more than one --ns.\n"));
                          failed= true;
                        }
                      else
                        nameService = *argv;
                    }
                }
              else if (0 == ACE_OS::strcmp (*argv, ACE_TEXT ("--quiet")))
                {
                  quiet = true;
                }
              else if (0 == ACE_OS::strcmp (*argv, ACE_TEXT ("--name")))
                {
                  if (name)
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                 "Error: more than one --name\n"));
                      failed = true;
                    }
                  else if (!--argc)
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                  "Error: --name requires an argument\n"));
                      failed = true;
                    }
                  else
                    name = *(++argv);
                }
              else if (0 == ACE_OS::strcmp (*argv, ACE_TEXT ("--ctxsep")))
                {
                  if (!--argc)
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                  "Error: --ctxsep requires a character\n"));
                      failed = true;
                    }
                  else if (1 != ACE_OS::strlen(*(++argv)))
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                 "Error: --ctxsep takes a single character (not %s)\n", *argv));
                      failed = true;
                    }
                  else
                    ctxsep[0] = (*argv)[0];
                }
              else if (0 == ACE_OS::strcmp (*argv, ACE_TEXT ("--kindsep")))
                {
                  if (!--argc)
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                  "Error: --kindsep requires a character\n"));
                      failed = true;
                    }
                  else if (1 != ACE_OS::strlen(*(++argv)))
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                 "Error: --kindsep takes a single character (not %s)\n", *argv));
                      failed = true;
                    }
                  else
                    kindsep = (*argv)[0];
                }
              else if (0 == ACE_OS::strcmp(*argv, ACE_TEXT ("--rtt")))
                {
                  if (rtt != ACE_Time_Value::zero)
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                 "Error: --rtt given more than once\n"));
                      failed = true;
                    }
                  else if (!--argc || !ACE_OS::ace_isdigit (ACE_TEXT_ALWAYS_CHAR (*(++argv))[0]))
                    {
                      ACE_DEBUG ((LM_DEBUG,
                                 "Error: --rtt requires a number\n"));
                      failed = true;
                    }
                 else
                  rtt.set(ACE_OS::atoi (ACE_TEXT_ALWAYS_CHAR (*argv)), 0);
                }
              else if (0 == ACE_OS::strcmp (*argv, ACE_TEXT ("--destroy")))
                {
                  destroy = true;
                }
              else
                {
                  ACE_DEBUG ((LM_DEBUG,
                             "Unknown option %s\n", *argv));
                  failed = true;
                }
            }
        }

      if (!name || failed)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "\nUsage:\n  %s --name <name>\n"
                      "optional:\n"
                      "  --ns <ior>\n"
                      "  --ctxsep  <character>\n"
                      "  --kindsep <character>\n"
                      "  --destroy\n"
                      "  --quiet\n"
                      "  --rtt <seconds> {Sets the relative round trip timeout policy}\n\n",
                      "where <name> uses the --ctxsep character (defaults to /)\n"
                      "to separate sub-contexts and --kindsep (defaults to .)\n"
                      "to separate ID & Kind. Will destroy a naming context\n"
                      "before unbinding if --destroy is given, otherwise it\n"
                      "will orphan them. Connects to default NameService\n"
                      "unless --ns is given. Displays all ID/Kinds found\n"
                      "on path unless --quiet is given.\n",
                      pname));
          orb->destroy ();
          return 1;
        }

      // Contact the name service
      CORBA::Object_var nc_obj;
      if (nameService)
        nc_obj = orb->string_to_object (nameService);
      else
        nc_obj = orb->resolve_initial_references ("NameService");

      nc_obj = set_rtt(orb.in(), nc_obj.in (), rtt);
      CosNaming::NamingContext_var root_nc =
        CosNaming::NamingContext::_narrow (nc_obj.in ());

      if (CORBA::is_nil (root_nc.in ()))
        {
          ACE_DEBUG ((LM_DEBUG,
                      "Error: nil naming context\n"));
          orb->destroy ();
          return 1;
        }

      // Assemble the name from the user string given
      ACE_TCHAR *cp;
      while (0 != (cp = ACE_OS::strtok (name, ctxsep)))
        {
          const int index= the_name.length();
          the_name.length (index+1);
          ACE_TCHAR *kind = const_cast<ACE_TCHAR*> (ACE_OS::strchr (cp, kindsep));
          if (kind)
            {
              *kind = '\0';
              the_name[index].kind= CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR(++kind));
            }
          the_name[index].id = CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR(cp));
          name = 0; // way strtok works
        }

      // Attempt to locate the object and destroy/unbind it
      CORBA::Object_var
        obj = root_nc->resolve (the_name);
      root_nc->unbind (the_name);
      if (!quiet)
        {
          unsigned int index;
          for (index= 0u; index < the_name.length()-1u; ++index)
            {
              if (the_name[index].kind && the_name[index].kind[0])
                ACE_DEBUG ((LM_DEBUG, "Found ID: %C  (Kind: %C)\n",
                           the_name[index].id.in(),
                           the_name[index].kind.in()));
              else
                ACE_DEBUG ((LM_DEBUG, "Found ID: %C\n",
                           the_name[index].id.in()));
            }
          ACE_DEBUG ((LM_DEBUG, "UnBound ID: %C",
                     the_name[index].id.in()));
          if (the_name[index].kind && the_name[index].kind[0])
            ACE_DEBUG ((LM_DEBUG, "  (Kind: %C)\n",
                       the_name[index].kind.in()));
          ACE_DEBUG ((LM_DEBUG, "\n"));
        }

      if (!quiet || destroy) {
        bool failure = false;
        try {
          obj = set_rtt(orb.in (), obj.in (), rtt);
          CosNaming::NamingContext_var this_nc =
          CosNaming::NamingContext::_narrow (obj.in ());
          if (!CORBA::is_nil (this_nc.in ()))
            {
              if (destroy)
                {
                  if (!quiet)
                    ACE_DEBUG ((LM_DEBUG,"Destroying\n"));
                  this_nc->destroy( );
                }
              else if (!quiet)
                {
                  CORBA::String_var str =
                    orb->object_to_string (obj.in ());
                  ACE_DEBUG ((LM_DEBUG,
                    "\n*** Possiably Orphaned Naming Context ***\n%C\n\n", str.in()));
                }
            }
          else if (destroy && !quiet)
            ACE_DEBUG ((LM_DEBUG,"Can't Destroy object, it is not a naming context!\n"));
        }
      catch (const CORBA::OBJECT_NOT_EXIST&)
        {
          if (!quiet)
            ACE_DEBUG ((LM_DEBUG, "{Object does not exist!}\n"));
          failure = true;
        }
      catch (const CORBA::TRANSIENT&)
        {
          if (!quiet)
            ACE_DEBUG ((LM_DEBUG, "{Object is transient!}\n"));
          failure = true;
        }
      catch (const CORBA::TIMEOUT&)
        {
          if (!quiet)
            ACE_DEBUG ((LM_DEBUG, "{Operation timed out!}\n"));
          failure = true;
        }

        if (failure && !quiet)
          {
            if (destroy) {
              ACE_DEBUG ((LM_DEBUG, "Failed to destroy context.\n"));
            }
            else {
              ACE_DEBUG ((LM_DEBUG, "Failed to check for orphaned naming context.\n"));
            }
          }
      }
    }
  catch (const CosNaming::NamingContext::NotFound& nf)
    {
      unsigned int index;
      const unsigned int limit= the_name.length()-nf.rest_of_name.length();
      ACE_DEBUG ((LM_DEBUG, "\nError:\n"));
      for (index= 0u; index < limit; ++index)
        {
          if (the_name[index].kind && the_name[index].kind[0])
             ACE_DEBUG ((LM_DEBUG, "ID: %C  (Kind: %C)\n",
               the_name[index].id.in(),
               the_name[index].kind.in()));
          else
             ACE_DEBUG ((LM_DEBUG, "ID: %C\n",
               the_name[index].id.in()));
        }
      const char *why= "Unknown reason";
      switch (nf.why)
        {
        case CosNaming::NamingContext::missing_node:
          why= "\nThe following node is missing";
          break;
        case CosNaming::NamingContext::not_context:
          why= "\nThe following is a final object binding, not a naming context";
          break;
        case CosNaming::NamingContext::not_object:
          why= "\nThe following is a naming context, not a final object binding";
          break;
        }
      nf._tao_print_exception (why);
      for (index= 0u; index < nf.rest_of_name.length(); ++index)
        {
          if (nf.rest_of_name[index].kind && nf.rest_of_name[index].kind[0])
             ACE_DEBUG ((LM_DEBUG, "ID: %C  (Kind: %C)\n",
               nf.rest_of_name[index].id.in(),
               nf.rest_of_name[index].kind.in()));
          else
             ACE_DEBUG ((LM_DEBUG, "ID: %C\n",
               nf.rest_of_name[index].id.in()));
        }
      ++err;
    }
  catch (const CORBA::Exception& ex)
    {
      ACE_DEBUG ((LM_DEBUG, "\nError:\n"));
      ex._tao_print_exception ("Exception in nsdel");
      ++err;
    }

  try
    {
      orb->destroy ();
    }
  catch (const CORBA::Exception& ex)
    {
      ACE_DEBUG ((LM_DEBUG, "\nError:\n"));
      ex._tao_print_exception ("Exception in while shutting down");
      ++err;
    }
  return err;
}
Exemple #15
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  TAO_EC_Default_Factory::init_svcs ();

  try
    {
      // ORB initialization boiler plate...
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      if (parse_args (argc, argv) == -1)
        {
          ACE_ERROR ((LM_ERROR,
                      "Usage: Service [-o IOR_file_name]\n"));
          return 1;
        }

      CORBA::Object_var object =
        orb->resolve_initial_references ("RootPOA");
      PortableServer::POA_var poa =
        PortableServer::POA::_narrow (object.in ());
      PortableServer::POAManager_var poa_manager =
        poa->the_POAManager ();
      poa_manager->activate ();

      // ****************************************************************

#if 0
      // Obtain a reference to the naming service...
      CORBA::Object_var naming_obj =
        orb->resolve_initial_references ("NameService");

      CosNaming::NamingContext_var naming_context =
        CosNaming::NamingContext::_narrow (naming_obj.in ());
#endif /* 0 */

      // ****************************************************************

      // Create an scheduling service
      POA_RtecScheduler::Scheduler* sched_impl = 0;
      if (config_run)
        {
          ACE_NEW_RETURN (sched_impl,
                          RECONFIG_SCHED_TYPE,
                          1);
        }
      else
        {
          ACE_NEW_RETURN (sched_impl,
                          RECONFIG_SCHED_TYPE (configs_size,
                                               configs,
                                               infos_size,
                                               infos,
                                               0, 0,
                                               0),
                          1);
        }

      RtecScheduler::Scheduler_var scheduler =
        sched_impl->_this ();

#if 0
      // Bind the scheduler with the naming service so clients
      // (consumers and suppliers) can resolve it, some (old)
      // implementations of the EC will try to do the same thing
      // (yikes!)
      CosNaming::Name schedule_name (1);
      schedule_name.length (1);
      schedule_name[0].id = CORBA::string_dup ("ScheduleService");
      // Register the servant with the Naming Context....
      naming_context->rebind (schedule_name, scheduler.in ());
#endif /* 0 */

      // ****************************************************************

      TAO_EC_Event_Channel_Attributes attributes (poa.in (),
                                                  poa.in ());
      attributes.scheduler = scheduler.in (); // no need to dup

      TAO_EC_Event_Channel ec_impl (attributes);
      ACE_DEBUG ((LM_DEBUG, "activating EC\n"));
      ec_impl.activate ();
      ACE_DEBUG ((LM_DEBUG, "EC activated\n"));

      RtecEventChannelAdmin::EventChannel_var event_channel =
        ec_impl._this ();

      // ****************************************************************

      // Create a consumer, intialize its RT_Info structures, and
      // connnect to the event channel....

      Consumer consumer_impl;

      RtecScheduler::handle_t consumer_rt_info1 =
        scheduler->create ("consumer_event_1");

      // Let's say that the execution time for event 1 is 2
      // milliseconds...
      ACE_Time_Value tv (0, 2000);
      TimeBase::TimeT time;
      ORBSVCS_Time::Time_Value_to_TimeT (time, tv);
      scheduler->set (consumer_rt_info1,
                      RtecScheduler::VERY_HIGH_CRITICALITY,
                      time, time, time,
                      0,
                      RtecScheduler::VERY_LOW_IMPORTANCE,
                      time,
                      0,
                      RtecScheduler::OPERATION);

      RtecScheduler::handle_t consumer_rt_info2 =
        scheduler->create ("consumer_event_2");

      // Let's say that the execution time for event 2 is 1
      // milliseconds...
      tv.set (0, 1000);
      ORBSVCS_Time::Time_Value_to_TimeT (time, tv);
      scheduler->set (consumer_rt_info2,
                      RtecScheduler::VERY_LOW_CRITICALITY,
                      time, time, time,
                      0,
                      RtecScheduler::VERY_LOW_IMPORTANCE,
                      time,
                      0,
                      RtecScheduler::OPERATION);

      ACE_ConsumerQOS_Factory consumer_qos;
      consumer_qos.start_disjunction_group ();
      // The types int the range [0,ACE_ES_EVENT_UNDEFINED) are
      // reserved for the EC...
      consumer_qos.insert_type (ACE_ES_EVENT_UNDEFINED,
                                consumer_rt_info1);
      consumer_qos.insert_type (ACE_ES_EVENT_UNDEFINED + 1,
                                consumer_rt_info2);

      // The canonical protocol to connect to the EC
      RtecEventChannelAdmin::ConsumerAdmin_var consumer_admin =
        event_channel->for_consumers ();

      RtecEventChannelAdmin::ProxyPushSupplier_var supplier_proxy =
        consumer_admin->obtain_push_supplier ();

      RtecEventComm::PushConsumer_var consumer =
        consumer_impl._this ();

      ACE_DEBUG ((LM_DEBUG, "connecting consumer\n"));
      supplier_proxy->connect_push_consumer (consumer.in (),
                                             consumer_qos.get_ConsumerQOS ());
      ACE_DEBUG ((LM_DEBUG, "consumer connected\n"));

      // ****************************************************************

      Supplier supplier_impl;

      RtecScheduler::handle_t supplier_rt_info1 =
        scheduler->create ("supplier_event_1");

      // The execution times are set to reasonable values, but
      // actually they are changed on the real execution, i.e. we
      // lie to the scheduler to obtain right priorities; but we
      // don't care if the set is schedulable.
      tv.set (0, 10000);
      TimeBase::TimeT tmp;
      ORBSVCS_Time::Time_Value_to_TimeT (tmp, tv);
      RtecScheduler::Period_t rate = ACE_U64_TO_U32(tmp);

      scheduler->set (supplier_rt_info1,
                      RtecScheduler::VERY_HIGH_CRITICALITY,
                      0, 0, 0,
                      rate,
                      RtecScheduler::VERY_LOW_IMPORTANCE,
                      0,
                      1,
                      RtecScheduler::OPERATION);

      RtecScheduler::handle_t supplier_rt_info2 =
        scheduler->create ("supplier_event_2");

      // The execution times are set to reasonable values, but
      // actually they are changed on the real execution, i.e. we
      // lie to the scheduler to obtain right priorities; but we
      // don't care if the set is schedulable.
      tv.set (0, 20000);
      ORBSVCS_Time::Time_Value_to_TimeT (tmp, tv);
      rate = ACE_U64_TO_U32(tmp);

      scheduler->set (supplier_rt_info2,
                      RtecScheduler::VERY_HIGH_CRITICALITY,
                      0, 0, 0,
                      rate,
                      RtecScheduler::VERY_LOW_IMPORTANCE,
                      0,
                      1,
                      RtecScheduler::OPERATION);

      RtecEventComm::EventSourceID supplier_id = 1;
      ACE_SupplierQOS_Factory supplier_qos;
      supplier_qos.insert (supplier_id,
                           ACE_ES_EVENT_UNDEFINED,
                           supplier_rt_info1,
                           1 /* number of calls, but what does that mean? */);
      supplier_qos.insert (supplier_id,
                           ACE_ES_EVENT_UNDEFINED + 1,
                           supplier_rt_info2,
                           1 /* number of calls, but what does that mean? */);

      // The canonical protocol to connect to the EC
      RtecEventChannelAdmin::SupplierAdmin_var supplier_admin =
        event_channel->for_suppliers ();

      RtecEventChannelAdmin::ProxyPushConsumer_var consumer_proxy =
        supplier_admin->obtain_push_consumer ();

      RtecEventComm::PushSupplier_var supplier =
        supplier_impl._this ();

      ACE_DEBUG ((LM_DEBUG, "connecting supplier\n"));
      consumer_proxy->connect_push_supplier (supplier.in (),
                                             supplier_qos.get_SupplierQOS ());
      ACE_DEBUG ((LM_DEBUG, "supplier connected\n"));

      // ****************************************************************

      // At this point the consumer and supplier are connected to the
      // EC, they have provided their QoS info to the Scheduling
      // Service and the EC has informed the Scheduler about the
      // dependencies between them.
      // We can now compute the schedule for this configuration...

      // The schedule is returned in this variables....

      if (config_run)
        {
          ACE_DEBUG ((LM_DEBUG, "Computing schedule\n"));
          RtecScheduler::RT_Info_Set_var infos;
          RtecScheduler::Dependency_Set_var deps;
          RtecScheduler::Config_Info_Set_var configs;
          RtecScheduler::Scheduling_Anomaly_Set_var anomalies;

          // Obtain the range of valid priorities in the current
          // platform, the scheduler hard-code this values in the
          // generated file, but in the future we may just use the
          // "logical" priorities and define the mapping to OS
          // priorities at run-time.
          int min_os_priority =
            ACE_Sched_Params::priority_min (ACE_SCHED_FIFO,
                                            ACE_SCOPE_THREAD);
          int max_os_priority =
            ACE_Sched_Params::priority_max (ACE_SCHED_FIFO,
                                            ACE_SCOPE_THREAD);
          scheduler->compute_scheduling (min_os_priority,
                                         max_os_priority,
                                         infos.out (),
                                         deps.out (),
                                         configs.out (),
                                         anomalies.out ());

          // Dump the schedule to a file..
          ACE_Scheduler_Factory::dump_schedule (infos.in (),
                                                deps.in (),
                                                configs.in (),
                                                anomalies.in (),
                                                ACE_TEXT("schedule.out"));
        }

      // ****************************************************************

      ACE_DEBUG ((LM_DEBUG, "Pushing events\n"));

      // Generate a few events....

      RtecEventComm::EventSet event1 (1);
      event1.length (1);
      event1[0].header.type   = ACE_ES_EVENT_UNDEFINED;
      event1[0].header.source = supplier_id;
      event1[0].header.ttl    = 1;

      RtecEventComm::EventSet event2 (1);
      event2.length (1);
      event2[0].header.type   = ACE_ES_EVENT_UNDEFINED + 1;
      event2[0].header.source = supplier_id;
      event2[0].header.ttl    = 1;

      for (int i = 0; i != 200; ++i)
        {
          if (i % 2 == 0)
            {
              consumer_proxy->push (event1);
            }
          else
            {
              consumer_proxy->push (event2);
            }

          ACE_Time_Value rate (0, 10000);
          ACE_OS::sleep (rate);
        }

      // ****************************************************************

      // We should do a lot of cleanup (disconnect from the EC,
      // deactivate all the objects with the POA, etc.) but this is
      // just a simple demo so we are going to be lazy.

    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Service");
      return 1;
    }
  return 0;
}
Exemple #16
0
int
test_assignments ()
{
  int errors {};
  ACE_Time_Value tv { std::chrono::nanoseconds {100} };
  if (tv.sec () != 0 || tv.usec () != 0)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::nanoseconds (100) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=0,usec=0> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::nanoseconds {10005} };
  if (tv.sec () != 0 || tv.usec () != 10)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::nanoseconds (10005) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=0,usec=10> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::microseconds {1} };
  if (tv.sec () != 0 || tv.usec () != 1)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::microseconds (1) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=0,usec=1> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::microseconds {10005} };
  if (tv.sec () != 0 || tv.usec () != 10005)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::microseconds (10005) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=0,usec=10005> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  std::chrono::milliseconds ms_test { tv.msec () };
  if (ms_test.count () != 10)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after get_chrono_msec. ")
                ACE_TEXT ("Expected <10> - got <%q>\n"),
                ms_test.count ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::milliseconds {1} };
  if (tv.sec () != 0 || tv.usec () != 1000)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::milliseconds (1) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=0,usec=1000> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::milliseconds {10005} };
  if (tv.sec () != 10 || tv.usec () != 5000)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::milliseconds (10005) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=10,usec=5000> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::seconds {1} };
  if (tv.sec () != 1 || tv.usec () != 0)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::seconds (1) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=1,usec=0> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::seconds {10005} };
  if (tv.sec () != 10005 || tv.usec () != 0)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::seconds (10005) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=10005,usec=0> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::hours {1} };
  if (tv.sec () != 3600 || tv.usec () != 0)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::hours (1) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=3600,usec=0> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  tv = ACE_Time_Value { std::chrono::hours {10005} };
  if (tv.sec () != 3600*10005 || tv.usec () != 0)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("std::chrono::hours (10005) to an ACE_Time_Value. ")
                ACE_TEXT ("<sec=%d,usec=0> - got <sec=%d,usec=%d>\n"),
                3600*10005, tv.sec (), tv.usec ()));
    ++errors;
  }

  // Two times half a day, 3 hours, 24 minutes, 54 seconds, 238 milliseconds,
  // 754 microseconds and 342 nanoseconds.
  std::chrono::duration<double, std::ratio<(24*3600)>> half_day {0.5};
  std::chrono::microseconds const usec {
    2 * (
    std::chrono::duration_cast<std::chrono::microseconds> (
      half_day +
      std::chrono::hours {3} + std::chrono::minutes {24} +
      std::chrono::seconds {54} + std::chrono::milliseconds {238} +
      std::chrono::microseconds {754} + std::chrono::nanoseconds {342}))
  };


  tv = ACE_Time_Value {usec};

  //                       half a day  3 hours   24 minutes 54 seconds
  time_t expected_sec = { ((12*3600) + (3*3600) + (24*60) + 54 ) * 2 };
  //                              238 milli    usec  342 nano
  suseconds_t expected_usec = { ((238*1000) + 754 + 0) * 2 };

  if (tv.sec () != expected_sec || tv.usec () != expected_usec)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("two times half a day, 3 hours, 24 minutes, 54 seconds, ")
                ACE_TEXT ("238 milliseconds, 754 microseconds and 342 nanoseconds ")
                ACE_TEXT ("to an ACE_Time_Value. Expected <sec=%d,usec=%d> - ")
                ACE_TEXT ("got <sec=%d,usec=%d>\n"),
                expected_sec,  expected_usec, tv.sec (), tv.usec ()));
    ++errors;
  }

  tv.set (std::chrono::milliseconds {1120});
  if (tv.sec () != 1 || tv.usec () != 120 * std::kilo::num)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P|%t) unexpected value after converting ")
                ACE_TEXT ("a std::chrono::milliseconds of 1120 to an ACE_Time_Value ")
                ACE_TEXT ("Expected <sec=1,usec=120000> - got <sec=%d,usec=%d>\n"),
                tv.sec (), tv.usec ()));
    ++errors;
  }

  return errors;
}
Exemple #17
0
RtecEventChannelAdmin::EventChannel_ptr
get_event_channel(int argc, ACE_TCHAR** argv)
{
    FtRtecEventChannelAdmin::EventChannel_var channel;
    ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("hi:nt:?"));
    int opt;
    int use_gateway = 1;

    while ((opt = get_opt ()) != EOF)
    {
      switch (opt)
      {
      case 'i':
        {
          CORBA::Object_var obj = orb->string_to_object(get_opt.opt_arg ());
          channel = FtRtecEventChannelAdmin::EventChannel::_narrow(obj.in());
        }
        break;
      case 'n':
        use_gateway = 0;
        break;
      case 't':
        timer_interval.set(ACE_OS::atof(get_opt.opt_arg ()));
      case 'h':
      case '?':
        ACE_DEBUG((LM_DEBUG,
                   ACE_TEXT("Usage: %s ")
                   ACE_TEXT("-i ftrt_eventchannel_ior\n")
                   ACE_TEXT("-n       do not use gateway\n")
                   ACE_TEXT("-t time  Time interval in seconds between events (default 1.0)\n")
                   ACE_TEXT("\n"),
                      argv[0]));
        return 0;

      }
    }


    if (CORBA::is_nil(channel.in()))
    {
      /// Find the FTRTEC from the Naming Service
      CosNaming::Name name(1);
      name.length(1);
      name[0].id = CORBA::string_dup("FT_EventService");

      CosNaming::NamingContext_var naming_context =
        resolve_init<CosNaming::NamingContext>(orb.in(), "NameService");

      channel  = resolve<FtRtecEventChannelAdmin::EventChannel> (naming_context.in (),
        name);
    }

    if (use_gateway)
    {
      // use local gateway to communicate with FTRTEC
      ACE_auto_ptr_reset (gateway, new TAO_FTRTEC::FTEC_Gateway (orb.in (), channel.in ()));
      return gateway->_this ();
    }
    else
      return channel._retn ();
}
Exemple #18
0
// 支持指定接收的结束符来接收数据 add by awayfang 2010-03-02 
int PlatConnMgrEx::send_recv_ex(const void * send_buf, int send_len
    , void * recv_buf, int recv_len, const char * separator, const unsigned int uin)
{
    int ip_idx = get_ip_idx(uin); // ip 默认根据 uin 轮询 
    int index = get_index(ip_idx, uin); 
    ACE_SOCK_Stream* conn = get_conn(index, ip_idx);
    if (conn == NULL)
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get conn failed"
            ",can't get a useful conn"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    
    // 因为 ip_idx 可能被修改,加锁需要放在获取的后面 
    ACE_Guard<ACE_Thread_Mutex> guard(conn_lock_[ip_idx][index]); 
    // 加锁后增加一次非法判断 不然有可能被其他线程释放连接对象
    if (conn_[ip_idx][index] == NULL) 
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex failed"
            ",conn is null"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    conn_use_flag_[ip_idx][index] = 1;

    //清除原缓冲 add by awayfang 2010-03-02 
    ACE_Time_Value zero;
    zero.set(0);
    int max_recv_len = recv_len;
    int tmp_ret = conn_[ip_idx][index]->recv(recv_buf, max_recv_len, &zero);//不等特直接返返回
    // 检测到连接关闭时, 重建连接
    // 在对面进程重启时, 有可能发生
    if((tmp_ret < 0 && errno != ETIME)   // 连接上无数据的情况,会返回超时,不需重连 
        || tmp_ret == 0)                 // 连接已经被对端关闭, 处于close wait状态
    {
        ACE_DEBUG((LM_INFO, "[%D] PlatConnMgrEx send_recv_ex connection close detected,"
            "uin=%u,ip=%s,index=%d\n", uin, ip_[ip_idx], index));
        init_conn(index, ip_idx);
    	if(conn_[ip_idx][index] == NULL)
    	{
    		ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex reconnect failed,"
                "index=%d,ip_idx=%d\n", index, ip_idx));
    		return -1;
    	}
    }

    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex msg"
        ",index=%d,ip_idx=%d,uin=%u\n", index, ip_idx, uin));
    int ret = conn_[ip_idx][index]->send_n(send_buf, send_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex send msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接,清理状态
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_SEND_FAIL);
        return ret;
    }
    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex send msg succ"
        ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
	// 
    ret = conn_[ip_idx][index]->recv(recv_buf, recv_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex recv msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接,清理状态
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_RECV_FAIL);
        return ret;
    }

    // 判断结束符 
    if (separator != NULL)
    {
        int tmp_recv_len = ret;
        //判断消息是否结束
        while (strstr((const char*)recv_buf, separator) == NULL 
            && tmp_recv_len < max_recv_len) //未结束,继续接收
        {
            ret = conn_[ip_idx][index]->recv((char*)recv_buf + tmp_recv_len
                , max_recv_len - tmp_recv_len, &time_out_);
            if (ret <= 0) //异常或者对端关闭
            {
                ACE_DEBUG((LM_ERROR, "[%D] [%N,%l]PlatConnMgrEx send_recv_ex"
                    " recv msg failed"
                    ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
                //关闭连接,清理状态
                fini(index, ip_idx);
                Stat::instance()->incre_stat(STAT_CODE_RECV_FAIL);
                return ret;
            }
            tmp_recv_len += ret;
            ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex msg"
                ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
        }
        ret = tmp_recv_len;
    }

    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex msg succ"
        ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
    
    conn_use_flag_[ip_idx][index] = 0;//退出前清理使用状态
    return ret;
}
Exemple #19
0
void
Test_Supplier::connect (RtecScheduler::Scheduler_ptr scheduler,
                        const char* name,
                        int burst_count,
                        int burst_size,
                        int event_size,
                        int burst_pause,
                        int type_start,
                        int type_count,
                        RtecEventChannelAdmin::EventChannel_ptr ec)
{
  this->burst_count_ = burst_count;
  this->burst_size_ = burst_size;
  this->event_size_ = event_size;
  this->burst_pause_ = burst_pause;
  this->type_start_ = type_start;
  this->type_count_ = type_count;

  RtecScheduler::handle_t rt_info =
    scheduler->create (name);

  ACE_Time_Value tv (0, burst_pause);
  RtecScheduler::Period_t rate = tv.usec () * 10;

  // The execution times are set to reasonable values, but
  // actually they are changed on the real execution, i.e. we
  // lie to the scheduler to obtain right priorities; but we
  // don't care if the set is schedulable.
  tv.set (0, 2000);
  TimeBase::TimeT time;
  ORBSVCS_Time::Time_Value_to_TimeT (time, tv);
  scheduler->set (rt_info,
                  RtecScheduler::VERY_HIGH_CRITICALITY,
                  time, time, time,
                  rate,
                  RtecScheduler::VERY_LOW_IMPORTANCE,
                  time,
                  1,
                  RtecScheduler::OPERATION);

  this->supplier_id_ = ACE::crc32 (name);
  ACE_DEBUG ((LM_DEBUG, "ID for <%s> is %04.4x\n", name,
              this->supplier_id_));

  ACE_SupplierQOS_Factory qos;
  for (int i = 0; i != type_count; ++i)
    {
      qos.insert (this->supplier_id_,
                  type_start + i,
                  rt_info, 1);
    }
  qos.insert (this->supplier_id_,
              ACE_ES_EVENT_SHUTDOWN,
              rt_info, 1);

  RtecEventChannelAdmin::SupplierAdmin_var supplier_admin =
    ec->for_suppliers ();

  this->consumer_proxy_ =
    supplier_admin->obtain_push_consumer ();

  RtecEventComm::PushSupplier_var objref =
    this->supplier_._this ();

  this->consumer_proxy_->connect_push_supplier (objref.in (),
                                                qos.get_SupplierQOS ());
}