ZKMocks.cc 16.3 KB
Newer Older
1
2
3
4
5
6
7
8
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
Andrew Kornev's avatar
Andrew Kornev committed
9
10
11
12
13
14
15
16
17
18
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Andrew Kornev's avatar
Andrew Kornev committed
19
20
21
#include <arpa/inet.h>  // for htonl
#include <memory>

Andrew Kornev's avatar
Andrew Kornev committed
22
#include <zookeeper.h>
Andrew Kornev's avatar
Andrew Kornev committed
23
24
#include <proto.h>

Andrew Kornev's avatar
Andrew Kornev committed
25
26
27
#ifdef THREADED
#include "PthreadMocks.h"
#endif
28
29
#include "ZKMocks.h"

Andrew Kornev's avatar
Andrew Kornev committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using namespace std;

TestClientId testClientId;
const char* TestClientId::PASSWD="1234567890123456";

HandshakeRequest* HandshakeRequest::parse(const std::string& buf){
    auto_ptr<HandshakeRequest> req(new HandshakeRequest);

    memcpy(&req->protocolVersion,buf.data(), sizeof(req->protocolVersion));
    req->protocolVersion = htonl(req->protocolVersion);
    
    int offset=sizeof(req->protocolVersion);
    
    memcpy(&req->lastZxidSeen,buf.data()+offset,sizeof(req->lastZxidSeen));
    req->lastZxidSeen = htonll(req->lastZxidSeen);
    offset+=sizeof(req->lastZxidSeen);
    
    memcpy(&req->timeOut,buf.data()+offset,sizeof(req->timeOut));
    req->timeOut = htonl(req->timeOut);
    offset+=sizeof(req->timeOut);
    
    memcpy(&req->sessionId,buf.data()+offset,sizeof(req->sessionId));
    req->sessionId = htonll(req->sessionId);
    offset+=sizeof(req->sessionId);
    
    memcpy(&req->passwd_len,buf.data()+offset,sizeof(req->passwd_len));
    req->passwd_len = htonl(req->passwd_len);
    offset+=sizeof(req->passwd_len);
    
    memcpy(req->passwd,buf.data()+offset,sizeof(req->passwd));
    if(testClientId.client_id==req->sessionId &&
            !memcmp(testClientId.passwd,req->passwd,sizeof(req->passwd)))
        return req.release();
    // the request didn't match -- may not be a handshake request after all
    return 0;
}

Andrew Kornev's avatar
Andrew Kornev committed
67
68
// *****************************************************************************
// watcher action implementation
69
70
71
void activeWatcher(zhandle_t *zh, int type, int state, const char *path,void* ctx){
    if(zh==0 || ctx==0) return;
    WatcherAction* action=(WatcherAction*)ctx;
Andrew Kornev's avatar
Andrew Kornev committed
72
    
Flavio Paiva Junqueira's avatar
Flavio Paiva Junqueira committed
73
74
    if(type==ZOO_SESSION_EVENT){
        if(state==ZOO_EXPIRED_SESSION_STATE)
75
            action->onSessionExpired(zh);
Flavio Paiva Junqueira's avatar
Flavio Paiva Junqueira committed
76
        else if(state==ZOO_CONNECTING_STATE)
77
            action->onConnectionLost(zh);
Flavio Paiva Junqueira's avatar
Flavio Paiva Junqueira committed
78
        else if(state==ZOO_CONNECTED_STATE)
79
            action->onConnectionEstablished(zh);
Flavio Paiva Junqueira's avatar
Flavio Paiva Junqueira committed
80
    }else if(type==ZOO_CHANGED_EVENT)
Andrew Kornev's avatar
Andrew Kornev committed
81
        action->onNodeValueChanged(zh,path);
Flavio Paiva Junqueira's avatar
Flavio Paiva Junqueira committed
82
    else if(type==ZOO_DELETED_EVENT)
83
        action->onNodeDeleted(zh,path);
Flavio Paiva Junqueira's avatar
Flavio Paiva Junqueira committed
84
    else if(type==ZOO_CHILD_EVENT)
85
        action->onChildChanged(zh,path);
Andrew Kornev's avatar
Andrew Kornev committed
86
87
    // TODO: implement for the rest of the event types
    // ...
88
    action->setWatcherTriggered();    
Andrew Kornev's avatar
Andrew Kornev committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
}
SyncedBoolCondition WatcherAction::isWatcherTriggered() const{
    return SyncedBoolCondition(triggered_,mx_);
}

