cleos 源碼分析 -- nodeos(一)

http_plugin

http_plugin 用來(lái)接受客戶端cleos 發(fā)過(guò)來(lái)的請(qǐng)求,eos 使用多插件機(jī)制來(lái)拆分業(yè)務(wù)邏輯,各plugin 想要相應(yīng)來(lái)自客戶端的請(qǐng)求,就需要在各自模塊的api_plugin 中向 http_plugin 注冊(cè) url_handler .

http_plugin 中有個(gè)map<string,url_handler> url_handlers;變量,保管著其他插件注冊(cè)過(guò)來(lái)的接口以及回調(diào)。

http_plugin 中的 add_api 方法 以及 add_handler:

void add_api(const api_description& api) {
   for (const auto& call : api) 
      add_handler(call.first, call.second);
}

void http_plugin::add_handler(const string& url, const url_handler& handler) {
  ilog( "add api url: ${c}", ("c",url) );
  app().get_io_service().post([=](){
    my->url_handlers.insert(std::make_pair(url,handler));
  });
}

http_plugin 中處理http請(qǐng)求的函數(shù), 通過(guò)handler_itr->second(...)來(lái)調(diào)用具體邏輯。

template<class T>
 void handle_http_request(typename websocketpp::server<detail::asio_with_stub_log<T>>::connection_ptr con) {
    try {
       
       ......

       con->append_header( "Content-type", "application/json" );
       auto body = con->get_request_body();
       auto resource = con->get_uri()->get_resource();
       auto handler_itr = url_handlers.find( resource );
       if( handler_itr != url_handlers.end()) {
          con->defer_http_response();
          
          // 調(diào)用其他模塊注冊(cè)過(guò)來(lái)的回調(diào)
          handler_itr->second( resource, body, [con]( auto code, auto&& body ) {
             con->set_body( std::move( body ));
             con->set_status( websocketpp::http::status_code::value( code ));
             con->send_http_response();
          } );

       } else {
          wlog( "404 - not found: ${ep}", ("ep", resource));
          error_results results{websocketpp::http::status_code::not_found,
                                "Not Found", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, "Unknown Endpoint" )), verbose_http_errors )};
          con->set_body( fc::json::to_string( results ));
          con->set_status( websocketpp::http::status_code::not_found );
       }
    } catch( ... ) {
       handle_exception<T>( con );
    }
 }

chain_plugin

要知道chain_plugin對(duì)外提供什么功能,首先看 chain_api_plugin

chain_api_plugin 中主要分了兩個(gè) api: read_onlyread_write 兩個(gè)類(lèi)處理。

void chain_api_plugin::plugin_startup() {
   ilog( "starting chain_api_plugin" );
   my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain()));
   auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api();
   auto rw_api = app().get_plugin<chain_plugin>().get_read_write_api();

   app().get_plugin<http_plugin>().add_api({
      CHAIN_RO_CALL(get_info, 200l),
      CHAIN_RO_CALL(get_block, 200),
      CHAIN_RO_CALL(get_block_header_state, 200),
      CHAIN_RO_CALL(get_account, 200),
      CHAIN_RO_CALL(get_code, 200),
      CHAIN_RO_CALL(get_abi, 200),
      CHAIN_RO_CALL(get_raw_code_and_abi, 200),
      CHAIN_RO_CALL(get_table_rows, 200),
      CHAIN_RO_CALL(get_currency_balance, 200),
      CHAIN_RO_CALL(get_currency_stats, 200),
      CHAIN_RO_CALL(get_producers, 200),
      CHAIN_RO_CALL(get_producer_schedule, 200),
      CHAIN_RO_CALL(get_scheduled_transactions, 200),
      CHAIN_RO_CALL(abi_json_to_bin, 200),
      CHAIN_RO_CALL(abi_bin_to_json, 200),
      CHAIN_RO_CALL(get_required_keys, 200),
      CHAIN_RW_CALL_ASYNC(push_block, chain_apis::read_write::push_block_results, 202),
      CHAIN_RW_CALL_ASYNC(push_transaction, chain_apis::read_write::push_transaction_results, 202),
      CHAIN_RW_CALL_ASYNC(push_transactions, chain_apis::read_write::push_transactions_results, 202)
   });
}

可以看到,plugin_startup 函數(shù)向 http_plugin 插件添加了若干個(gè)接口,

CHAIN_RW_CALL_ASYNC 定義如下:

#define CHAIN_RW_CALL_ASYNC(call_name, call_result, http_response_code) CALL_ASYNC(chain, rw_api, chain_apis::read_write, call_name, call_result, http_response_code)

