美文网首页
cleos 源码分析 -- nodeos(一)

cleos 源码分析 -- nodeos(一)

作者: 不要人夸颜色好 | 来源:发表于2018-08-27 19:01 被阅读82次

http_plugin

http_plugin 用来接受客户端cleos 发过来的请求,eos 使用多插件机制来拆分业务逻辑,各plugin 想要相应来自客户端的请求,就需要在各自模块的api_plugin 中向 http_plugin 注册 url_handler .

http_plugin 中有个map<string,url_handler> url_handlers;变量,保管着其他插件注册过来的接口以及回调。

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请求的函数, 通过handler_itr->second(...)来调用具体逻辑。

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();
          
          // 调用其他模块注册过来的回调
          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对外提供什么功能,首先看 chain_api_plugin

chain_api_plugin 中主要分了两个 api: read_onlyread_write 两个类处理。

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 函数向 http_plugin 插件添加了若干个接口,

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()));\
            }\
         });\
   }\
}

最终定义的是一个map, key 是注册的url地址, value 是回调 lambada

例如 CHAIN_RW_CALL_ASYNC(push_block, chain_apis::read_write::push_block_results, 202), 就是向 http_plugin 注册了 /v1/chain/push_block 接口,该接口被调用后,会转向 chain_pluginread_write 类的 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));
      // 直接向客户端返回了空的结果
      next(read_write::push_block_results{});
   } catch ( boost::interprocess::bad_alloc& ) {
      raise(SIGUSR1);
   } CATCH_AND_CALL(next);
}

重点在于这行代码

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

先看前面一半: app().get_method<incoming::methods::block_sync>()
调用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)); 是一个类模版特化,可以将模版名转换为字符串 ,参考链接
methods 会查找这个key,如果不存在就新建,

incoming::methods::block_sync 类型定义如下:

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库中的signal 类型:
boost::signals2::signal<void(Args...), DispatchPolicy>;

并重载了()函数:

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

signal 直接发出信号

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

最终拿到一个 chain_plugin_interface 类型的信号,将事件发出,供其他plugin接受,plugin 之间的通信用这种方式可以减少耦合

全局查找 incoming::methods::block_sync 会发现,在 producer_plugin 中注册了此类信号的回调

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);
});

这里没有深入讨论 boost 库的 signal 机制。只是简单阐述调用流程。

相关文章

网友评论

      本文标题:cleos 源码分析 -- nodeos(一)

      本文链接:https://www.haomeiwen.com/subject/zzbtwftx.html