// *****************************************************************************
// a set of async completion signatures
void asyncCompletion(int rc, ACL_vector *acl,Stat *stat, const void *data){
    assert("Completion data is NULL"&&data);
    static_cast<AsyncCompletion*>((void*)data)->aclCompl(rc,acl,stat);
}
void asyncCompletion(int rc, const char *value, int len, const Stat *stat, 
        const void *data){    
    assert("Completion data is NULL"&&data);
    static_cast<AsyncCompletion*>((void*)data)->dataCompl(rc,value,len,stat);    
}
void asyncCompletion(int rc, const Stat *stat, const void *data){    
    assert("Completion data is NULL"&&data);
    static_cast<AsyncCompletion*>((void*)data)->statCompl(rc,stat);
}
void asyncCompletion(int rc, const char *value, const void *data){
    assert("Completion data is NULL"&&data);
    static_cast<AsyncCompletion*>((void*)data)->stringCompl(rc,value);
}
void asyncCompletion(int rc,const String_vector *strings, const void *data){    
    assert("Completion data is NULL"&&data);
    static_cast<AsyncCompletion*>((void*)data)->stringsCompl(rc,strings);
}
void asyncCompletion(int rc, const void *data){    
    assert("Completion data is NULL"&&data);
    static_cast<AsyncCompletion*>((void*)data)->voidCompl(rc);
}

// *****************************************************************************
// a predicate implementation
bool IOThreadStopped::operator()() const{
#ifdef THREADED
    adaptor_threads* adaptor=(adaptor_threads*)zh_->adaptor_priv;
    return CheckedPthread::isTerminated(adaptor->io);
#else
    assert("IOThreadStopped predicate is only for use with THREADED client"&& false);
    return false;
#endif
}

Andrew Kornev's avatar
Andrew Kornev committed
134
135
136
137
138
139
140
141
142
143
144
//******************************************************************************
//
DECLARE_WRAPPER(int,flush_send_queue,(zhandle_t*zh, int timeout))
{
    if(!Mock_flush_send_queue::mock_)
        return CALL_REAL(flush_send_queue,(zh,timeout));
    return Mock_flush_send_queue::mock_->call(zh,timeout);
}

Mock_flush_send_queue* Mock_flush_send_queue::mock_=0;

145
146
147
148
149
150
151
152
153
154
155
//******************************************************************************
//
DECLARE_WRAPPER(int32_t,get_xid,())
{
    if(!Mock_get_xid::mock_)
        return CALL_REAL(get_xid,());
    return Mock_get_xid::mock_->call();
}

Mock_get_xid* Mock_get_xid::mock_=0;

156
157
158
//******************************************************************************
// activateWatcher mock

159
DECLARE_WRAPPER(void,activateWatcher,(zhandle_t *zh, watcher_registration_t* reg, int rc))
160
161
{
    if(!Mock_activateWatcher::mock_){
162
        CALL_REAL(activateWatcher,(zh, reg,rc));
163
    }else{
164
        Mock_activateWatcher::mock_->call(zh, reg,rc);
165
166
167
168
169
170
171
172
    }
}
Mock_activateWatcher* Mock_activateWatcher::mock_=0;

class ActivateWatcherWrapper: public Mock_activateWatcher{
public:
    ActivateWatcherWrapper():ctx_(0),activated_(false){}
    
173
174
    virtual void call(zhandle_t *zh, watcher_registration_t* reg, int rc){
        CALL_REAL(activateWatcher,(zh, reg,rc));
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        synchronized(mx_);
        if(reg->context==ctx_){
            activated_=true;
            ctx_=0;
        }
    }
    
    void setContext(void* ctx){
        synchronized(mx_);
        ctx_=ctx;
        activated_=false;
    }
    
    SyncedBoolCondition isActivated() const{
        return SyncedBoolCondition(activated_,mx_);
    }
    mutable Mutex mx_;
    void* ctx_;
    bool activated_;
};

WatcherActivationTracker::WatcherActivationTracker():
    wrapper_(new ActivateWatcherWrapper)
{    
}

