Cosmetic changes
[invirt/third/libt4.git] / rpc / rpc.h
index 84c12f3..ddf15f9 100644 (file)
--- a/rpc/rpc.h
+++ b/rpc/rpc.h
 #define rpc_h
 
 #include "types.h"
-#include <sys/socket.h>
-#include <netinet/in.h>
 
-#include "thr_pool.h"
+#include "rpc_protocol.h"
+#include "thread_pool.h"
 #include "marshall.h"
 #include "marshall_wrap.h"
 #include "connection.h"
+#include "threaded_log.h"
+
+using std::chrono::milliseconds;
 
 namespace rpc {
     static constexpr milliseconds to_max{12000};
     static constexpr milliseconds to_min{100};
 }
 
-class rpc_const {
-    public:
-        static const unsigned int bind = 1;   // handler number reserved for bind
-        static const int timeout_failure = -1;
-        static const int unmarshal_args_failure = -2;
-        static const int unmarshal_reply_failure = -3;
-        static const int atmostonce_failure = -4;
-        static const int oldsrv_failure = -5;
-        static const int bind_failure = -6;
-        static const int cancel_failure = -7;
-};
+template<class P, class R, class ...Args>
+struct is_valid_call : false_type {};
+
+template<class S, class R, class ...Args>
+struct is_valid_call<S(R &, Args...), R, Args...> : true_type {};
+
+template<class P, class F>
+struct is_valid_registration : false_type {};
+
+template<class S, class R, class ...Args>
+struct is_valid_registration<
+    S(R &, typename std::decay<Args>::type...),
+    S(R &, Args...)> : true_type {};
+
+template<class P, class C, class S, class R, class ...Args>
+struct is_valid_registration<
+    P,
+    S(C::*)(R &, Args...)> : is_valid_registration<P, S(R &, Args...)> {};
 
 // rpc client endpoint.
 // manages a xid space per destination socket
 // threaded: multiple threads can be sending RPCs,
 class rpcc : private connection_delegate {
     private:
+        using proc_id_t = rpc_protocol::proc_id_t;
+        template <class S>
+        using proc_t = rpc_protocol::proc_t<S>;
+        using nonce_t = rpc_protocol::nonce_t;
+        using xid_t = rpc_protocol::xid_t;
 
         // manages per rpc info
         struct caller {
-            caller(int _xid, string *_rep) : xid(_xid), rep(_rep) {}
+            caller(xid_t _xid, string *_rep) : xid(_xid), rep(_rep) {}
 
             int xid;
             string *rep;
             int intret;
             bool done = false;
-            mutex m;
+            std::mutex m;
             cond c;
         };
 
-        void get_refconn(shared_ptr<connection> & ch);
-        void update_xid_rep(int xid);
+        void get_latest_connection(shared_ptr<connection> & ch);
+        void update_xid_rep(xid_t xid, lock & m_lock);
 
 
         sockaddr_in dst_;
-        unsigned int clt_nonce_;
-        unsigned int srv_nonce_;
-        bool bind_done_;
-        int xid_;
-        int lossytest_;
-        bool retrans_;
-        bool reachable_;
+        nonce_t clt_nonce_;
+        nonce_t srv_nonce_ = 0;
+        bool bind_done_ = false;
+        int lossytest_ = 0;
+        bool reachable_ = true;
 
         shared_ptr<connection> chan_;
 
-        mutex m_; // protect insert/delete to calls[]
-        mutex chan_m_;
+        std::mutex m_; // protect insert/delete to calls[]
+        std::mutex chan_m_;
+        std::mutex bind_m_; // protect bind operations
 
-        bool destroy_wait_;
+        bool destroy_wait_ = false;
         cond destroy_wait_c_;
 
-        map<int, caller *> calls_;
-        list<int> xid_rep_window_;
+        std::map<int, caller *> calls_;
+
+        // xid starts with 1 and latest received reply starts with 0
+        xid_t xid_ = 1;
+        std::list<xid_t> xid_rep_window_ = {0};
 
         struct request {
             void clear() { buf.clear(); xid = -1; }
             bool isvalid() { return xid != -1; }
             string buf;
-            int xid = -1;
+            xid_t xid = -1;
         };
         request dup_req_;
-        int xid_rep_done_;
+        int xid_rep_done_ = -1;
 
-        int call1(proc_t proc, marshall &req, string &rep, milliseconds to);
+        int call_marshalled(proc_id_t proc, milliseconds to, string & rep, marshall & req);
 
         template<class R>
-        int call_m(proc_t proc, marshall &req, R & r, milliseconds to) {
+        inline int call_m(proc_id_t proc, milliseconds to, R & r, marshall && req) {
             string rep;
-            int intret = call1(proc, req, rep, to);
-            unmarshall u(rep, true);
-            if (intret < 0) return intret;
-            u >> r;
-            if (u.okdone() != true) {
-                cerr << "rpcc::call_m: failed to unmarshall the reply.  You are probably " <<
-                    "calling RPC 0x" << hex << proc << " with the wrong return type." << endl;
-                VERIFY(0);
-                return rpc_const::unmarshal_reply_failure;
-            }
+            int intret = call_marshalled(proc, to, rep, req);
+            if (intret >= 0)
+                VERIFY(unmarshall(rep, true, r).okdone()); // guaranteed by static type checking
             return intret;
         }
 
@@ -100,32 +109,43 @@ class rpcc : private connection_delegate {
 
     public:
 
-        rpcc(const string & d, bool retrans=true);
+        rpcc(const string & d);
         ~rpcc();
 
-        unsigned int id() { return clt_nonce_; }
-
         int bind(milliseconds to = rpc::to_max);
 
+        // Manages a cache of RPC connections.  Usage:
+        //     if (auto cl = rpcc::bind_cached(dst))
+        //         ret = cl->call(...);
+        // where the string dst has the form "host:port".  Because bind_cached()
+        // may block, callers should probably not hold mutexes.
+        static shared_ptr<rpcc> bind_cached(const string & destination);
+        static void unbind_cached(const string & destination);
+
         void set_reachable(bool r) { reachable_ = r; }
 
-        void cancel();
+        void cancel(lock & m_lock);
 
-        template<class R, typename ...Args>
-        inline int call(proc_t proc, R & r, const Args&... args) {
+        template<class P, class R, typename ...Args>
+        inline int call(proc_t<P> proc, R & r, const Args & ... args) {
             return call_timeout(proc, rpc::to_max, r, args...);
         }
 
-        template<class R, typename ...Args>
-        inline int call_timeout(proc_t proc, milliseconds to, R & r, const Args&... args) {
-            marshall m{args...};
-            return call_m(proc, m, r, to);
+        template<class P, class R, typename ...Args>
+        inline int call_timeout(proc_t<P> proc, milliseconds to, R & r, const Args & ... args) {
+            static_assert(is_valid_call<P, R, Args...>::value, "RPC called with incorrect argument types");
+            return call_m(proc.id, to, r, std::forward<marshall>(marshall(args...)));
         }
 };
 
 // rpc server endpoint.
 class rpcs : private connection_delegate {
     private:
+        using proc_id_t = rpc_protocol::proc_id_t;
+        template <class S>
+        using proc_t = rpc_protocol::proc_t<S>;
+        using nonce_t = rpc_protocol::nonce_t;
+        using xid_t = rpc_protocol::xid_t;
 
         typedef enum {
             NEW,  // new RPC, not a duplicate
@@ -139,74 +159,66 @@ class rpcs : private connection_delegate {
         // has been sent; in that case buf points to a copy of the reply,
         // and sz holds the size of the reply.
         struct reply_t {
-            reply_t (int _xid) : xid(_xid), cb_present(false) {}
-            reply_t (int _xid, const string & _buf) : xid(_xid), cb_present(true), buf(_buf) {}
-            int xid;
+            reply_t (xid_t _xid) : xid(_xid), cb_present(false) {}
+            reply_t (xid_t _xid, const string & _buf) : xid(_xid), cb_present(true), buf(_buf) {}
+            xid_t xid;
             bool cb_present; // whether the reply buffer is valid
             string buf;      // the reply buffer
         };
 
         in_port_t port_;
-        unsigned int nonce_;
+        nonce_t nonce_;
 
         // provide at most once semantics by maintaining a window of replies
         // per client that that client hasn't acknowledged receiving yet.
         // indexed by client nonce.
-        map<unsigned int, list<reply_t>> reply_window_;
+        std::map<nonce_t, std::list<reply_t>> reply_window_;
 
-        void free_reply_window(void);
-        void add_reply(unsigned int clt_nonce, int xid, const string & b);
+        void add_reply(nonce_t clt_nonce, xid_t xid, const string & b);
 
-        rpcstate_t checkduplicate_and_update(unsigned int clt_nonce, 
-                int xid, int rep_xid, string & b);
-
-        void updatestat(proc_t proc);
+        rpcstate_t check_duplicate_and_update(nonce_t clt_nonce, xid_t xid,
+                xid_t rep_xid, string & b);
 
         // latest connection to the client
-        map<unsigned int, shared_ptr<connection>> conns_;
-
-        // counting
-        const size_t counting_;
-        size_t curr_counts_;
-        map<proc_t, size_t> counts_;
+        std::map<nonce_t, shared_ptr<connection>> conns_;
 
-        bool reachable_;
+        bool reachable_ = true;
 
         // map proc # to function
-        map<proc_t, handler *> procs_;
+        std::map<proc_id_t, handler *> procs_;
 
-        mutex procs_m_; // protect insert/delete to procs[]
-        mutex count_m_;  // protect modification of counts
-        mutex reply_window_m_; // protect reply window et al
-        mutex conns_m_; // protect conns_
+        std::mutex procs_m_; // protect insert/delete to procs[]
+        std::mutex reply_window_m_; // protect reply window et al
+        std::mutex conns_m_; // protect conns_
 
         void dispatch(shared_ptr<connection> c, const string & buf);
 
-        // internal handler registration
-        void reg1(proc_t proc, handler *);
-
-        unique_ptr<thread_pool> dispatchpool_;
-        unique_ptr<tcpsconn> listener_;
+        unique_ptr<thread_pool> dispatchpool_{new thread_pool(6)};
+        unique_ptr<connection_listener> listener_;
 
         // RPC handler for clients binding
-        int rpcbind(unsigned int &r, int a);
+        rpc_protocol::status rpcbind(nonce_t & r);
 
         bool got_pdu(const shared_ptr<connection> & c, const string & b);
 
     public:
 
-        rpcs(in_port_t port, size_t counts=0);
+        rpcs(in_port_t port);
         ~rpcs();
 
         void set_reachable(bool r) { reachable_ = r; }
 
-        template<class F, class C=void> void reg(proc_t proc, F f, C *c=nullptr) {
+        template<class P, class F, class C=void> inline void reg(proc_t<P> proc, F f, C *c=nullptr) {
+            static_assert(is_valid_registration<P, F>::value, "RPC handler registered with incorrect argument types");
             struct ReturnOnFailure {
                 static inline int unmarshall_args_failure() {
-                    return rpc_const::unmarshal_args_failure;
+                    return rpc_protocol::unmarshall_args_failure;
                 }
             };
-            reg1(proc, marshalled_func<F, ReturnOnFailure>::wrap(f, c));
+            lock pl(procs_m_);
+            VERIFY(procs_.count(proc.id) == 0);
+            procs_[proc.id] = marshalled_func<F, ReturnOnFailure>::wrap(f, c);
+            VERIFY(procs_.count(proc.id) >= 1);
         }
 
         void start();