#define CALL_ASYNC(api_name, api_handle, api_namespace, call_name, call_result, http_response_code) \
{std::string("/v1/" #api_name "/" #call_name), \
   [this, api_handle](string, string body, url_response_callback cb) mutable { \
      if (body.empty()) body = "{}"; \
      api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>(),\
         [cb, body](const fc::static_variant<fc::exception_ptr, call_result>& result){\
            if (result.contains<fc::exception_ptr>()) {\
               try {\
                  result.get<fc::exception_ptr>()->dynamic_rethrow_exception();\
               } catch (...) {\
                  http_plugin::handle_exception(#api_name, #call_name, body, cb);\
               }\
            } else {\
               cb(http_response_code, result.visit(async_result_visitor()));\
            }\
         });\
   }\
}

最終定義的是一個(gè)map, key 是注冊(cè)的url地址, value 是回調(diào) lambada

例如 CHAIN_RW_CALL_ASYNC(push_block, chain_apis::read_write::push_block_results, 202), 就是向 http_plugin 注冊(cè)了 /v1/chain/push_block 接口,該接口被調(diào)用后,會(huì)轉(zhuǎn)向 chain_pluginread_write 類(lèi)的 push_block 方法,

看看 push_block 方法的定義:


void read_write::push_block(const read_write::push_block_params& params, next_function<read_write::push_block_results> next) {
   try {
      app().get_method<incoming::methods::block_sync>()(std::make_shared<signed_block>(params));
      // 直接向客戶端返回了空的結(jié)果
      next(read_write::push_block_results{});
   } catch ( boost::interprocess::bad_alloc& ) {
      raise(SIGUSR1);
   } CATCH_AND_CALL(next);
}

重點(diǎn)在于這行代碼

app().get_method<incoming::methods::block_sync>()(std::make_shared<signed_block>(params));

先看前面一半: app().get_method<incoming::methods::block_sync>()
調(diào)用applicationget_method 方法,

 template<typename MethodDecl>
 auto get_method() -> std::enable_if_t<is_method_decl<MethodDecl>::value, typename MethodDecl::method_type&>
 {
    using method_type = typename MethodDecl::method_type;
    auto key = std::type_index(typeid(MethodDecl));
    auto itr = methods.find(key);
    if(itr != methods.end()) {
       return *method_type::get_method(itr->second);
    } else {
       methods.emplace(std::make_pair(key, method_type::make_unique()));
       return  *method_type::get_method(methods.at(key));
    }
 }

auto key = std::type_index(typeid(MethodDecl)); 是一個(gè)類(lèi)模版特化,可以將模版名轉(zhuǎn)換為字符串 ,參考鏈接
methods 會(huì)查找這個(gè)key,如果不存在就新建,

incoming::methods::block_sync 類(lèi)型定義如下:

namespace incoming {
  namespace methods {
     // synchronously push a block/trx to a single provider
     using block_sync   = method_decl<chain_plugin_interface, void(const signed_block_ptr&), first_provider_policy>;
  }
}

method_decl 定義又如下

   template< typename Tag, typename FunctionSig, template <typename> class DispatchPolicy = first_success_policy>
   struct method_decl {
      using method_type = method<FunctionSig, DispatchPolicy<FunctionSig>>;
      using tag_type = Tag;
   };
using method_type = typename MethodDecl::method_type;

翻譯如下:
using method_type = method<void(const signed_block_ptr&), first_success_policy>

查看method定義,繼承自 method_caller

method_caller 中定義了signal_typeboost庫(kù)中的signal 類(lèi)型:
boost::signals2::signal<void(Args...), DispatchPolicy>;

并重載了()函數(shù):

void operator()(Args&&... args)
{
   _signal(std::forward<Args>(args)...);
}

signal 直接發(fā)出信號(hào)

回到上面
app().get_method<incoming::methods::block_sync>()(std::make_shared<signed_block>(params))

最終拿到一個(gè) chain_plugin_interface 類(lèi)型的信號(hào),將事件發(fā)出,供其他plugin接受,plugin 之間的通信用這種方式可以減少耦合

全局查找 incoming::methods::block_sync 會(huì)發(fā)現(xiàn),在 producer_plugin 中注冊(cè)了此類(lèi)信號(hào)的回調(diào)

my->_incoming_block_sync_provider = app().get_method<incoming::methods::block_sync>().register_provider([this](const signed_block_ptr& block){
  my->on_incoming_block(block);
});

這里沒(méi)有深入討論 boost 庫(kù)的 signal 機(jī)制。只是簡(jiǎn)單闡述調(diào)用流程。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容