WatcherActivationTracker::~WatcherActivationTracker(){
    delete wrapper_;
}

void WatcherActivationTracker::track(void* ctx){
    wrapper_->setContext(ctx);
}

SyncedBoolCondition WatcherActivationTracker::isWatcherActivated() const{
    return wrapper_->isActivated();
}

//******************************************************************************
//
215
DECLARE_WRAPPER(void,deliverWatchers,(zhandle_t* zh,int type,int state, const char* path, watcher_object_list_t **list))
216
217
{
    if(!Mock_deliverWatchers::mock_){
218
        CALL_REAL(deliverWatchers,(zh,type,state,path, list));
219
    }else{
220
        Mock_deliverWatchers::mock_->call(zh,type,state,path, list);
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    }
}

Mock_deliverWatchers* Mock_deliverWatchers::mock_=0;

struct RefCounterValue{
    RefCounterValue(zhandle_t* const& zh,int32_t expectedCounter,Mutex& mx):
        zh_(zh),expectedCounter_(expectedCounter),mx_(mx){}
    bool operator()() const{
        {
            synchronized(mx_);
            if(zh_==0)
                return false;
        }
        return inc_ref_counter(zh_,0)==expectedCounter_;
    }
    zhandle_t* const& zh_;
    int32_t expectedCounter_;
    Mutex& mx_;
};


class DeliverWatchersWrapper: public Mock_deliverWatchers{
public:
    DeliverWatchersWrapper(int type,int state,bool terminate):
        type_(type),state_(state),
        allDelivered_(false),terminate_(terminate),zh_(0),deliveryCounter_(0){}
248
    virtual void call(zhandle_t* zh,int type,int state, const char* path, watcher_object_list **list){
249
250
251
252
253
        {
            synchronized(mx_);
            zh_=zh;
            allDelivered_=false;
        }
254
        CALL_REAL(deliverWatchers,(zh,type,state,path, list));
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        if(type_==type && state_==state){
            if(terminate_){
                // prevent zhandle_t from being prematurely distroyed;
                // this will also ensure that zookeeper_close() cleanups the thread
                // resources by calling finish_adaptor()
                inc_ref_counter(zh,1);
                terminateZookeeperThreads(zh);
            }
            synchronized(mx_);
            allDelivered_=true;
            deliveryCounter_++;
        }
    }
    SyncedBoolCondition isDelivered() const{
        if(terminate_){
            int i=ensureCondition(RefCounterValue(zh_,1,mx_),1000);
            assert(i<1000);
        }
        return SyncedBoolCondition(allDelivered_,mx_);
    }
    void resetDeliveryCounter(){
        synchronized(mx_);
        deliveryCounter_=0;
    }
    SyncedIntegerEqual deliveryCounterEquals(int expected) const{
        if(terminate_){
            int i=ensureCondition(RefCounterValue(zh_,1,mx_),1000);
            assert(i<1000);
        }
        return SyncedIntegerEqual(deliveryCounter_,expected,mx_);
    }
    int type_;
    int state_;
    mutable Mutex mx_;
    bool allDelivered_;
    bool terminate_;
    zhandle_t* zh_;
    int deliveryCounter_;
};

WatcherDeliveryTracker::WatcherDeliveryTracker(
        int type,int state,bool terminateCompletionThread):
    deliveryWrapper_(new DeliverWatchersWrapper(
            type,state,terminateCompletionThread)){
}

WatcherDeliveryTracker::~WatcherDeliveryTracker(){
    delete deliveryWrapper_;
}

SyncedBoolCondition WatcherDeliveryTracker::isWatcherProcessingCompleted() const{
    return deliveryWrapper_->isDelivered();
}

void WatcherDeliveryTracker::resetDeliveryCounter(){
    deliveryWrapper_->resetDeliveryCounter();
}

SyncedIntegerEqual WatcherDeliveryTracker::deliveryCounterEquals(int expected) const{
    return deliveryWrapper_->deliveryCounterEquals(expected);
}

