Line data Source code
1 : //
2 : // Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2015
3 : //
4 : // Copyright: See COPYING file that comes with this distribution
5 : //
6 :
7 : #include "pinger.hpp"
8 : #include <pingpong/iponger.hpp>
9 : #include <wfc/logger.hpp>
10 : #include <wfc/memory.hpp>
11 : #include <iostream>
12 : #include <atomic>
13 : #include <memory>
14 : #include <chrono>
15 : #include <iomanip>
16 :
17 : // #define PINGER_LOG_MESSAGE(message) WFC_LOG_MESSAGE("pinger", message)
18 : // #define PINGER_LOG_DEBUG(message) WFC_LOG_DEBUG("pinger", message)
19 :
20 : namespace demo{ namespace pingpong{
21 :
22 0 : void pinger::initialize()
23 : {
24 0 : std::lock_guard<std::mutex> lk(_mutex);
25 0 : for (const auto& target_name : this->options().target_list )
26 0 : _targets.push_back( this->get_target<iponger2>(target_name) );
27 0 : }
28 :
29 0 : pinger::target_list pinger::get_target_list() const
30 : {
31 0 : std::lock_guard<std::mutex> lk(_mutex);
32 0 : return _targets;
33 : }
34 :
35 0 : void pinger::play(ball::ptr req, ball::handler cb)
36 : {
37 0 : if ( this->notify_ban(req, cb ) )
38 0 : return;
39 :
40 0 : auto tlist = this->get_target_list();
41 0 : if ( tlist.empty() )
42 : {
43 0 : return cb( std::move(req) );
44 : }
45 :
46 0 : std::cout << "play power=" << req->power << std::endl;
47 0 : auto pwait = std::make_shared< std::atomic<size_t> >();
48 0 : auto ptotal = std::make_shared< std::atomic<size_t> >();
49 0 : *pwait = tlist.size();
50 0 : for (auto wt : tlist )
51 : {
52 0 : if ( auto t = wt.lock() )
53 : {
54 0 : auto rereq = std::make_unique<ball>( *req );
55 0 : ++rereq->count;
56 0 : --rereq->power;
57 0 : t->ping( std::move(rereq), [this, pwait, ptotal, cb](ball::ptr res)
58 : {
59 0 : if ( this->system_is_stopped() )
60 0 : return;
61 :
62 0 : if ( res==nullptr )
63 : {
64 0 : DOMAIN_LOG_FATAL("Bad Gateway");
65 0 : return;
66 : }
67 :
68 0 : auto& ref_wait = *pwait;
69 0 : if ( ref_wait != 0 )
70 : {
71 0 : --ref_wait;
72 0 : *ptotal+=res->count;
73 0 : if (ref_wait == 0 )
74 : {
75 0 : res->count = *ptotal;
76 0 : cb( std::move(res) );
77 : }
78 : }
79 0 : });
80 0 : }
81 0 : }
82 : }
83 :
84 0 : void pinger::pong( ball::ptr req, ball::handler cb, io_id_t, ball_handler reping )
85 : {
86 0 : if ( this->notify_ban(req, cb ) )
87 0 : return;
88 :
89 0 : std::cout << "pinger::pong power=" << req->power << std::endl;
90 :
91 0 : if ( req->power == 0 )
92 : {
93 0 : cb( std::move(req) );
94 : }
95 : else
96 : {
97 0 : --req->power;
98 0 : ++req->count;
99 0 : reping( std::move(req), [cb](ball::ptr req1)
100 : {
101 0 : cb( std::move(req1) );
102 0 : });
103 : }
104 : }
105 :
106 3 : }}
|