ZKMocks.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef ZKMOCKS_H_
  19. #define ZKMOCKS_H_
  20. #include <zookeeper.h>
  21. #include "src/zk_adaptor.h"
  22. #include "Util.h"
  23. #include "LibCMocks.h"
  24. #include "MocksBase.h"
  25. // *****************************************************************************
  26. // sets internal zhandle_t members to certain values to simulate the client
  27. // connected state. This function should only be used with the single-threaded
  28. // Async API tests!
  29. void forceConnected(zhandle_t* zh, const struct timeval *last_recv_send = NULL);
  30. /**
  31. * Gracefully terminates zookeeper I/O and completion threads.
  32. */
  33. void terminateZookeeperThreads(zhandle_t* zh);
  34. // *****************************************************************************
  35. // Abstract watcher action
  36. struct SyncedBoolCondition;
  37. class WatcherAction{
  38. public:
  39. WatcherAction():triggered_(false){}
  40. virtual ~WatcherAction(){}
  41. virtual void onSessionExpired(zhandle_t*){}
  42. virtual void onConnectionEstablished(zhandle_t*){}
  43. virtual void onConnectionLost(zhandle_t*){}
  44. virtual void onNodeValueChanged(zhandle_t*,const char* path){}
  45. virtual void onNodeDeleted(zhandle_t*,const char* path){}
  46. virtual void onChildChanged(zhandle_t*,const char* path){}
  47. SyncedBoolCondition isWatcherTriggered() const;
  48. void setWatcherTriggered(){
  49. synchronized(mx_);
  50. triggered_=true;
  51. }
  52. protected:
  53. mutable Mutex mx_;
  54. bool triggered_;
  55. };
  56. // zh->context is a pointer to a WatcherAction instance
  57. // based on the event type and state, the watcher calls a specific watcher
  58. // action method
  59. void activeWatcher(zhandle_t *zh, int type, int state, const char *path,void* ctx);
  60. // *****************************************************************************
  61. // a set of async completion signatures
  62. class AsyncCompletion{
  63. public:
  64. virtual ~AsyncCompletion(){}
  65. virtual void aclCompl(int rc, ACL_vector *acl,Stat *stat){}
  66. virtual void dataCompl(int rc, const char *value, int len, const Stat *stat){}
  67. virtual void statCompl(int rc, const Stat *stat){}
  68. virtual void stringCompl(int rc, const char *value){}
  69. virtual void stringsCompl(int rc,const String_vector *strings){}
  70. virtual void voidCompl(int rc){}
  71. };
  72. void asyncCompletion(int rc, ACL_vector *acl,Stat *stat, const void *data);
  73. void asyncCompletion(int rc, const char *value, int len, const Stat *stat,
  74. const void *data);
  75. void asyncCompletion(int rc, const Stat *stat, const void *data);
  76. void asyncCompletion(int rc, const char *value, const void *data);
  77. void asyncCompletion(int rc,const String_vector *strings, const void *data);
  78. void asyncCompletion(int rc, const void *data);
  79. // *****************************************************************************
  80. // some common predicates to use with ensureCondition():
  81. // checks if the connection is established
  82. struct ClientConnected{
  83. ClientConnected(zhandle_t* zh):zh_(zh){}
  84. bool operator()() const{
  85. return zoo_state(zh_)==ZOO_CONNECTED_STATE;
  86. }
  87. zhandle_t* zh_;
  88. };
  89. // check in the session expired
  90. struct SessionExpired{
  91. SessionExpired(zhandle_t* zh):zh_(zh){}
  92. bool operator()() const{
  93. return zoo_state(zh_)==ZOO_EXPIRED_SESSION_STATE;
  94. }
  95. zhandle_t* zh_;
  96. };
  97. // checks if the IO thread has stopped; CheckedPthread must be active
  98. struct IOThreadStopped{
  99. IOThreadStopped(zhandle_t* zh):zh_(zh){}
  100. bool operator()() const;
  101. zhandle_t* zh_;
  102. };
  103. // a synchronized boolean condition
  104. struct SyncedBoolCondition{
  105. SyncedBoolCondition(const bool& cond,Mutex& mx):cond_(cond),mx_(mx){}
  106. bool operator()() const{
  107. synchronized(mx_);
  108. return cond_;
  109. }
  110. const bool& cond_;
  111. Mutex& mx_;
  112. };
  113. // a synchronized integer comparison
  114. struct SyncedIntegerEqual{
  115. SyncedIntegerEqual(const int& cond,int expected,Mutex& mx):
  116. cond_(cond),expected_(expected),mx_(mx){}
  117. bool operator()() const{
  118. synchronized(mx_);
  119. return cond_==expected_;
  120. }
  121. const int& cond_;
  122. const int expected_;
  123. Mutex& mx_;
  124. };
  125. // *****************************************************************************
  126. // make sure to call zookeeper_close() even in presence of exceptions
  127. struct CloseFinally{
  128. CloseFinally(zhandle_t** zh):zh_(zh){}
  129. ~CloseFinally(){
  130. execute();
  131. }
  132. int execute(){
  133. if(zh_==0)return ZOK;
  134. zhandle_t* lzh=*zh_;
  135. *zh_=0;
  136. disarm();
  137. return zookeeper_close(lzh);
  138. }
  139. void disarm(){zh_=0;}
  140. zhandle_t ** zh_;
  141. };
  142. struct TestClientId: clientid_t{
  143. static const int SESSION_ID=123456789;
  144. static const char* PASSWD;
  145. TestClientId(){
  146. client_id=SESSION_ID;
  147. memcpy(passwd,PASSWD,sizeof(passwd));
  148. }
  149. };
  150. // *****************************************************************************
  151. // special client id recongnized by the ZK server simulator
  152. extern TestClientId testClientId;
  153. #define TEST_CLIENT_ID &testClientId
  154. // *****************************************************************************
  155. //
  156. struct HandshakeRequest: public connect_req
  157. {
  158. static HandshakeRequest* parse(const std::string& buf);
  159. static bool isValid(const std::string& buf){
  160. // this is just quick and dirty check before we go and parse the request
  161. return buf.size()==HANDSHAKE_REQ_SIZE;
  162. }
  163. };
  164. // *****************************************************************************
  165. // flush_send_queue
  166. class Mock_flush_send_queue: public Mock
  167. {
  168. public:
  169. Mock_flush_send_queue():counter(0),callReturns(ZOK){mock_=this;}
  170. ~Mock_flush_send_queue(){mock_=0;}
  171. int counter;
  172. int callReturns;
  173. virtual int call(zhandle_t* zh, int timeout){
  174. counter++;
  175. return callReturns;
  176. }
  177. static Mock_flush_send_queue* mock_;
  178. };
  179. // *****************************************************************************
  180. // get_xid
  181. class Mock_get_xid: public Mock
  182. {
  183. public:
  184. static const int32_t XID=123456;
  185. Mock_get_xid(int retValue=XID):callReturns(retValue){mock_=this;}
  186. ~Mock_get_xid(){mock_=0;}
  187. int callReturns;
  188. virtual int call(){
  189. return callReturns;
  190. }
  191. static Mock_get_xid* mock_;
  192. };
  193. // *****************************************************************************
  194. // activateWatcher
  195. class Mock_activateWatcher: public Mock{
  196. public:
  197. Mock_activateWatcher(){mock_=this;}
  198. virtual ~Mock_activateWatcher(){mock_=0;}
  199. virtual void call(zhandle_t *zh, watcher_registration_t* reg, int rc){}
  200. static Mock_activateWatcher* mock_;
  201. };
  202. class ActivateWatcherWrapper;
  203. class WatcherActivationTracker{
  204. public:
  205. WatcherActivationTracker();
  206. ~WatcherActivationTracker();
  207. void track(void* ctx);
  208. SyncedBoolCondition isWatcherActivated() const;
  209. private:
  210. ActivateWatcherWrapper* wrapper_;
  211. };
  212. // *****************************************************************************
  213. // deliverWatchers
  214. class Mock_deliverWatchers: public Mock{
  215. public:
  216. Mock_deliverWatchers(){mock_=this;}
  217. virtual ~Mock_deliverWatchers(){mock_=0;}
  218. virtual void call(zhandle_t* zh,int type,int state, const char* path, watcher_object_list **){}
  219. static Mock_deliverWatchers* mock_;
  220. };
  221. class DeliverWatchersWrapper;
  222. class WatcherDeliveryTracker{
  223. public:
  224. // filters deliveries by state and type
  225. WatcherDeliveryTracker(int type,int state,bool terminateCompletionThread=true);
  226. ~WatcherDeliveryTracker();
  227. // if the thread termination requested (see the ctor params)
  228. // this function will wait for the I/O and completion threads to
  229. // terminate before returning a SyncBoolCondition instance
  230. SyncedBoolCondition isWatcherProcessingCompleted() const;
  231. void resetDeliveryCounter();
  232. SyncedIntegerEqual deliveryCounterEquals(int expected) const;
  233. private:
  234. DeliverWatchersWrapper* deliveryWrapper_;
  235. };
  236. // *****************************************************************************
  237. // a zookeeper Stat wrapper
  238. struct NodeStat: public Stat
  239. {
  240. NodeStat(){
  241. czxid=0;
  242. mzxid=0;
  243. ctime=0;
  244. mtime=0;
  245. version=1;
  246. cversion=0;
  247. aversion=0;
  248. ephemeralOwner=0;
  249. }
  250. NodeStat(const Stat& other){
  251. memcpy(this,&other,sizeof(*this));
  252. }
  253. };
  254. // *****************************************************************************
  255. // Abstract server Response
  256. class Response
  257. {
  258. public:
  259. virtual ~Response(){}
  260. virtual void setXID(int32_t xid){}
  261. // this method is used by the ZookeeperServer class to serialize
  262. // the instance of Response
  263. virtual std::string toString() const =0;
  264. };
  265. // *****************************************************************************
  266. // Handshake response
  267. class HandshakeResponse: public Response
  268. {
  269. public:
  270. HandshakeResponse(int64_t sessId=1):
  271. protocolVersion(1),timeOut(10000),sessionId(sessId),
  272. passwd_len(sizeof(passwd)),readOnly(0),omitReadOnly(false)
  273. {
  274. memcpy(passwd,"1234567890123456",sizeof(passwd));
  275. }
  276. int32_t protocolVersion;
  277. int32_t timeOut;
  278. int64_t sessionId;
  279. int32_t passwd_len;
  280. char passwd[16];
  281. char readOnly;
  282. bool omitReadOnly;
  283. virtual std::string toString() const ;
  284. };
  285. // zoo_get() response
  286. class ZooGetResponse: public Response
  287. {
  288. public:
  289. ZooGetResponse(const char* data, int len,int32_t xid=0,int rc=ZOK,const Stat& stat=NodeStat())
  290. :xid_(xid),data_(data,len),rc_(rc),stat_(stat)
  291. {
  292. }
  293. virtual std::string toString() const;
  294. virtual void setXID(int32_t xid) {xid_=xid;}
  295. private:
  296. int32_t xid_;
  297. std::string data_;
  298. int rc_;
  299. Stat stat_;
  300. };
  301. // zoo_exists(), zoo_set() response
  302. class ZooStatResponse: public Response
  303. {
  304. public:
  305. ZooStatResponse(int32_t xid=0,int rc=ZOK,const Stat& stat=NodeStat())
  306. :xid_(xid),rc_(rc),stat_(stat)
  307. {
  308. }
  309. virtual std::string toString() const;
  310. virtual void setXID(int32_t xid) {xid_=xid;}
  311. private:
  312. int32_t xid_;
  313. int rc_;
  314. Stat stat_;
  315. };
  316. // zoo_get_children()
  317. class ZooGetChildrenResponse: public Response
  318. {
  319. public:
  320. typedef std::vector<std::string> StringVector;
  321. ZooGetChildrenResponse(const StringVector& v,int rc=ZOK):
  322. xid_(0),strings_(v),rc_(rc)
  323. {
  324. }
  325. virtual std::string toString() const;
  326. virtual void setXID(int32_t xid) {xid_=xid;}
  327. int32_t xid_;
  328. StringVector strings_;
  329. int rc_;
  330. };
  331. // PING response
  332. class PingResponse: public Response
  333. {
  334. public:
  335. virtual std::string toString() const;
  336. };
  337. // watcher znode event
  338. class ZNodeEvent: public Response
  339. {
  340. public:
  341. ZNodeEvent(int type,const char* path):type_(type),path_(path){}
  342. virtual std::string toString() const;
  343. private:
  344. int type_;
  345. std::string path_;
  346. };
  347. // ****************************************************************************
  348. // Zookeeper server simulator
  349. class ZookeeperServer: public Mock_socket
  350. {
  351. public:
  352. ZookeeperServer():
  353. serverDownSkipCount_(-1),sessionExpired(false),connectionLost(false)
  354. {
  355. connectReturns=-1;
  356. connectErrno=EWOULDBLOCK;
  357. }
  358. virtual ~ZookeeperServer(){
  359. clearRecvQueue();
  360. clearRespQueue();
  361. }
  362. virtual int callClose(int fd){
  363. if(fd!=FD)
  364. return LIBC_SYMBOLS.close(fd);
  365. clearRecvQueue();
  366. clearRespQueue();
  367. return Mock_socket::callClose(fd);
  368. }
  369. // connection handling
  370. // what to do when the handshake request comes in?
  371. int serverDownSkipCount_;
  372. // this will cause getsockopt(zh->fd,SOL_SOCKET,SO_ERROR,&error,&len) return
  373. // a failure after skipCount dropped to zero, thus simulating a server down
  374. // condition
  375. // passing skipCount==-1 will make every connect attempt succeed
  376. void setServerDown(int skipCount=0){
  377. serverDownSkipCount_=skipCount;
  378. optvalSO_ERROR=0;
  379. }
  380. virtual void setSO_ERROR(void *optval,socklen_t len){
  381. if(serverDownSkipCount_!=-1){
  382. if(serverDownSkipCount_==0)
  383. optvalSO_ERROR=ECONNREFUSED;
  384. else
  385. serverDownSkipCount_--;
  386. }
  387. Mock_socket::setSO_ERROR(optval,len);
  388. }
  389. // this is a trigger that gets reset back to false
  390. // a connect request will return a non-matching session id thus causing
  391. // the client throw SESSION_EXPIRED
  392. volatile bool sessionExpired;
  393. void returnSessionExpired(){ sessionExpired=true; }
  394. // this is a one shot trigger that gets reset back to false
  395. // next recv call will return 0 length, thus simulating a connection loss
  396. volatile bool connectionLost;
  397. void setConnectionLost() {connectionLost=true;}
  398. // recv
  399. // this queue is used for server responses: client's recv() system call
  400. // returns next available message from this queue
  401. typedef std::pair<Response*,int> Element;
  402. typedef std::deque<Element> ResponseList;
  403. ResponseList recvQueue;
  404. mutable Mutex recvQMx;
  405. AtomicInt recvHasMore;
  406. ZookeeperServer& addRecvResponse(Response* resp, int errnum=0){
  407. synchronized(recvQMx);
  408. recvQueue.push_back(Element(resp,errnum));
  409. ++recvHasMore;
  410. return *this;
  411. }
  412. ZookeeperServer& addRecvResponse(int errnum){
  413. synchronized(recvQMx);
  414. recvQueue.push_back(Element(0,errnum));
  415. ++recvHasMore;
  416. return *this;
  417. }
  418. ZookeeperServer& addRecvResponse(const Element& e){
  419. synchronized(recvQMx);
  420. recvQueue.push_back(e);
  421. ++recvHasMore;
  422. return *this;
  423. }
  424. void clearRecvQueue(){
  425. synchronized(recvQMx);
  426. recvHasMore=0;
  427. for(unsigned i=0; i<recvQueue.size();i++)
  428. delete recvQueue[i].first;
  429. recvQueue.clear();
  430. }
  431. virtual ssize_t callRecv(int s,void *buf,size_t len,int flags);
  432. virtual bool hasMoreRecv() const;
  433. // the operation response queue holds zookeeper operation responses till the
  434. // operation request has been sent to the server. After that, the operation
  435. // response gets moved on to the recv queue (see above) ready to be read by
  436. // the next recv() system call
  437. // send operation doesn't try to match request to the response
  438. ResponseList respQueue;
  439. mutable Mutex respQMx;
  440. ZookeeperServer& addOperationResponse(Response* resp, int errnum=0){
  441. synchronized(respQMx);
  442. respQueue.push_back(Element(resp,errnum));
  443. return *this;
  444. }
  445. void clearRespQueue(){
  446. synchronized(respQMx);
  447. for(unsigned i=0; i<respQueue.size();i++)
  448. delete respQueue[i].first;
  449. respQueue.clear();
  450. }
  451. AtomicInt closeSent;
  452. virtual void notifyBufferSent(const std::string& buffer);
  453. // simulates an arrival of a client request
  454. // a callback to be implemented by subclasses (no-op by default)
  455. virtual void onMessageReceived(const RequestHeader& rh, iarchive* ia);
  456. };
  457. #endif /*ZKMOCKS_H_*/