Andrew Kornev's avatar
Andrew Kornev committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
//******************************************************************************
//
string HandshakeResponse::toString() const {
    string buf;
    int32_t tmp=htonl(protocolVersion);
    buf.append((char*)&tmp,sizeof(tmp));
    tmp=htonl(timeOut);
    buf.append((char*)&tmp,sizeof(tmp));
    int64_t tmp64=htonll(sessionId);
    buf.append((char*)&tmp64,sizeof(sessionId));
    tmp=htonl(passwd_len);
    buf.append((char*)&tmp,sizeof(tmp));
    buf.append(passwd,sizeof(passwd));
    // finally set the buffer length
    tmp=htonl(buf.size()+sizeof(tmp));
    buf.insert(0,(char*)&tmp, sizeof(tmp));
    return buf;
}

string ZooGetResponse::toString() const{
    oarchive* oa=create_buffer_oarchive();
    
    ReplyHeader h = {xid_,1,ZOK};
    serialize_ReplyHeader(oa, "hdr", &h);
    
    GetDataResponse resp;
343
344
	char buf[1024];
    assert("GetDataResponse is too long"&&data_.size()<=sizeof(buf));
Andrew Kornev's avatar
Andrew Kornev committed
345
    resp.data.len=data_.size();
346
    resp.data.buff=buf;
Andrew Kornev's avatar
Andrew Kornev committed
347
348
349
350
    data_.copy(resp.data.buff, data_.size());
    resp.stat=stat_;
    serialize_GetDataResponse(oa, "reply", &resp);
    int32_t len=htonl(get_buffer_len(oa));
351
352
    string res((char*)&len,sizeof(len));
    res.append(get_buffer(oa),get_buffer_len(oa));
Andrew Kornev's avatar
Andrew Kornev committed
353
354
    
    close_buffer_oarchive(&oa,1);
355
    return res;
Andrew Kornev's avatar
Andrew Kornev committed
356
357
}

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
string ZooStatResponse::toString() const{
    oarchive* oa=create_buffer_oarchive();
    
    ReplyHeader h = {xid_,1,rc_};
    serialize_ReplyHeader(oa, "hdr", &h);
    
    SetDataResponse resp;
    resp.stat=stat_;
    serialize_SetDataResponse(oa, "reply", &resp);
    int32_t len=htonl(get_buffer_len(oa));
    string res((char*)&len,sizeof(len));
    res.append(get_buffer(oa),get_buffer_len(oa));
    
    close_buffer_oarchive(&oa,1);
    return res;
}

string ZooGetChildrenResponse::toString() const{
    oarchive* oa=create_buffer_oarchive();
    
    ReplyHeader h = {xid_,1,rc_};
    serialize_ReplyHeader(oa, "hdr", &h);
 
    GetChildrenResponse resp;
    // populate the string vector
    allocate_String_vector(&resp.children,strings_.size());
    for(int i=0;i<(int)strings_.size();++i)
        resp.children.data[i]=strdup(strings_[i].c_str());
    serialize_GetChildrenResponse(oa, "reply", &resp);
    deallocate_GetChildrenResponse(&resp);
    
    int32_t len=htonl(get_buffer_len(oa));
    string res((char*)&len,sizeof(len));
    res.append(get_buffer(oa),get_buffer_len(oa));
    
    close_buffer_oarchive(&oa,1);
    return res;
}

Andrew Kornev's avatar
Andrew Kornev committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
string ZNodeEvent::toString() const{
    oarchive* oa=create_buffer_oarchive();
    struct WatcherEvent evt = {type_,0,(char*)path_.c_str()};
    struct ReplyHeader h = {WATCHER_EVENT_XID,0,ZOK };
    
    serialize_ReplyHeader(oa, "hdr", &h);
    serialize_WatcherEvent(oa, "event", &evt);
    
    int32_t len=htonl(get_buffer_len(oa));
    string res((char*)&len,sizeof(len));
    res.append(get_buffer(oa),get_buffer_len(oa));
    
    close_buffer_oarchive(&oa,1);
    return res;
}

413
414
415
416
417
418
419
420
421
422
423
424
425
426
string PingResponse::toString() const{
    oarchive* oa=create_buffer_oarchive();
    
    ReplyHeader h = {PING_XID,1,ZOK};
    serialize_ReplyHeader(oa, "hdr", &h);
    
    int32_t len=htonl(get_buffer_len(oa));
    string res((char*)&len,sizeof(len));
    res.append(get_buffer(oa),get_buffer_len(oa));
    
    close_buffer_oarchive(&oa,1);
    return res;
}

