http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/c/include/zoo_queue.h ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/c/include/zoo_queue.h b/src/recipes/queue/src/c/include/zoo_queue.h deleted file mode 100644 index dccc763..0000000 --- a/src/recipes/queue/src/c/include/zoo_queue.h +++ /dev/null @@ -1,118 +0,0 @@ -/** - * 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 - * - * 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. - */ - -#ifndef ZOOKEEPER_QUEUE_H_ -#define ZOOKEEPER_QUEUE_H_ - -#include <zookeeper.h> -#include <pthread.h> - -#ifdef __cplusplus -extern "C" { -#endif - - -/** - * \file zoo_queue.h - * \brief zookeeper recipe for queues. - */ - - -struct zkr_queue { - zhandle_t *zh; - char *path; - struct ACL_vector *acl; - pthread_mutex_t pmutex; - char *node_name; - int node_name_length; - char *cached_create_path; -}; - -typedef struct zkr_queue zkr_queue_t; - - -/** - * \brief initializes a zookeeper queue - * - * this method instantiates a zookeeper queue - * \param queue the zookeeper queue to initialize - * \param zh the zookeeper handle to use - * \param path the path in zookeeper to use for the queue - * \param acl the acl to use in zookeeper. - * \return return 0 if successful. - */ -ZOOAPI int zkr_queue_init(zkr_queue_t *queue, zhandle_t* zh, char* path, struct ACL_vector *acl); - -/** - * \brief adds an element to a zookeeper queue - * - * this method adds an element to the back of a zookeeper queue. - * \param queue the zookeeper queue to add the element to - * \param data a pointer to a data buffer - * \param buffer_len the length of the buffer - * \return returns 0 (ZOK) if successful, otherwise returns a zookeeper error code. - */ -ZOOAPI int zkr_queue_offer(zkr_queue_t *queue, const char *data, int buffer_len); - -/** - * \brief returns the head of a zookeeper queue - * - * this method returns the head of a zookeeper queue without removing it. - * \param queue the zookeeper queue to add the element to - * \param buffer a pointer to a data buffer - * \param buffer_len a pointer to the length of the buffer - * \return returns 0 (ZOK) and sets *buffer_len to the length of data written if successful (-1 if the queue is empty). Otherwise it will set *buffer_len to -1 and return a zookeeper error code. - */ -ZOOAPI int zkr_queue_element(zkr_queue_t *queue, char *buffer, int *buffer_len); - -/** - * \brief returns the head of a zookeeper queue - * - * this method returns the head of a zookeeper queue without removing it. - * \param queue the zookeeper queue to get the head of - * \param buffer a pointer to a data buffer - * \param buffer_len a pointer to the length of the buffer - * \return returns 0 (ZOK) and sets *buffer_len to the length of data written if successful (-1 if the queue is empty). Otherwise it will set *buffer_len to -1 and return a zookeeper error code. - */ -ZOOAPI int zkr_queue_remove(zkr_queue_t *queue, char *buffer, int *buffer_len); - -/** - * \brief removes and returns the head of a zookeeper queue, blocks if necessary - * - * this method returns the head of a zookeeper queue without removing it. - * \param queue the zookeeper queue to remove and return the head of - * \param buffer a pointer to a data buffer - * \param buffer_len a pointer to the length of the buffer - * \return returns 0 (ZOK) and sets *buffer_len to the length of data written if successful. Otherwise it will set *buffer_len to -1 and return a zookeeper error code. - */ -ZOOAPI int zkr_queue_take(zhandle_t *zh, zkr_queue_t *queue, char *buffer, int *buffer_len); - -/** - * \brief destroys a zookeeper queue structure - * - * this destroys a zookeeper queue structure, this is only a local operation and will not affect - * the state of the queue on the zookeeper server. - * \param queue the zookeeper queue to destroy - */ -void zkr_queue_destroy(zkr_queue_t *queue); - - -#ifdef __cplusplus -} -#endif -#endif //ZOOKEEPER_QUEUE_H_
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/c/src/zoo_queue.c ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/c/src/zoo_queue.c b/src/recipes/queue/src/c/src/zoo_queue.c deleted file mode 100644 index d7cc570..0000000 --- a/src/recipes/queue/src/c/src/zoo_queue.c +++ /dev/null @@ -1,442 +0,0 @@ -/** - * 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 - * - * 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. - */ - -#ifdef DLL_EXPORT -#define USE_STATIC_LIB -#endif - -#if defined(__CYGWIN__) -#define USE_IPV6 -#endif - -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <zookeeper_log.h> -#include <time.h> -#include <sys/time.h> -#include <sys/socket.h> -#include <limits.h> -#include <zoo_queue.h> -#include <stdbool.h> -#ifdef HAVE_SYS_UTSNAME_H -#include <sys/utsname.h> -#endif - -#ifdef HAVE_GETPWUID_R -#include <pwd.h> -#endif - -#define IF_DEBUG(x) if (logLevel==ZOO_LOG_LEVEL_DEBUG) {x;} - - -static void free_String_vector(struct String_vector *v) { - if (v->data) { - int32_t i; - for (i=0; i<v->count; i++) { - free(v->data[i]); - } - free(v->data); - v->data = 0; - } -} - - -static int vstrcmp(const void* str1, const void* str2) { - const char **a = (const char**)str1; - const char **b = (const char**) str2; - return strcmp(*a, *b); -} - -static void sort_children(struct String_vector *vector) { - qsort( vector->data, vector->count, sizeof(char*), &vstrcmp); -} - - -static void concat_path_nodename_n(char *buffer, int len, const char *path, const char *node_name){ - snprintf(buffer, len, "%s/%s", path, node_name); -} - -static char *concat_path_nodename(const char *path, const char *node_name){ - int node_path_length = strlen(path) + 1+ strlen(node_name) +1; - char *node_path = (char *) malloc(node_path_length * sizeof(char)); - concat_path_nodename_n(node_path, node_path_length, path, node_name); - return node_path; -} - - -static void zkr_queue_cache_create_path(zkr_queue_t *queue){ - if(queue->cached_create_path != NULL){ - free(queue->cached_create_path); - } - queue->cached_create_path = concat_path_nodename(queue->path, queue->node_name); -} - -ZOOAPI int zkr_queue_init(zkr_queue_t *queue, zhandle_t* zh, char* path, struct ACL_vector *acl){ - queue->zh = zh; - queue->path = path; - queue->node_name = "qn-"; - queue->node_name_length = strlen(queue->node_name); - queue->cached_create_path = NULL; - queue->acl = acl; - pthread_mutex_init(&(queue->pmutex), NULL); - zkr_queue_cache_create_path(queue); - return 0; -} - -static ZOOAPI int create_queue_root(zkr_queue_t *queue){ - return zoo_create(queue->zh, queue->path, NULL, 0, queue->acl, 0, NULL, 0 ); -} - -static int valid_child_name(zkr_queue_t *queue, const char *child_name){ - return strncmp(queue->node_name, child_name, queue->node_name_length); -} - -ZOOAPI int zkr_queue_offer(zkr_queue_t *queue, const char *data, int buffer_len){ - for(;;){ - int rc = zoo_create(queue->zh, queue->cached_create_path, data, buffer_len, queue->acl, ZOO_SEQUENCE, NULL, 0 ); - switch(rc){ - int create_root_rc; - case ZNONODE: - create_root_rc = create_queue_root(queue); - switch(create_root_rc){ - case ZNODEEXISTS: - case ZOK: - break; - default: - return create_root_rc; - } - break; - default: - return rc; - } - } -} - - -ZOOAPI int zkr_queue_element(zkr_queue_t *queue, char *buffer, int *buffer_len){ - int path_length = strlen(queue->path); - for(;;){ - struct String_vector stvector; - struct String_vector *vector = &stvector; - /*Get sorted children*/ - int get_children_rc = zoo_get_children(queue->zh, queue->path, 0, vector); - switch(get_children_rc){ - case ZOK: - break; - case ZNONODE: - *buffer_len = -1; - return ZOK; - default: - return get_children_rc; - } - if(stvector.count == 0){ - *buffer_len = -1; - return ZOK; - } - - sort_children(vector); - /*try all*/ - int i; - for(i=0; i < stvector.count; i++){ - char *child_name = stvector.data[i]; - int child_path_length = path_length + 1 + strlen(child_name) +1; - char child_path[child_path_length]; - concat_path_nodename_n(child_path, child_path_length, queue->path, child_name); - int get_rc = zoo_get(queue->zh, child_path, 0, buffer, buffer_len, NULL); - switch(get_rc){ - case ZOK: - free_String_vector(vector); - return ZOK; - case ZNONODE: - break; - default: - free_String_vector(vector); - return get_rc; - } - } - - free_String_vector(vector); - } -} - -ZOOAPI int zkr_queue_remove(zkr_queue_t *queue, char *buffer, int *buffer_len){ - int path_length = strlen(queue->path); - for(;;){ - struct String_vector stvector; - struct String_vector *vector = &stvector; - /*Get sorted children*/ - int get_children_rc = zoo_get_children(queue->zh, queue->path, 0, &stvector); - switch(get_children_rc){ - case ZOK: - break; - case ZNONODE: - *buffer_len = -1; - return ZOK; - - default: - *buffer_len = -1; - return get_children_rc; - } - if(stvector.count == 0){ - *buffer_len = -1; - return ZOK; - } - - sort_children(vector); - /*try all*/ - int i; - for( i=0; i < stvector.count; i++){ - char *child_name = stvector.data[i]; - int child_path_length = path_length + 1 + strlen(child_name) +1; - char child_path[child_path_length]; - concat_path_nodename_n(child_path, child_path_length, queue->path, child_name); - int get_rc = zoo_get(queue->zh, child_path, 0, buffer, buffer_len, NULL); - switch(get_rc){ - int delete_rc; - case ZOK: - delete_rc = zoo_delete(queue->zh, child_path, -1); - switch(delete_rc){ - case ZOK: - free_String_vector(vector); - return delete_rc; - case ZNONODE: - break; - default: - free_String_vector(vector); - *buffer_len = -1; - return delete_rc; - } - break; - case ZNONODE: - break; - default: - free_String_vector(vector); - *buffer_len = -1; - return get_rc; - } - } - free_String_vector(vector); - } -} - -/** - * The take_latch structure roughly emulates a Java CountdownLatch with 1 as the initial value. - * It is meant to be used by a setter thread and a waiter thread. - * - * This latch is specialized to be used with the queue, all latches created for the same queue structure will use the same mutex. - * - * The setter thread at some point will call take_latch_setter_trigger_latch() on the thread. - * - * The waiter thread creates the latch and at some point either calls take_latch_waiter_await()s or take_latch_waiter_mark_unneeded()s it. - * The await function will return after the setter thread has triggered the latch. - * The mark unneeded function will return immediately and avoid some unneeded initialization. - * - * Whichever thread is last to call their required function disposes of the latch. - * - * The latch may disposed if no threads will call the waiting, marking, or triggering functions using take_latch_destroy_syncrhonized(). - */ - -struct take_latch { - enum take_state {take_init, take_waiting, take_triggered, take_not_needed} state; - pthread_cond_t latch_condition; - zkr_queue_t *queue; -}; - - -typedef struct take_latch take_latch_t; - - -static void take_latch_init( take_latch_t *latch, zkr_queue_t *queue){ - pthread_mutex_t *mutex = &(queue->pmutex); - pthread_mutex_lock(mutex); - latch->state = take_init; - latch->queue = queue; - pthread_mutex_unlock(mutex); -} - -static take_latch_t *create_take_latch(zkr_queue_t *queue){ - take_latch_t *new_take_latch = (take_latch_t *) malloc(sizeof(take_latch_t)); - take_latch_init(new_take_latch, queue); - return new_take_latch; -} - - -//Only call this when you own the mutex -static void take_latch_destroy_unsafe(take_latch_t *latch){ - if(latch->state == take_waiting){ - pthread_cond_destroy(&(latch->latch_condition)); - } - free(latch); -} - -static void take_latch_destroy_synchronized(take_latch_t *latch){ - pthread_mutex_t *mutex = &(latch->queue->pmutex); - pthread_mutex_lock(mutex); - take_latch_destroy_unsafe(latch); - pthread_mutex_unlock(mutex); -} - -static void take_latch_setter_trigger_latch(zhandle_t *zh, take_latch_t *latch){ - pthread_mutex_t *mutex = &(latch->queue->pmutex); - pthread_mutex_lock(mutex); - switch(latch->state){ - case take_init: - latch->state = take_triggered; - break; - case take_not_needed: - take_latch_destroy_unsafe(latch); - break; - case take_triggered: - LOG_DEBUG(LOGCALLBACK(zh), ("Error! Latch was triggered twice.")); - break; - case take_waiting: - pthread_cond_signal(&(latch->latch_condition)); - break; - } - pthread_mutex_unlock(mutex); -} - -static void take_latch_waiter_await(zhandle_t *zh, take_latch_t *latch){ - pthread_mutex_t *mutex = &(latch->queue->pmutex); - pthread_mutex_lock(mutex); - switch(latch->state){ - case take_init: - pthread_cond_init(&(latch->latch_condition),NULL); - latch->state = take_waiting; - pthread_cond_wait(&(latch->latch_condition),mutex); - take_latch_destroy_unsafe(latch); - break; - case take_waiting: - LOG_DEBUG(LOGCALLBACK(zh), ("Error! Called await twice.")); - break; - case take_not_needed: - LOG_DEBUG(LOGCALLBACK(zh), ("Error! Waiting after marking not needed.")); - break; - case take_triggered: - take_latch_destroy_unsafe(latch); - break; - } - pthread_mutex_unlock(mutex); -} - -static void take_latch_waiter_mark_unneeded(zhandle_t *zh, take_latch_t *latch){ - pthread_mutex_t *mutex = &(latch->queue->pmutex); - pthread_mutex_lock(mutex); - switch(latch->state){ - case take_init: - latch->state = take_not_needed; - break; - case take_waiting: - LOG_DEBUG(LOGCALLBACK(zh), ("Error! Can't mark unneeded after waiting.")); - break; - case take_not_needed: - LOG_DEBUG(LOGCALLBACK(zh), ("Marked unneeded twice.")); - break; - case take_triggered: - take_latch_destroy_unsafe(latch); - break; - } - pthread_mutex_unlock(mutex); -} - -static void take_watcher(zhandle_t *zh, int type, int state, const char *path, void *watcherCtx){ - take_latch_t *latch = (take_latch_t *) watcherCtx; - take_latch_setter_trigger_latch(zh, latch); -} - - - -ZOOAPI int zkr_queue_take(zhandle_t *zh, zkr_queue_t *queue, char *buffer, int *buffer_len){ - int path_length = strlen(queue->path); -take_attempt: - for(;;){ - struct String_vector stvector; - struct String_vector *vector = &stvector; - /*Get sorted children*/ - take_latch_t *take_latch = create_take_latch(queue); - int get_children_rc = zoo_wget_children(queue->zh, queue->path, take_watcher, take_latch, &stvector); - switch(get_children_rc){ - case ZOK: - break; - int create_queue_rc; - case ZNONODE: - take_latch_destroy_synchronized(take_latch); - create_queue_rc = create_queue_root(queue); - switch(create_queue_rc){ - case ZNODEEXISTS: - case ZOK: - goto take_attempt; - default: - *buffer_len = -1; - return create_queue_rc; - } - default: - take_latch_destroy_synchronized(take_latch); - *buffer_len = -1; - return get_children_rc; - } - if(stvector.count == 0){ - take_latch_waiter_await(zh, take_latch); - }else{ - take_latch_waiter_mark_unneeded(zh, take_latch); - } - - sort_children(vector); - /*try all*/ - int i; - for( i=0; i < stvector.count; i++){ - char *child_name = stvector.data[i]; - int child_path_length = path_length + 1 + strlen(child_name) +1; - char child_path[child_path_length]; - concat_path_nodename_n(child_path, child_path_length, queue->path, child_name); - int get_rc = zoo_get(queue->zh, child_path, 0, buffer, buffer_len, NULL); - switch(get_rc){ - int delete_rc; - case ZOK: - delete_rc = zoo_delete(queue->zh, child_path, -1); - switch(delete_rc){ - case ZOK: - free_String_vector(vector); - return delete_rc; - case ZNONODE: - break; - default: - free_String_vector(vector); - *buffer_len = -1; - return delete_rc; - } - break; - case ZNONODE: - break; - default: - free_String_vector(vector); - *buffer_len = -1; - return get_rc; - } - } - free_String_vector(vector); - } -} - -ZOOAPI void zkr_queue_destroy(zkr_queue_t *queue){ - pthread_mutex_destroy(&(queue->pmutex)); - if(queue->cached_create_path != NULL){ - free(queue->cached_create_path); - } -} http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/c/tests/TestClient.cc ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/c/tests/TestClient.cc b/src/recipes/queue/src/c/tests/TestClient.cc deleted file mode 100644 index 5446d9b..0000000 --- a/src/recipes/queue/src/c/tests/TestClient.cc +++ /dev/null @@ -1,452 +0,0 @@ -/** - * 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 - * - * 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. - */ - -#include <cppunit/extensions/HelperMacros.h> - -#include <pthread.h> -#include <unistd.h> -#include <stdlib.h> -#include <sys/select.h> -#include <cppunit/TestAssert.h> - - -using namespace std; - -#include <cstring> -#include <list> - -#include <zookeeper.h> -#include <zoo_queue.h> - -static void yield(zhandle_t *zh, int i) -{ - sleep(i); -} - -typedef struct evt { - string path; - int type; -} evt_t; - -typedef struct watchCtx { -private: - list<evt_t> events; -public: - bool connected; - zhandle_t *zh; - - watchCtx() { - connected = false; - zh = 0; - } - ~watchCtx() { - if (zh) { - zookeeper_close(zh); - zh = 0; - } - } - - evt_t getEvent() { - evt_t evt; - evt = events.front(); - events.pop_front(); - return evt; - } - - int countEvents() { - int count; - count = events.size(); - return count; - } - - void putEvent(evt_t evt) { - events.push_back(evt); - } - - bool waitForConnected(zhandle_t *zh) { - time_t expires = time(0) + 10; - while(!connected && time(0) < expires) { - yield(zh, 1); - } - return connected; - } - bool waitForDisconnected(zhandle_t *zh) { - time_t expires = time(0) + 15; - while(connected && time(0) < expires) { - yield(zh, 1); - } - return !connected; - } -} watchctx_t; - -extern "C" { - - const char *thread_test_string="Hello World!"; - - void *offer_thread_shared_queue(void *queue_handle){ - zkr_queue_t *queue = (zkr_queue_t *) queue_handle; - - int test_string_buffer_length = strlen(thread_test_string) + 1; - int offer_rc = zkr_queue_offer(queue, thread_test_string, test_string_buffer_length); - pthread_exit(NULL); - } - - void *take_thread_shared_queue(void *queue_handle){ - zkr_queue_t *queue = (zkr_queue_t *) queue_handle; - - int test_string_buffer_length = strlen(thread_test_string) + 1; - int receive_buffer_capacity = test_string_buffer_length; - int receive_buffer_length = receive_buffer_capacity; - char *receive_buffer = (char *) malloc(sizeof(char) * receive_buffer_capacity); - - int remove_rc = zkr_queue_take(queue, receive_buffer, &receive_buffer_length); - switch(remove_rc){ - case ZOK: - pthread_exit(receive_buffer); - default: - free(receive_buffer); - pthread_exit(NULL); - } - } - - int valid_test_string(void *result){ - char *result_string = (char *) result; - return !strncmp(result_string, thread_test_string, strlen(thread_test_string)); - } -} - -class Zookeeper_queuetest : public CPPUNIT_NS::TestFixture -{ - CPPUNIT_TEST_SUITE(Zookeeper_queuetest); - CPPUNIT_TEST(testInitDestroy); - CPPUNIT_TEST(testOffer1); - CPPUNIT_TEST(testOfferRemove1); - CPPUNIT_TEST(testOfferRemove2); - CPPUNIT_TEST(testOfferRemove3); - CPPUNIT_TEST(testOfferRemove4); - CPPUNIT_TEST(testOfferRemove5); - CPPUNIT_TEST(testOfferRemove6); - CPPUNIT_TEST(testOfferTake1); - CPPUNIT_TEST(testOfferTake2); - CPPUNIT_TEST(testOfferTake3); - CPPUNIT_TEST(testOfferTake4); - CPPUNIT_TEST(testOfferTake5); - CPPUNIT_TEST(testOfferTake6); - CPPUNIT_TEST_SUITE_END(); - - static void watcher(zhandle_t *, int type, int state, const char *path,void*v){ - watchctx_t *ctx = (watchctx_t*)v; - - if (state == ZOO_CONNECTED_STATE) { - ctx->connected = true; - } else { - ctx->connected = false; - } - if (type != ZOO_SESSION_EVENT) { - evt_t evt; - evt.path = path; - evt.type = type; - ctx->putEvent(evt); - } - } - - static const char hostPorts[]; - - const char *getHostPorts() { - return hostPorts; - } - - zhandle_t *createClient(watchctx_t *ctx) { - zhandle_t *zk = zookeeper_init(hostPorts, watcher, 10000, 0, - ctx, 0); - ctx->zh = zk; - sleep(1); - return zk; - } - -public: - -#define ZKSERVER_CMD "./tests/zkServer.sh" - - void setUp() - { - char cmd[1024]; - sprintf(cmd, "%s startClean %s", ZKSERVER_CMD, getHostPorts()); - CPPUNIT_ASSERT(system(cmd) == 0); - } - - - void startServer() { - char cmd[1024]; - sprintf(cmd, "%s start %s", ZKSERVER_CMD, getHostPorts()); - CPPUNIT_ASSERT(system(cmd) == 0); - } - - void stopServer() { - tearDown(); - } - - void tearDown() - { - char cmd[1024]; - sprintf(cmd, "%s stop %s", ZKSERVER_CMD, getHostPorts()); - CPPUNIT_ASSERT(system(cmd) == 0); - } - - void initializeQueuesAndHandles(int num_clients, zhandle_t *zoohandles[], - watchctx_t ctxs[], zkr_queue_t queues[], char *path){ - int i; - for(i=0; i< num_clients; i++){ - zoohandles[i] = createClient(&ctxs[i]); - zkr_queue_init(&queues[i], zoohandles[i], path, &ZOO_OPEN_ACL_UNSAFE); - } - } - - void cleanUpQueues(int num_clients, zkr_queue_t queues[]){ - int i; - for(i=0; i < num_clients; i++){ - zkr_queue_destroy(&queues[i]); - } - } - - void testInitDestroy(){ - int num_clients = 1; - watchctx_t ctxs[num_clients]; - zhandle_t *zoohandles[num_clients]; - zkr_queue_t queues[num_clients]; - char *path= (char *)"/testInitDestroy"; - - int i; - for(i=0; i< num_clients; i++){ - zoohandles[i] = createClient(&ctxs[i]); - zkr_queue_init(&queues[i], zoohandles[i], path, &ZOO_OPEN_ACL_UNSAFE); - } - - for(i=0; i< num_clients; i++){ - zkr_queue_destroy(&queues[i]); - } - - } - - void testOffer1(){ - int num_clients = 1; - watchctx_t ctxs[num_clients]; - zhandle_t *zoohandles[num_clients]; - zkr_queue_t queues[num_clients]; - char *path= (char *)"/testOffer1"; - - initializeQueuesAndHandles(num_clients, zoohandles, ctxs, queues, path); - - const char *test_string="Hello World!"; - int test_string_length = strlen(test_string); - int test_string_buffer_length = test_string_length + 1; - char buffer[test_string_buffer_length]; - - int offer_rc = zkr_queue_offer(&queues[0], test_string, test_string_buffer_length); - CPPUNIT_ASSERT(offer_rc == ZOK); - - int removed_element_buffer_length = test_string_buffer_length; - int remove_rc = zkr_queue_remove(&queues[0], buffer, &removed_element_buffer_length); - CPPUNIT_ASSERT(remove_rc == ZOK); - CPPUNIT_ASSERT(removed_element_buffer_length == test_string_buffer_length); - CPPUNIT_ASSERT(strncmp(test_string,buffer,test_string_length)==0); - - cleanUpQueues(num_clients,queues); - } - - void create_n_remove_m(char *path, int n, int m){ - int num_clients = 2; - watchctx_t ctxs[num_clients]; - zhandle_t *zoohandles[num_clients]; - zkr_queue_t queues[num_clients]; - - initializeQueuesAndHandles(num_clients, zoohandles, ctxs, queues, path); - - int i; - int max_digits = sizeof(int)*3; - const char *test_string = "Hello World!"; - int buffer_length = strlen(test_string) + max_digits + 1; - char correct_buffer[buffer_length]; - char receive_buffer[buffer_length]; - - for(i = 0; i < n; i++){ - snprintf(correct_buffer, buffer_length, "%s%d", test_string,i); - int offer_rc = zkr_queue_offer(&queues[0], correct_buffer, buffer_length); - CPPUNIT_ASSERT(offer_rc == ZOK); - } - printf("Offers\n"); - for(i=0; i<m ;i++){ - snprintf(correct_buffer, buffer_length, "%s%d", test_string,i); - int receive_buffer_length=buffer_length; - int remove_rc = zkr_queue_remove(&queues[1], receive_buffer, &receive_buffer_length); - CPPUNIT_ASSERT(remove_rc == ZOK); - if(i >=n){ - CPPUNIT_ASSERT(receive_buffer_length == -1); - }else{ - CPPUNIT_ASSERT(strncmp(correct_buffer,receive_buffer, buffer_length)==0); - } - } - - cleanUpQueues(num_clients,queues); - } - - void testOfferRemove1(){ - create_n_remove_m((char *)"/testOfferRemove1", 0,1); - } - - void testOfferRemove2(){ - create_n_remove_m((char *)"/testOfferRemove2", 1,1); - } - - void testOfferRemove3(){ - create_n_remove_m((char *)"/testOfferRemove3", 10,1); - } - - void testOfferRemove4(){ - create_n_remove_m((char *)"/testOfferRemove4", 10,10); - } - - void testOfferRemove5(){ - create_n_remove_m((char *)"/testOfferRemove5", 10,5); - } - - void testOfferRemove6(){ - create_n_remove_m((char *)"/testOfferRemove6", 10,11); - } - - void create_n_take_m(char *path, int n, int m){ - CPPUNIT_ASSERT(m<=n); - int num_clients = 2; - watchctx_t ctxs[num_clients]; - zhandle_t *zoohandles[num_clients]; - zkr_queue_t queues[num_clients]; - - initializeQueuesAndHandles(num_clients, zoohandles, ctxs, queues, path); - - int i; - int max_digits = sizeof(int)*3; - const char *test_string = "Hello World!"; - int buffer_length = strlen(test_string) + max_digits + 1; - char correct_buffer[buffer_length]; - char receive_buffer[buffer_length]; - - for(i = 0; i < n; i++){ - snprintf(correct_buffer, buffer_length, "%s%d", test_string,i); - int offer_rc = zkr_queue_offer(&queues[0], correct_buffer, buffer_length); - CPPUNIT_ASSERT(offer_rc == ZOK); - } - printf("Offers\n"); - for(i=0; i<m ;i++){ - snprintf(correct_buffer, buffer_length, "%s%d", test_string,i); - int receive_buffer_length=buffer_length; - int remove_rc = zkr_queue_take(&queues[1], receive_buffer, &receive_buffer_length); - CPPUNIT_ASSERT(remove_rc == ZOK); - if(i >=n){ - CPPUNIT_ASSERT(receive_buffer_length == -1); - }else{ - CPPUNIT_ASSERT(strncmp(correct_buffer,receive_buffer, buffer_length)==0); - } - } - - cleanUpQueues(num_clients,queues); - } - - void testOfferTake1(){ - create_n_take_m((char *)"/testOfferTake1", 2,1); - } - - void testOfferTake2(){ - create_n_take_m((char *)"/testOfferTake2", 1,1); - } - - void testOfferTake3(){ - create_n_take_m((char *)"/testOfferTake3", 10,1); - } - - void testOfferTake4(){ - create_n_take_m((char *)"/testOfferTake4", 10,10); - } - - void testOfferTake5(){ - create_n_take_m((char *)"/testOfferTake5", 10,5); - } - - void testOfferTake6(){ - create_n_take_m((char *)"/testOfferTake6", 12,11); - } - - void testTakeThreaded(){ - int num_clients = 1; - watchctx_t ctxs[num_clients]; - zhandle_t *zoohandles[num_clients]; - zkr_queue_t queues[num_clients]; - char *path=(char *)"/testTakeThreaded"; - - initializeQueuesAndHandles(num_clients, zoohandles, ctxs, queues, path); - pthread_t take_thread; - - pthread_create(&take_thread, NULL, take_thread_shared_queue, (void *) &queues[0]); - - usleep(1000); - - pthread_t offer_thread; - pthread_create(&offer_thread, NULL, offer_thread_shared_queue, (void *) &queues[0]); - pthread_join(offer_thread, NULL); - - void *take_thread_result; - pthread_join(take_thread, &take_thread_result); - CPPUNIT_ASSERT(take_thread_result != NULL); - CPPUNIT_ASSERT(valid_test_string(take_thread_result)); - - cleanUpQueues(num_clients,queues); - } - - void testTakeThreaded2(){ - int num_clients = 1; - watchctx_t ctxs[num_clients]; - zhandle_t *zoohandles[num_clients]; - zkr_queue_t queues[num_clients]; - char *path=(char *)"/testTakeThreaded2"; - - initializeQueuesAndHandles(num_clients, zoohandles, ctxs, queues, path); - - int take_attempts; - int num_take_attempts = 2; - for(take_attempts=0; take_attempts < num_take_attempts; take_attempts++){ - pthread_t take_thread; - - pthread_create(&take_thread, NULL, take_thread_shared_queue, (void *) &queues[0]); - - usleep(1000); - - pthread_t offer_thread; - pthread_create(&offer_thread, NULL, offer_thread_shared_queue, (void *) &queues[0]); - pthread_join(offer_thread, NULL); - - void *take_thread_result; - pthread_join(take_thread, &take_thread_result); - CPPUNIT_ASSERT(take_thread_result != NULL); - CPPUNIT_ASSERT(valid_test_string(take_thread_result)); - - } - cleanUpQueues(num_clients,queues); - } -}; - -const char Zookeeper_queuetest::hostPorts[] = "127.0.0.1:22181"; -CPPUNIT_TEST_SUITE_REGISTRATION(Zookeeper_queuetest); http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/c/tests/TestDriver.cc ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/c/tests/TestDriver.cc b/src/recipes/queue/src/c/tests/TestDriver.cc deleted file mode 100644 index 2b818f4..0000000 --- a/src/recipes/queue/src/c/tests/TestDriver.cc +++ /dev/null @@ -1,114 +0,0 @@ -/** - * 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 - * - * 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. - */ - -#include <string> -#include <cppunit/TestRunner.h> -#include <cppunit/CompilerOutputter.h> -#include <cppunit/TestResult.h> -#include <cppunit/TestResultCollector.h> -#include <cppunit/TextTestProgressListener.h> -#include <cppunit/BriefTestProgressListener.h> -#include <cppunit/extensions/TestFactoryRegistry.h> -#include <stdexcept> -#include <cppunit/Exception.h> -#include <cppunit/TestFailure.h> -#include <cppunit/XmlOutputter.h> -#include <fstream> - -#include "Util.h" - -using namespace std; - -CPPUNIT_NS_BEGIN - -class EclipseOutputter: public CompilerOutputter -{ -public: - EclipseOutputter(TestResultCollector *result,ostream &stream): - CompilerOutputter(result,stream,"%p:%l: "),stream_(stream) - { - } - virtual void printFailedTestName( TestFailure *failure ){} - virtual void printFailureMessage( TestFailure *failure ) - { - stream_<<": "; - Message msg = failure->thrownException()->message(); - stream_<< msg.shortDescription(); - - string text; - for(int i=0; i<msg.detailCount();i++){ - text+=msg.detailAt(i); - if(i+1!=msg.detailCount()) - text+=", "; - } - if(text.length()!=0) - stream_ <<" ["<<text<<"]"; - stream_<<"\n"; - } - ostream& stream_; -}; - -CPPUNIT_NS_END - -int main( int argc, char* argv[] ) { - // if command line contains "-ide" then this is the post build check - // => the output must be in the compiler error format. - //bool selfTest = (argc > 1) && (std::string("-ide") == argv[1]); - globalTestConfig.addConfigFromCmdLine(argc,argv); - - // Create the event manager and test controller - CPPUNIT_NS::TestResult controller; - // Add a listener that colllects test result - CPPUNIT_NS::TestResultCollector result; - controller.addListener( &result ); - - // Add a listener that print dots as tests run. - // CPPUNIT_NS::TextTestProgressListener progress; - CPPUNIT_NS::BriefTestProgressListener progress; - controller.addListener( &progress ); - - CPPUNIT_NS::TestRunner runner; - runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() ); - - try - { - cout << "Running " << globalTestConfig.getTestName(); - runner.run( controller, globalTestConfig.getTestName()); - cout<<endl; - - // Print test in a compiler compatible format. - CPPUNIT_NS::EclipseOutputter outputter( &result,cout); - outputter.write(); - - // Uncomment this for XML output -#ifdef ENABLE_XML_OUTPUT - std::ofstream file( "tests.xml" ); - CPPUNIT_NS::XmlOutputter xml( &result, file ); - xml.setStyleSheet( "report.xsl" ); - xml.write(); - file.close(); -#endif - } - catch ( std::invalid_argument &e ) // Test path not resolved - { - cout<<"\nERROR: "<<e.what()<<endl; - return 0; - } - - return result.wasSuccessful() ? 0 : 1; - } http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/c/tests/Util.cc ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/c/tests/Util.cc b/src/recipes/queue/src/c/tests/Util.cc deleted file mode 100644 index 26a9a09..0000000 --- a/src/recipes/queue/src/c/tests/Util.cc +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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 - * - * 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. - */ - -#include "Util.h" - -const std::string EMPTY_STRING; - -TestConfig globalTestConfig; - -void millisleep(int ms){ - timespec ts; - ts.tv_sec=ms/1000; - ts.tv_nsec=(ms%1000)*1000000; // to nanoseconds - nanosleep(&ts,0); -} http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/c/tests/Util.h ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/c/tests/Util.h b/src/recipes/queue/src/c/tests/Util.h deleted file mode 100644 index 95f5420..0000000 --- a/src/recipes/queue/src/c/tests/Util.h +++ /dev/null @@ -1,134 +0,0 @@ -/** - * 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 - * - * 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. - */ - -#ifndef UTIL_H_ -#define UTIL_H_ - -#include <map> -#include <vector> -#include <string> - -// number of elements in array -#define COUNTOF(array) sizeof(array)/sizeof(array[0]) - -#define DECLARE_WRAPPER(ret,sym,sig) \ - extern "C" ret __real_##sym sig; \ - extern "C" ret __wrap_##sym sig - -#define CALL_REAL(sym,params) \ - __real_##sym params - -// must include "src/zookeeper_log.h" to be able to use this macro -#define TEST_TRACE(x) \ - log_message(3,__LINE__,__func__,format_log_message x) - -extern const std::string EMPTY_STRING; - -// ***************************************************************************** -// A bit of wizardry to get to the bare type from a reference or a pointer -// to the type -template <class T> -struct TypeOp { - typedef T BareT; - typedef T ArgT; -}; - -// partial specialization for reference types -template <class T> -struct TypeOp<T&>{ - typedef T& ArgT; - typedef typename TypeOp<T>::BareT BareT; -}; - -// partial specialization for pointers -template <class T> -struct TypeOp<T*>{ - typedef T* ArgT; - typedef typename TypeOp<T>::BareT BareT; -}; - -// ***************************************************************************** -// Container utilities - -template <class K, class V> -void putValue(std::map<K,V>& map,const K& k, const V& v){ - typedef std::map<K,V> Map; - typename Map::const_iterator it=map.find(k); - if(it==map.end()) - map.insert(typename Map::value_type(k,v)); - else - map[k]=v; -} - -template <class K, class V> -bool getValue(const std::map<K,V>& map,const K& k,V& v){ - typedef std::map<K,V> Map; - typename Map::const_iterator it=map.find(k); - if(it==map.end()) - return false; - v=it->second; - return true; -} - -// ***************************************************************************** -// misc utils - -// millisecond sleep -void millisleep(int ms); -// evaluate given predicate until it returns true or the timeout -// (in millis) has expired -template<class Predicate> -int ensureCondition(const Predicate& p,int timeout){ - int elapsed=0; - while(!p() && elapsed<timeout){ - millisleep(2); - elapsed+=2; - } - return elapsed; -}; - -// ***************************************************************************** -// test global configuration data -class TestConfig{ - typedef std::vector<std::string> CmdLineOptList; -public: - typedef CmdLineOptList::const_iterator const_iterator; - TestConfig(){} - ~TestConfig(){} - void addConfigFromCmdLine(int argc, char* argv[]){ - if(argc>=2) - testName_=argv[1]; - for(int i=2; i<argc;++i) - cmdOpts_.push_back(argv[i]); - } - const_iterator getExtraOptBegin() const {return cmdOpts_.begin();} - const_iterator getExtraOptEnd() const {return cmdOpts_.end();} - size_t getExtraOptCount() const { - return cmdOpts_.size(); - } - const std::string& getTestName() const { - return testName_=="all"?EMPTY_STRING:testName_; - } -private: - CmdLineOptList cmdOpts_; - std::string testName_; -}; - -extern TestConfig globalTestConfig; - -#endif /*UTIL_H_*/ http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/c/tests/zkServer.sh ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/c/tests/zkServer.sh b/src/recipes/queue/src/c/tests/zkServer.sh deleted file mode 100755 index a22fd30..0000000 --- a/src/recipes/queue/src/c/tests/zkServer.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -# -# 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 -# -# 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. - - -if [ "x$1" == "x" ] -then - echo "USAGE: $0 startClean|start|stop hostPorts" - exit 2 -fi - -if [ "x$1" == "xstartClean" ] -then - rm -rf /tmp/zkdata -fi - -# Make sure nothing is left over from before -if [ -r "/tmp/zk.pid" ] -then -pid=`cat /tmp/zk.pid` -kill -9 $pid -rm -f /tmp/zk.pid -fi - -base_dir="../../../../.." - -CLASSPATH="$CLASSPATH:${base_dir}/build/classes" -CLASSPATH="$CLASSPATH:${base_dir}/conf" - -for f in "${base_dir}"/zookeeper-*.jar -do - CLASSPATH="$CLASSPATH:$f" -done - -for i in "${base_dir}"/build/lib/*.jar -do - CLASSPATH="$CLASSPATH:$i" -done - -for i in "${base_dir}"/src/java/lib/*.jar -do - CLASSPATH="$CLASSPATH:$i" -done - -CLASSPATH="$CLASSPATH:${CLOVER_HOME}/lib/clover.jar" - -case $1 in -start|startClean) - mkdir -p /tmp/zkdata - java -cp $CLASSPATH org.apache.zookeeper.server.ZooKeeperServerMain 22181 /tmp/zkdata &> /tmp/zk.log & - echo $! > /tmp/zk.pid - sleep 5 - ;; -stop) - # Already killed above - ;; -*) - echo "Unknown command " + $1 - exit 2 -esac - http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/src/java/org/apache/zookeeper/recipes/queue/DistributedQueue.java ---------------------------------------------------------------------- diff --git a/src/recipes/queue/src/java/org/apache/zookeeper/recipes/queue/DistributedQueue.java b/src/recipes/queue/src/java/org/apache/zookeeper/recipes/queue/DistributedQueue.java deleted file mode 100644 index c35c332..0000000 --- a/src/recipes/queue/src/java/org/apache/zookeeper/recipes/queue/DistributedQueue.java +++ /dev/null @@ -1,314 +0,0 @@ -/** - * - * 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 - * - * 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. - */ - -package org.apache.zookeeper.recipes.queue; - -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.TreeMap; -import java.util.concurrent.CountDownLatch; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.ZooDefs; -import org.apache.zookeeper.ZooKeeper; -import org.apache.zookeeper.data.ACL; -import org.apache.zookeeper.data.Stat; - -/** - * - * A <a href="package.html">protocol to implement a distributed queue</a>. - * - */ - -public class DistributedQueue { - private static final Logger LOG = LoggerFactory.getLogger(DistributedQueue.class); - - private final String dir; - - private ZooKeeper zookeeper; - private List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE; - - private final String prefix = "qn-"; - - - public DistributedQueue(ZooKeeper zookeeper, String dir, List<ACL> acl){ - this.dir = dir; - - if(acl != null){ - this.acl = acl; - } - this.zookeeper = zookeeper; - - } - - - - /** - * Returns a Map of the children, ordered by id. - * @param watcher optional watcher on getChildren() operation. - * @return map from id to child name for all children - */ - private Map<Long,String> orderedChildren(Watcher watcher) throws KeeperException, InterruptedException { - Map<Long,String> orderedChildren = new TreeMap<Long,String>(); - - List<String> childNames = null; - try{ - childNames = zookeeper.getChildren(dir, watcher); - }catch (KeeperException.NoNodeException e){ - throw e; - } - - for(String childName : childNames){ - try{ - //Check format - if(!childName.regionMatches(0, prefix, 0, prefix.length())){ - LOG.warn("Found child node with improper name: " + childName); - continue; - } - String suffix = childName.substring(prefix.length()); - Long childId = new Long(suffix); - orderedChildren.put(childId,childName); - }catch(NumberFormatException e){ - LOG.warn("Found child node with improper format : " + childName + " " + e,e); - } - } - - return orderedChildren; - } - - /** - * Find the smallest child node. - * @return The name of the smallest child node. - */ - private String smallestChildName() throws KeeperException, InterruptedException { - long minId = Long.MAX_VALUE; - String minName = ""; - - List<String> childNames = null; - - try{ - childNames = zookeeper.getChildren(dir, false); - }catch(KeeperException.NoNodeException e){ - LOG.warn("Caught: " +e,e); - return null; - } - - for(String childName : childNames){ - try{ - //Check format - if(!childName.regionMatches(0, prefix, 0, prefix.length())){ - LOG.warn("Found child node with improper name: " + childName); - continue; - } - String suffix = childName.substring(prefix.length()); - long childId = Long.parseLong(suffix); - if(childId < minId){ - minId = childId; - minName = childName; - } - }catch(NumberFormatException e){ - LOG.warn("Found child node with improper format : " + childName + " " + e,e); - } - } - - - if(minId < Long.MAX_VALUE){ - return minName; - }else{ - return null; - } - } - - /** - * Return the head of the queue without modifying the queue. - * @return the data at the head of the queue. - * @throws NoSuchElementException - * @throws KeeperException - * @throws InterruptedException - */ - public byte[] element() throws NoSuchElementException, KeeperException, InterruptedException { - Map<Long,String> orderedChildren; - - // element, take, and remove follow the same pattern. - // We want to return the child node with the smallest sequence number. - // Since other clients are remove()ing and take()ing nodes concurrently, - // the child with the smallest sequence number in orderedChildren might be gone by the time we check. - // We don't call getChildren again until we have tried the rest of the nodes in sequence order. - while(true){ - try{ - orderedChildren = orderedChildren(null); - }catch(KeeperException.NoNodeException e){ - throw new NoSuchElementException(); - } - if(orderedChildren.size() == 0 ) throw new NoSuchElementException(); - - for(String headNode : orderedChildren.values()){ - if(headNode != null){ - try{ - return zookeeper.getData(dir+"/"+headNode, false, null); - }catch(KeeperException.NoNodeException e){ - //Another client removed the node first, try next - } - } - } - - } - } - - - /** - * Attempts to remove the head of the queue and return it. - * @return The former head of the queue - * @throws NoSuchElementException - * @throws KeeperException - * @throws InterruptedException - */ - public byte[] remove() throws NoSuchElementException, KeeperException, InterruptedException { - Map<Long,String> orderedChildren; - // Same as for element. Should refactor this. - while(true){ - try{ - orderedChildren = orderedChildren(null); - }catch(KeeperException.NoNodeException e){ - throw new NoSuchElementException(); - } - if(orderedChildren.size() == 0) throw new NoSuchElementException(); - - for(String headNode : orderedChildren.values()){ - String path = dir +"/"+headNode; - try{ - byte[] data = zookeeper.getData(path, false, null); - zookeeper.delete(path, -1); - return data; - }catch(KeeperException.NoNodeException e){ - // Another client deleted the node first. - } - } - - } - } - - private class LatchChildWatcher implements Watcher { - - CountDownLatch latch; - - public LatchChildWatcher(){ - latch = new CountDownLatch(1); - } - - public void process(WatchedEvent event){ - LOG.debug("Watcher fired on path: " + event.getPath() + " state: " + - event.getState() + " type " + event.getType()); - latch.countDown(); - } - public void await() throws InterruptedException { - latch.await(); - } - } - - /** - * Removes the head of the queue and returns it, blocks until it succeeds. - * @return The former head of the queue - * @throws NoSuchElementException - * @throws KeeperException - * @throws InterruptedException - */ - public byte[] take() throws KeeperException, InterruptedException { - Map<Long,String> orderedChildren; - // Same as for element. Should refactor this. - while(true){ - LatchChildWatcher childWatcher = new LatchChildWatcher(); - try{ - orderedChildren = orderedChildren(childWatcher); - }catch(KeeperException.NoNodeException e){ - zookeeper.create(dir, new byte[0], acl, CreateMode.PERSISTENT); - continue; - } - if(orderedChildren.size() == 0){ - childWatcher.await(); - continue; - } - - for(String headNode : orderedChildren.values()){ - String path = dir +"/"+headNode; - try{ - byte[] data = zookeeper.getData(path, false, null); - zookeeper.delete(path, -1); - return data; - }catch(KeeperException.NoNodeException e){ - // Another client deleted the node first. - } - } - } - } - - /** - * Inserts data into queue. - * @param data - * @return true if data was successfully added - */ - public boolean offer(byte[] data) throws KeeperException, InterruptedException{ - for(;;){ - try{ - zookeeper.create(dir+"/"+prefix, data, acl, CreateMode.PERSISTENT_SEQUENTIAL); - return true; - }catch(KeeperException.NoNodeException e){ - zookeeper.create(dir, new byte[0], acl, CreateMode.PERSISTENT); - } - } - - } - - /** - * Returns the data at the first element of the queue, or null if the queue is empty. - * @return data at the first element of the queue, or null. - * @throws KeeperException - * @throws InterruptedException - */ - public byte[] peek() throws KeeperException, InterruptedException{ - try{ - return element(); - }catch(NoSuchElementException e){ - return null; - } - } - - - /** - * Attempts to remove the head of the queue and return it. Returns null if the queue is empty. - * @return Head of the queue or null. - * @throws KeeperException - * @throws InterruptedException - */ - public byte[] poll() throws KeeperException, InterruptedException { - try{ - return remove(); - }catch(NoSuchElementException e){ - return null; - } - } - - - -} http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/src/recipes/queue/test/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java ---------------------------------------------------------------------- diff --git a/src/recipes/queue/test/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java b/src/recipes/queue/test/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java deleted file mode 100644 index c6cfae2..0000000 --- a/src/recipes/queue/test/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java +++ /dev/null @@ -1,286 +0,0 @@ -/** - * - * 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 - * - * 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. - */ -package org.apache.zookeeper.recipes.queue; - -import java.util.NoSuchElementException; - -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.ZooKeeper; -import org.apache.zookeeper.test.ClientBase; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - - - -public class DistributedQueueTest extends ClientBase { - - @After - public void tearDown() throws Exception { - super.tearDown(); - LOG.info("FINISHED " + getTestName()); - } - - - @Test - public void testOffer1() throws Exception { - String dir = "/testOffer1"; - String testString = "Hello World"; - final int num_clients = 1; - ZooKeeper clients[] = new ZooKeeper[num_clients]; - DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - - queueHandles[0].offer(testString.getBytes()); - - byte dequeuedBytes[] = queueHandles[0].remove(); - Assert.assertEquals(new String(dequeuedBytes), testString); - } - - @Test - public void testOffer2() throws Exception { - String dir = "/testOffer2"; - String testString = "Hello World"; - final int num_clients = 2; - ZooKeeper clients[] = new ZooKeeper[num_clients]; - DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - - queueHandles[0].offer(testString.getBytes()); - - byte dequeuedBytes[] = queueHandles[1].remove(); - Assert.assertEquals(new String(dequeuedBytes), testString); - } - - @Test - public void testTake1() throws Exception { - String dir = "/testTake1"; - String testString = "Hello World"; - final int num_clients = 1; - ZooKeeper clients[] = new ZooKeeper[num_clients]; - DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - - queueHandles[0].offer(testString.getBytes()); - - byte dequeuedBytes[] = queueHandles[0].take(); - Assert.assertEquals(new String(dequeuedBytes), testString); - } - - - - @Test - public void testRemove1() throws Exception{ - String dir = "/testRemove1"; - String testString = "Hello World"; - final int num_clients = 1; - ZooKeeper clients[] = new ZooKeeper[num_clients]; - DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - - try{ - queueHandles[0].remove(); - }catch(NoSuchElementException e){ - return; - } - Assert.assertTrue(false); - } - - public void createNremoveMtest(String dir,int n,int m) throws Exception{ - String testString = "Hello World"; - final int num_clients = 2; - ZooKeeper clients[] = new ZooKeeper[num_clients]; - DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - - for(int i=0; i< n; i++){ - String offerString = testString + i; - queueHandles[0].offer(offerString.getBytes()); - } - - byte data[] = null; - for(int i=0; i<m; i++){ - data=queueHandles[1].remove(); - } - Assert.assertEquals(new String(data), testString+(m-1)); - } - - @Test - public void testRemove2() throws Exception{ - createNremoveMtest("/testRemove2",10,2); - } - @Test - public void testRemove3() throws Exception{ - createNremoveMtest("/testRemove3",1000,1000); - } - - public void createNremoveMelementTest(String dir,int n,int m) throws Exception{ - String testString = "Hello World"; - final int num_clients = 2; - ZooKeeper clients[] = new ZooKeeper[num_clients]; - DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - - for(int i=0; i< n; i++){ - String offerString = testString + i; - queueHandles[0].offer(offerString.getBytes()); - } - - byte data[] = null; - for(int i=0; i<m; i++){ - data=queueHandles[1].remove(); - } - Assert.assertEquals(new String(queueHandles[1].element()), testString+m); - } - - @Test - public void testElement1() throws Exception { - createNremoveMelementTest("/testElement1",1,0); - } - - @Test - public void testElement2() throws Exception { - createNremoveMelementTest("/testElement2",10,2); - } - - @Test - public void testElement3() throws Exception { - createNremoveMelementTest("/testElement3",1000,500); - } - - @Test - public void testElement4() throws Exception { - createNremoveMelementTest("/testElement4",1000,1000-1); - } - - @Test - public void testTakeWait1() throws Exception{ - String dir = "/testTakeWait1"; - final String testString = "Hello World"; - final int num_clients = 1; - final ZooKeeper clients[] = new ZooKeeper[num_clients]; - final DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - - final byte[] takeResult[] = new byte[1][]; - Thread takeThread = new Thread(){ - public void run(){ - try{ - takeResult[0] = queueHandles[0].take(); - }catch(KeeperException e){ - - }catch(InterruptedException e){ - - } - } - }; - takeThread.start(); - - Thread.sleep(1000); - Thread offerThread= new Thread() { - public void run(){ - try { - queueHandles[0].offer(testString.getBytes()); - } catch (KeeperException e) { - - } catch (InterruptedException e) { - - } - } - }; - offerThread.start(); - offerThread.join(); - - takeThread.join(); - - Assert.assertTrue(takeResult[0] != null); - Assert.assertEquals(new String(takeResult[0]), testString); - } - - @Test - public void testTakeWait2() throws Exception{ - String dir = "/testTakeWait2"; - final String testString = "Hello World"; - final int num_clients = 1; - final ZooKeeper clients[] = new ZooKeeper[num_clients]; - final DistributedQueue queueHandles[] = new DistributedQueue[num_clients]; - for(int i=0; i < clients.length; i++){ - clients[i] = createClient(); - queueHandles[i] = new DistributedQueue(clients[i], dir, null); - } - int num_attempts =2; - for(int i=0; i< num_attempts; i++){ - final byte[] takeResult[] = new byte[1][]; - final String threadTestString = testString + i; - Thread takeThread = new Thread(){ - public void run(){ - try{ - takeResult[0] = queueHandles[0].take(); - }catch(KeeperException e){ - - }catch(InterruptedException e){ - - } - } - }; - takeThread.start(); - - Thread.sleep(1000); - Thread offerThread= new Thread() { - public void run(){ - try { - queueHandles[0].offer(threadTestString.getBytes()); - } catch (KeeperException e) { - - } catch (InterruptedException e) { - - } - } - }; - offerThread.start(); - offerThread.join(); - - takeThread.join(); - - Assert.assertTrue(takeResult[0] != null); - Assert.assertEquals(new String(takeResult[0]), threadTestString); - } - } -} - http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/zookeeper-docs/src/documentation/content/xdocs/recipes.xml ---------------------------------------------------------------------- diff --git a/zookeeper-docs/src/documentation/content/xdocs/recipes.xml b/zookeeper-docs/src/documentation/content/xdocs/recipes.xml index f53536f..40a31ad 100644 --- a/zookeeper-docs/src/documentation/content/xdocs/recipes.xml +++ b/zookeeper-docs/src/documentation/content/xdocs/recipes.xml @@ -283,7 +283,7 @@ <note> <para>There now exists a Queue implementation in ZooKeeper recipes directory. This is distributed with the release -- - src/recipes/queue directory of the release artifact. + zookeeper-recipes/zookeeper-recipes-queue directory of the release artifact. </para> </note> @@ -312,7 +312,7 @@ <note> <para>There now exists a Lock implementation in ZooKeeper recipes directory. This is distributed with the release -- - src/recipes/lock directory of the release artifact. + zookeeper-recipes/zookeeper-recipes-lock directory of the release artifact. </para> </note> http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/zookeeper-recipes/README.txt ---------------------------------------------------------------------- diff --git a/zookeeper-recipes/README.txt b/zookeeper-recipes/README.txt new file mode 100644 index 0000000..856dae0 --- /dev/null +++ b/zookeeper-recipes/README.txt @@ -0,0 +1,26 @@ +1) This source directory contains various Zookeeper recipe implementations. + +2) The recipe directory name should specify the name of the recipe you are implementing - eg. zookeeper-recipes-lock/. + +3) It would be great if you can provide both the java and c recipes for the zookeeper recipes. + C recipes go in to zookeeper-recipes/zookeeper-recipes-[recipe-name]/src/c + Java implementation goes into zookeeper-recipes/zookeeper-recipes-[recipe-name]/src/java. + +4) The recipes hold high standards like our zookeeper c/java libraries, so make sure that you include +some unit testing with both the c and java recipe code. + +5) Also, please name your c client public methods as +zkr_recipe-name_methodname +(eg. zkr_lock_lock in zookeeper-recipes-lock/src/c) + +6) The various recipes are in ../docs/recipes.html or +../../docs/reciped.pdf. Also, this is not an exhaustive list by any chance. +Zookeeper is used (and can be used) for more than what we have listed in the docs. + +7) To run the c tests in all the recipes, +- make sure the main zookeeper c libraries in +{top}/src/c/ are compiled. Run autoreconf -if;./configure; make. The libaries +will be installed in {top}/src/c/.libs. +- run autoreconf if;./configure;make run-check + in zookeeper-recipes/$recipename/src/c + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/zookeeper-recipes/build-recipes.xml ---------------------------------------------------------------------- diff --git a/zookeeper-recipes/build-recipes.xml b/zookeeper-recipes/build-recipes.xml new file mode 100644 index 0000000..b8457eb --- /dev/null +++ b/zookeeper-recipes/build-recipes.xml @@ -0,0 +1,161 @@ +<?xml version="1.0"?> + +<!-- + 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 + + 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. +--> + +<!-- Imported by recipesb/*/build.xml files to share generic targets. --> + +<project name="zookeeperbuildrecipes"> + + <property name="name" value="${ant.project.name}"/> + <property name="root" value="${basedir}"/> + + <property name="zk.root" location="${root}/../../"/> + + <property name="src.dir" location="${root}/src/java"/> + <property name="src.test" location="${root}/src/test"/> + + <property name="build.dir" location="${zk.root}/build/recipes/${name}"/> + <property name="build.classes" location="${build.dir}/classes"/> + <property name="build.test" location="${build.dir}/test"/> + + <property name="javac.deprecation" value="on"/> + <property name="javac.debug" value="on"/> + + <property name="build.encoding" value="utf8"/> + + <!-- to be overridden by sub-projects --> + <target name="check-recipes"/> + <target name="init-recipes"/> + + <property name="lib.jars.includes" value="lib/*.jar" /> + <property name="lib.jars.excludes" value="" /> + + <!-- prior to ant 1.7.1 fileset always fails if dir doesn't exist + so just point to bin directory and provide settings that exclude + everything - user can change as appropriate --> + <property name="additional.lib.dir" value="${zk.root}/bin" /> + <property name="additional.lib.dir.includes" value="**/*.jar" /> + <property name="additional.lib.dir.excludes" value="**/*.jar" /> + + <fileset id="lib.jars" dir="${root}"> + <include name="${lib.jars.includes}" /> + <exclude name="${lib.jars.excludes}" /> + </fileset> + + <path id="classpath"> + <pathelement location="${build.classes}"/> + <!-- allow the user to override (e.g. if there are local versions) --> + <fileset dir="${additional.lib.dir}"> + <include name="${additional.lib.dir.includes}" /> + <exclude name="${additional.lib.dir.excludes}" /> + </fileset> + <fileset refid="lib.jars"/> + <pathelement location="${zk.root}/build/classes"/> + <fileset dir="${zk.root}/build/lib"> + <include name="**/*.jar" /> + </fileset> + <fileset dir="${zk.root}/build/test/lib"> + <include name="**/*.jar"/> + </fileset> + <fileset dir="${zk.root}/src/java/lib"> + <include name="**/*.jar" /> + </fileset> + </path> + + <!-- ====================================================== --> + <!-- Stuff needed by all targets --> + <!-- ====================================================== --> + <target name="init" depends="check-recipes" unless="skip.recipes"> + <echo message="recipes: ${name}"/> + <mkdir dir="${build.dir}"/> + <mkdir dir="${build.classes}"/> + <mkdir dir="${build.test}"/> + <antcall target="init-recipes"/> + </target> + + <!-- ====================================================== --> + <!-- Compile a recipes files --> + <!-- ====================================================== --> + <target name="compile" depends="init" unless="skip.contrib"> + <echo message="contrib: ${name}"/> + + <javac + encoding="${build.encoding}" + srcdir="${src.dir}" + includes="**/*.java" + destdir="${build.classes}" + debug="${javac.debug}" + deprecation="${javac.deprecation}"> + <classpath refid="classpath"/> + </javac> + </target> + + <!-- ====================================================== --> + <!-- Make a recipes jar --> + <!-- ====================================================== --> + <target name="jar" depends="compile" unless="skip.recipes"> + <echo message="recipes: ${name}"/> + <jar + jarfile="${build.dir}/zookeeper-${version}-recipes-${name}.jar" + basedir="${build.classes}" + /> + </target> + + <!-- ====================================================== --> + <!-- Package a recipes files --> + <!-- ====================================================== --> + <target name="package" depends="jar" unless="skip.recipes"> + <echo message="recipes: ${name}"/> + + <mkdir dir="${dist.dir}${package.share}/recipes/${name}"/> + <copy todir="${dist.dir}${package.share}/recipes/${name}" includeEmptyDirs="false" + flatten="true"> + <fileset dir="${build.dir}"> + <include name="zookeeper-${version}-recipes-${name}.jar" /> + </fileset> + </copy> + </target> + + <!-- ================================================================== --> + <!-- Clean. Delete the build files, and their directories --> + <!-- ================================================================== --> + <target name="clean"> + <echo message="recipes: ${name}"/> + <delete dir="${build.dir}"/> + </target> + + <!-- ================================================================== --> + <!-- Utility features --> + <!-- ================================================================== --> + + <target name="checkMainIsAvailable"> + <available classname="org.apache.zookeeper.ZooKeeperMain" + property="mainIsCompiled"> + <!-- we can't use id=classpath, because available fails if fileset directory + doesn't exist --> + <classpath> + <pathelement location="${zk.root}/build/classes"/> + </classpath> + </available> + </target> + + <target name="checkMainCompiled" unless="mainIsCompiled" depends="checkMainIsAvailable"> + <fail message="ZooKeeper main must first be compiled (toplevel build.xml)"/> + </target> + +</project> http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/zookeeper-recipes/build.xml ---------------------------------------------------------------------- diff --git a/zookeeper-recipes/build.xml b/zookeeper-recipes/build.xml new file mode 100644 index 0000000..559d5a5 --- /dev/null +++ b/zookeeper-recipes/build.xml @@ -0,0 +1,61 @@ +<?xml version="1.0"?> + +<!-- + 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 + + 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. +--> + +<project name="zookeeperrecipes" default="compile" basedir="."> + + <!-- In case one of the contrib subdirectories --> + <!-- fails the build or test targets and you cannot fix it: --> + <!-- Then add to fileset: excludes="badcontrib/build.xml" --> + + <!-- ====================================================== --> + <!-- Compile contribs. --> + <!-- ====================================================== --> + <target name="compile"> + <subant target="jar"> + <fileset dir="." includes="*/build.xml"/> + </subant> + </target> + + <!-- ====================================================== --> + <!-- Package contrib jars. --> + <!-- ====================================================== --> + <target name="package"> + <subant target="package"> + <fileset dir="." includes="*/build.xml"/> + </subant> + </target> + + <!-- ====================================================== --> + <!-- Test all the contribs. --> + <!-- ====================================================== --> + <target name="test"> + <subant target="test"> + <fileset dir="." includes="*/build.xml"/> + </subant> + </target> + + <!-- ====================================================== --> + <!-- Clean all the contribs. --> + <!-- ====================================================== --> + <target name="clean"> + <subant target="clean"> + <fileset dir="." includes="*/build.xml"/> + </subant> + </target> +</project> http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/zookeeper-recipes/zookeeper-recipes-election/README.txt ---------------------------------------------------------------------- diff --git a/zookeeper-recipes/zookeeper-recipes-election/README.txt b/zookeeper-recipes/zookeeper-recipes-election/README.txt new file mode 100644 index 0000000..10447ed --- /dev/null +++ b/zookeeper-recipes/zookeeper-recipes-election/README.txt @@ -0,0 +1,27 @@ +<!-- + 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 + + 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. +--> + +1) This election interface recipe implements the leader election recipe +mentioned in ../../../docs/recipes.[html,pdf]. + +2) To compile the leader election java recipe you can just run ant jar from +this directory. +Please report any bugs on the jira + +http://issues.apache.org/jira/browse/ZOOKEEPER + + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/28de451a/zookeeper-recipes/zookeeper-recipes-election/build.xml ---------------------------------------------------------------------- diff --git a/zookeeper-recipes/zookeeper-recipes-election/build.xml b/zookeeper-recipes/zookeeper-recipes-election/build.xml new file mode 100644 index 0000000..8e1d00a --- /dev/null +++ b/zookeeper-recipes/zookeeper-recipes-election/build.xml @@ -0,0 +1,128 @@ +<!-- + 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 + + 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. +--> + +<project name="election" default="jar"> + <import file="../build-recipes.xml"/> + <property name="test.main.classes" value="${zk.root}/build/test/classes"/> + <property name="test.build.dir" value="${build.test}" /> + <property name="test.src.dir" value="test"/> + <property name="test.log.dir" value="${test.build.dir}/logs" /> + <property name="test.data.dir" value="${test.build.dir}/data" /> + <property name="test.data.upgrade.dir" value="${test.data.dir}/upgrade" /> + <property name="test.tmp.dir" value="${test.build.dir}/tmp" /> + <property name="test.output" value="no" /> + <property name="test.timeout" value="900000" /> + <property name="test.junit.output.format" value="plain" /> + <property name="test.junit.fork.mode" value="perTest" /> + <property name="test.junit.printsummary" value="yes" /> + <property name="test.junit.haltonfailure" value="no" /> + <property name="test.junit.maxmem" value="512m" /> + + <target name="setjarname"> + <property name="jarname" + value="${build.dir}/zookeeper-${version}-recipes-${name}.jar"/> + </target> + + <!-- Override jar target to specify main class --> + <target name="jar" depends="checkMainCompiled, setjarname, compile"> + <echo message="recipes: ${name}"/> + + <jar jarfile="${jarname}"> + <fileset file="${zk.root}/LICENSE.txt" /> + <fileset dir="${build.classes}"/> + <fileset dir="${build.test}"/> + </jar> + </target> + + <target name="test" depends="compile-test,test-init,test-category,junit.run" /> + + <target name="compile-test" depends="compile"> + <property name="target.jdk" value="${ant.java.version}" /> + <property name="src.test.local" location="${basedir}/test" /> + <mkdir dir="${build.test}"/> + <javac srcdir="${src.test.local}" + destdir="${build.test}" + target="${target.jdk}" + debug="on" encoding="${build.encoding}"> + <classpath refid="classpath" /> + <classpath> + <pathelement path="${test.main.classes}"/> + </classpath> + </javac> + </target> + + <target name="test-init" depends="jar,compile-test"> + <delete dir="${test.log.dir}" /> + <delete dir="${test.tmp.dir}" /> + <delete dir="${test.data.dir}" /> + <mkdir dir="${test.log.dir}" /> + <mkdir dir="${test.tmp.dir}" /> + <mkdir dir="${test.data.dir}" /> + </target> + + <target name="test-category"> + <property name="test.category" value=""/> + </target> + + <target name="junit.run"> + <echo message="${test.src.dir}" /> + <junit showoutput="${test.output}" + printsummary="${test.junit.printsummary}" + haltonfailure="${test.junit.haltonfailure}" + fork="yes" + forkmode="${test.junit.fork.mode}" + maxmemory="${test.junit.maxmem}" + dir="${basedir}" timeout="${test.timeout}" + errorProperty="tests.failed" failureProperty="tests.failed"> + <sysproperty key="build.test.dir" value="${test.tmp.dir}" /> + <sysproperty key="test.data.dir" value="${test.data.dir}" /> + <sysproperty key="log4j.configuration" + value="file:${basedir}/conf/log4j.properties" /> + <classpath refid="classpath"/> + <classpath> + <pathelement path="${build.test}" /> + <pathelement path="${test.main.classes}"/> + </classpath> + <formatter type="${test.junit.output.format}" /> + <batchtest todir="${test.log.dir}" unless="testcase"> + <fileset dir="${test.src.dir}" + includes="**/*${test.category}Test.java"/> + </batchtest> + <batchtest todir="${test.log.dir}" if="testcase"> + <fileset dir="${test.src.dir}" includes="**/${testcase}.java"/> + </batchtest> + </junit> + <fail if="tests.failed">Tests failed!</fail> + </target> + + <target name="package" depends="jar, zookeeperbuildrecipes.package" + unless="skip.recipes"> + + <copy file="${basedir}/build.xml" todir="${dist.dir}/recipes/${name}"/> + + <mkdir dir="${dist.dir}/recipes/${name}/test"/> + <copy todir="${dist.dir}/recipes/${name}/test"> + <fileset dir="${basedir}/test"/> + </copy> + <mkdir dir="${dist.dir}/recipes/${name}/src"/> + <copy todir="${dist.dir}/recipes/${name}/src"> + <fileset dir="${basedir}/src"/> + </copy> + </target> + +</project> +
