ZKMocks.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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);
  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)
  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. virtual std::string toString() const ;
  283. };
  284. // zoo_get() response
  285. class ZooGetResponse: public Response
  286. {
  287. public:
  288. ZooGetResponse(const char* data, int len,int32_t xid=0,int rc=ZOK,const Stat& stat=NodeStat())
  289. :xid_(xid),data_(data,len),rc_(rc),stat_(stat)
  290. {
  291. }
  292. virtual std::string toString() const;
  293. virtual void setXID(int32_t xid) {xid_=xid;}
  294. private:
  295. int32_t xid_;
  296. std::string data_;
  297. int rc_;
  298. Stat stat_;
  299. };
  300. // zoo_exists(), zoo_set() response
  301. class ZooStatResponse: public Response
  302. {
  303. public:
  304. ZooStatResponse(int32_t xid=0,int rc=ZOK,const Stat& stat=NodeStat())
  305. :xid_(xid),rc_(rc),stat_(stat)
  306. {
  307. }
  308. virtual std::string toString() const;
  309. virtual void setXID(int32_t xid) {xid_=xid;}
  310. private:
  311. int32_t xid_;
  312. int rc_;
  313. Stat stat_;
  314. };
  315. // zoo_get_children()
  316. class ZooGetChildrenResponse: public Response
  317. {
  318. public:
  319. typedef std::vector<std::string> StringVector;
  320. ZooGetChildrenResponse(const StringVector& v,int rc=ZOK):
  321. xid_(0),strings_(v),rc_(rc)
  322. {
  323. }
  324. virtual std::string toString() const;
  325. virtual void setXID(int32_t xid) {xid_=xid;}
  326. int32_t xid_;
  327. StringVector strings_;
  328. int rc_;
  329. };
  330. // PING response
  331. class PingResponse: public Response
  332. {
  333. public:
  334. virtual std::string toString() const;
  335. };
  336. // watcher znode event
  337. class ZNodeEvent: public Response
  338. {
  339. public:
  340. ZNodeEvent(int type,const char* path):type_(type),path_(path){}
  341. virtual std::string toString() const;
  342. private:
  343. int type_;
  344. std::string path_;
  345. };
  346. // ****************************************************************************
  347. // Zookeeper server simulator
  348. class ZookeeperServer: public Mock_socket
  349. {
  350. public:
  351. ZookeeperServer():
  352. serverDownSkipCount_(-1),sessionExpired(false),connectionLost(false)
  353. {
  354. connectReturns=-1;
  355. connectErrno=EWOULDBLOCK;
  356. }
  357. virtual ~ZookeeperServer(){
  358. clearRecvQueue();
  359. clearRespQueue();
  360. }
  361. virtual int callClose(int fd){
  362. if(fd!=FD)
  363. return LIBC_SYMBOLS.close(fd);
  364. clearRecvQueue();
  365. clearRespQueue();
  366. return Mock_socket::callClose(fd);
  367. }
  368. // connection handling
  369. // what to do when the handshake request comes in?
  370. int serverDownSkipCount_;
  371. // this will cause getsockopt(zh->fd,SOL_SOCKET,SO_ERROR,&error,&len) return
  372. // a failure after skipCount dropped to zero, thus simulating a server down
  373. // condition
  374. // passing skipCount==-1 will make every connect attempt succeed
  375. void setServerDown(int skipCount=0){
  376. serverDownSkipCount_=skipCount;
  377. optvalSO_ERROR=0;
  378. }
  379. virtual void setSO_ERROR(void *optval,socklen_t len){
  380. if(serverDownSkipCount_!=-1){
  381. if(serverDownSkipCount_==0)
  382. optvalSO_ERROR=ECONNREFUSED;
  383. else
  384. serverDownSkipCount_--;
  385. }
  386. Mock_socket::setSO_ERROR(optval,len);
  387. }
  388. // this is a trigger that gets reset back to false
  389. // a connect request will return a non-matching session id thus causing
  390. // the client throw SESSION_EXPIRED
  391. volatile bool sessionExpired;
  392. void returnSessionExpired(){ sessionExpired=true; }
  393. // this is a one shot trigger that gets reset back to false
  394. // next recv call will return 0 length, thus simulating a connecton loss
  395. volatile bool connectionLost;
  396. void setConnectionLost() {connectionLost=true;}
  397. // recv
  398. // this queue is used for server responses: client's recv() system call
  399. // returns next available message from this queue
  400. typedef std::pair<Response*,int> Element;
  401. typedef std::deque<Element> ResponseList;
  402. ResponseList recvQueue;
  403. mutable Mutex recvQMx;
  404. AtomicInt recvHasMore;
  405. ZookeeperServer& addRecvResponse(Response* resp, int errnum=0){
  406. synchronized(recvQMx);
  407. recvQueue.push_back(Element(resp,errnum));
  408. ++recvHasMore;
  409. return *this;
  410. }
  411. ZookeeperServer& addRecvResponse(int errnum){
  412. synchronized(recvQMx);
  413. recvQueue.push_back(Element(0,errnum));
  414. ++recvHasMore;
  415. return *this;
  416. }
  417. ZookeeperServer& addRecvResponse(const Element& e){
  418. synchronized(recvQMx);
  419. recvQueue.push_back(e);
  420. ++recvHasMore;
  421. return *this;
  422. }
  423. void clearRecvQueue(){
  424. synchronized(recvQMx);
  425. recvHasMore=0;
  426. for(unsigned i=0; i<recvQueue.size();i++)
  427. delete recvQueue[i].first;
  428. recvQueue.clear();
  429. }
  430. virtual ssize_t callRecv(int s,void *buf,size_t len,int flags);
  431. virtual bool hasMoreRecv() const;
  432. // the operation response queue holds zookeeper operation responses till the
  433. // operation request has been sent to the server. After that, the operation
  434. // response gets moved on to the recv queue (see above) ready to be read by
  435. // the next recv() system call
  436. // send operation doesn't try to match request to the response
  437. ResponseList respQueue;
  438. mutable Mutex respQMx;
  439. ZookeeperServer& addOperationResponse(Response* resp, int errnum=0){
  440. synchronized(respQMx);
  441. respQueue.push_back(Element(resp,errnum));
  442. return *this;
  443. }
  444. void clearRespQueue(){
  445. synchronized(respQMx);
  446. for(unsigned i=0; i<respQueue.size();i++)
  447. delete respQueue[i].first;
  448. respQueue.clear();
  449. }
  450. AtomicInt closeSent;
  451. virtual void notifyBufferSent(const std::string& buffer);
  452. // simulates an arrival of a client request
  453. // a callback to be implemented by subclasses (no-op by default)
  454. virtual void onMessageReceived(const RequestHeader& rh, iarchive* ia);
  455. };
  456. #endif /*ZKMOCKS_H_*/