Andrew Kornev's avatar
Andrew Kornev committed
427
428
429
//******************************************************************************
// Zookeeper server simulator
// 
430
bool ZookeeperServer::hasMoreRecv() const{
431
  return recvHasMore.get()!=0  || connectionLost;
432
433
}

Andrew Kornev's avatar
Andrew Kornev committed
434
ssize_t ZookeeperServer::callRecv(int s,void *buf,size_t len,int flags){
435
436
437
438
    if(connectionLost){
        recvReturnBuffer.erase();
        return 0;
    }
Andrew Kornev's avatar
Andrew Kornev committed
439
440
441
    // done transmitting the current buffer?
    if(recvReturnBuffer.size()==0){
        synchronized(recvQMx);
442
443
444
445
446
        if(recvQueue.empty()){
            recvErrno=EAGAIN;
            return Mock_socket::callRecv(s,buf,len,flags);
        }
        --recvHasMore;
Andrew Kornev's avatar
Andrew Kornev committed
447
448
449
450
451
452
453
454
455
456
457
        Element& el=recvQueue.front();
        if(el.first!=0){
            recvReturnBuffer=el.first->toString();
            delete el.first;
        }
        recvErrno=el.second;
        recvQueue.pop_front();
    }
    return Mock_socket::callRecv(s,buf,len,flags);
}

458
459
460
461
void ZookeeperServer::onMessageReceived(const RequestHeader& rh, iarchive* ia){
    // no-op by default
}

Andrew Kornev's avatar
Andrew Kornev committed
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
void ZookeeperServer::notifyBufferSent(const std::string& buffer){
    if(HandshakeRequest::isValid(buffer)){
        // could be a connect request
        auto_ptr<HandshakeRequest> req(HandshakeRequest::parse(buffer));
        if(req.get()!=0){
            // handle the handshake
            int64_t sessId=sessionExpired?req->sessionId+1:req->sessionId;
            sessionExpired=false;
            addRecvResponse(new HandshakeResponse(sessId));            
            return;
        }
        // not a connect request -- fall thru
    }
    // parse the buffer to extract the request type and its xid
    iarchive *ia=create_buffer_iarchive((char*)buffer.data(), buffer.size());
    RequestHeader rh;
    deserialize_RequestHeader(ia,"hdr",&rh);
479
    // notify the "server" a client request has arrived
480
481
482
483
484
485
486
487
488
    if (rh.xid == -8) {
        Element e = Element(new ZooStatResponse,0);
        e.first->setXID(-8);
        addRecvResponse(e);
        close_buffer_iarchive(&ia);
        return;
    } else {
        onMessageReceived(rh,ia);
    }
Andrew Kornev's avatar
Andrew Kornev committed
489
    close_buffer_iarchive(&ia);
490
    if(rh.type==CLOSE_OP){
Andrew Kornev's avatar
Andrew Kornev committed
491
        ++closeSent;
Andrew Kornev's avatar
Andrew Kornev committed
492
        return; // no reply for close requests
493
    }
Andrew Kornev's avatar
Andrew Kornev committed
494
495
496
497
498
499
    // get the next response from the response queue and append it to the receive list
    Element e;
    {
        synchronized(respQMx);
        if(respQueue.empty())
            return;
500
501
        e=respQueue.front();
        respQueue.pop_front();
Andrew Kornev's avatar
Andrew Kornev committed
502
503
504
505
506
    }
    e.first->setXID(rh.xid);
    addRecvResponse(e);
}

507
508
void forceConnected(zhandle_t* zh){
    // simulate connected state
Flavio Paiva Junqueira's avatar
Flavio Paiva Junqueira committed
509
    zh->state=ZOO_CONNECTED_STATE;
510
511
512
513
514
    zh->fd=ZookeeperServer::FD;
    zh->input_buffer=0;
    gettimeofday(&zh->last_recv,0);    
    gettimeofday(&zh->last_send,0);    
}
515
516
517
518
519

void terminateZookeeperThreads(zhandle_t* zh){
    // this will cause the zookeeper threads to terminate
    zh->close_requested=1;
}