zookeeper.c 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef DLL_EXPORT
  19. # define USE_STATIC_LIB
  20. #endif
  21. #if defined(__CYGWIN__)
  22. #define USE_IPV6
  23. #endif
  24. #include <zookeeper.h>
  25. #include <zookeeper.jute.h>
  26. #include <proto.h>
  27. #include "zk_adaptor.h"
  28. #include "zookeeper_log.h"
  29. #include "zk_hashtable.h"
  30. #include <stdlib.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <time.h>
  34. #include <sys/time.h>
  35. #include <sys/socket.h>
  36. #include <poll.h>
  37. #include <netinet/in.h>
  38. #include <netinet/tcp.h>
  39. #include <arpa/inet.h>
  40. #include <netdb.h>
  41. #include <errno.h>
  42. #include <unistd.h>
  43. #include <fcntl.h>
  44. #include <assert.h>
  45. #include <stdarg.h>
  46. #include <limits.h>
  47. #include "config.h"
  48. #ifdef HAVE_SYS_UTSNAME_H
  49. #include <sys/utsname.h>
  50. #endif
  51. #ifdef HAVE_GETPWUID_R
  52. #include <pwd.h>
  53. #endif
  54. #define IF_DEBUG(x) if(logLevel==ZOO_LOG_LEVEL_DEBUG) {x;}
  55. const int ZOOKEEPER_WRITE = 1 << 0;
  56. const int ZOOKEEPER_READ = 1 << 1;
  57. const int ZOO_EPHEMERAL = 1 << 0;
  58. const int ZOO_SEQUENCE = 1 << 1;
  59. const int ZOO_EXPIRED_SESSION_STATE = EXPIRED_SESSION_STATE_DEF;
  60. const int ZOO_AUTH_FAILED_STATE = AUTH_FAILED_STATE_DEF;
  61. const int ZOO_CONNECTING_STATE = CONNECTING_STATE_DEF;
  62. const int ZOO_ASSOCIATING_STATE = ASSOCIATING_STATE_DEF;
  63. const int ZOO_CONNECTED_STATE = CONNECTED_STATE_DEF;
  64. static __attribute__ ((unused)) const char* state2String(int state){
  65. switch(state){
  66. case 0:
  67. return "ZOO_CLOSED_STATE";
  68. case CONNECTING_STATE_DEF:
  69. return "ZOO_CONNECTING_STATE";
  70. case ASSOCIATING_STATE_DEF:
  71. return "ZOO_ASSOCIATING_STATE";
  72. case CONNECTED_STATE_DEF:
  73. return "ZOO_CONNECTED_STATE";
  74. case EXPIRED_SESSION_STATE_DEF:
  75. return "ZOO_EXPIRED_SESSION_STATE";
  76. case AUTH_FAILED_STATE_DEF:
  77. return "ZOO_AUTH_FAILED_STATE";
  78. }
  79. return "INVALID_STATE";
  80. }
  81. const int ZOO_CREATED_EVENT = CREATED_EVENT_DEF;
  82. const int ZOO_DELETED_EVENT = DELETED_EVENT_DEF;
  83. const int ZOO_CHANGED_EVENT = CHANGED_EVENT_DEF;
  84. const int ZOO_CHILD_EVENT = CHILD_EVENT_DEF;
  85. const int ZOO_SESSION_EVENT = SESSION_EVENT_DEF;
  86. const int ZOO_NOTWATCHING_EVENT = NOTWATCHING_EVENT_DEF;
  87. static __attribute__ ((unused)) const char* watcherEvent2String(int ev){
  88. switch(ev){
  89. case 0:
  90. return "ZOO_ERROR_EVENT";
  91. case CREATED_EVENT_DEF:
  92. return "ZOO_CREATED_EVENT";
  93. case DELETED_EVENT_DEF:
  94. return "ZOO_DELETED_EVENT";
  95. case CHANGED_EVENT_DEF:
  96. return "ZOO_CHANGED_EVENT";
  97. case CHILD_EVENT_DEF:
  98. return "ZOO_CHILD_EVENT";
  99. case SESSION_EVENT_DEF:
  100. return "ZOO_SESSION_EVENT";
  101. case NOTWATCHING_EVENT_DEF:
  102. return "ZOO_NOTWATCHING_EVENT";
  103. }
  104. return "INVALID_EVENT";
  105. }
  106. const int ZOO_PERM_READ = 1 << 0;
  107. const int ZOO_PERM_WRITE = 1 << 1;
  108. const int ZOO_PERM_CREATE = 1 << 2;
  109. const int ZOO_PERM_DELETE = 1 << 3;
  110. const int ZOO_PERM_ADMIN = 1 << 4;
  111. const int ZOO_PERM_ALL = 0x1f;
  112. struct Id ZOO_ANYONE_ID_UNSAFE = {"world", "anyone"};
  113. struct Id ZOO_AUTH_IDS = {"auth", ""};
  114. static struct ACL _OPEN_ACL_UNSAFE_ACL[] = {{0x1f, {"world", "anyone"}}};
  115. static struct ACL _READ_ACL_UNSAFE_ACL[] = {{0x01, {"world", "anyone"}}};
  116. static struct ACL _CREATOR_ALL_ACL_ACL[] = {{0x1f, {"auth", ""}}};
  117. struct ACL_vector ZOO_OPEN_ACL_UNSAFE = { 1, _OPEN_ACL_UNSAFE_ACL};
  118. struct ACL_vector ZOO_READ_ACL_UNSAFE = { 1, _READ_ACL_UNSAFE_ACL};
  119. struct ACL_vector ZOO_CREATOR_ALL_ACL = { 1, _CREATOR_ALL_ACL_ACL};
  120. #define COMPLETION_WATCH -1
  121. #define COMPLETION_VOID 0
  122. #define COMPLETION_STAT 1
  123. #define COMPLETION_DATA 2
  124. #define COMPLETION_STRINGLIST 3
  125. #define COMPLETION_STRINGLIST_STAT 4
  126. #define COMPLETION_ACLLIST 5
  127. #define COMPLETION_STRING 6
  128. typedef struct _auth_completion_list {
  129. void_completion_t completion;
  130. const char *auth_data;
  131. struct _auth_completion_list *next;
  132. } auth_completion_list_t;
  133. typedef struct _completion_list {
  134. int xid;
  135. int completion_type; /* one of the COMPLETION_* values */
  136. union {
  137. void_completion_t void_result;
  138. stat_completion_t stat_result;
  139. data_completion_t data_result;
  140. strings_completion_t strings_result;
  141. strings_stat_completion_t strings_stat_result;
  142. acl_completion_t acl_result;
  143. string_completion_t string_result;
  144. struct watcher_object_list *watcher_result;
  145. } c;
  146. const void *data;
  147. buffer_list_t *buffer;
  148. struct _completion_list *next;
  149. watcher_registration_t* watcher;
  150. } completion_list_t;
  151. const char*err2string(int err);
  152. static int queue_session_event(zhandle_t *zh, int state);
  153. static const char* format_endpoint_info(const struct sockaddr_storage* ep);
  154. static const char* format_current_endpoint_info(zhandle_t* zh);
  155. /* completion routine forward declarations */
  156. static int add_completion(zhandle_t *zh, int xid, int completion_type,
  157. const void *dc, const void *data, int add_to_front,watcher_registration_t* wo);
  158. static completion_list_t* create_completion_entry(int xid, int completion_type,
  159. const void *dc, const void *data,watcher_registration_t* wo);
  160. static void destroy_completion_entry(completion_list_t* c);
  161. static void queue_completion_nolock(completion_head_t *list, completion_list_t *c,
  162. int add_to_front);
  163. static void queue_completion(completion_head_t *list, completion_list_t *c,
  164. int add_to_front);
  165. static int handle_socket_error_msg(zhandle_t *zh, int line, int rc,
  166. const char* format,...);
  167. static void cleanup_bufs(zhandle_t *zh,int callCompletion,int rc);
  168. static int disable_conn_permute=0; // permute enabled by default
  169. static __attribute__((unused)) void print_completion_queue(zhandle_t *zh);
  170. static void *SYNCHRONOUS_MARKER = (void*)&SYNCHRONOUS_MARKER;
  171. static int isValidPath(const char* path, const int flags);
  172. const void *zoo_get_context(zhandle_t *zh)
  173. {
  174. return zh->context;
  175. }
  176. void zoo_set_context(zhandle_t *zh, void *context)
  177. {
  178. if (zh != NULL) {
  179. zh->context = context;
  180. }
  181. }
  182. int zoo_recv_timeout(zhandle_t *zh)
  183. {
  184. return zh->recv_timeout;
  185. }
  186. /** these functions are thread unsafe, so make sure that
  187. zoo_lock_auth is called before you access them **/
  188. static auth_info* get_last_auth(auth_list_head_t *auth_list) {
  189. auth_info *element;
  190. element = auth_list->auth;
  191. if (element == NULL) {
  192. return NULL;
  193. }
  194. while (element->next != NULL) {
  195. element = element->next;
  196. }
  197. return element;
  198. }
  199. static void free_auth_completion(auth_completion_list_t *a_list) {
  200. auth_completion_list_t *tmp, *ftmp;
  201. if (a_list == NULL) {
  202. return;
  203. }
  204. tmp = a_list->next;
  205. while (tmp != NULL) {
  206. ftmp = tmp;
  207. tmp = tmp->next;
  208. ftmp->completion = NULL;
  209. ftmp->auth_data = NULL;
  210. free(ftmp);
  211. }
  212. a_list->completion = NULL;
  213. a_list->auth_data = NULL;
  214. a_list->next = NULL;
  215. return;
  216. }
  217. static void add_auth_completion(auth_completion_list_t* a_list, void_completion_t* completion,
  218. const char *data) {
  219. auth_completion_list_t *element;
  220. auth_completion_list_t *n_element;
  221. element = a_list;
  222. if (a_list->completion == NULL) {
  223. //this is the first element
  224. a_list->completion = *completion;
  225. a_list->next = NULL;
  226. a_list->auth_data = data;
  227. return;
  228. }
  229. while (element->next != NULL) {
  230. element = element->next;
  231. }
  232. n_element = (auth_completion_list_t*) malloc(sizeof(auth_completion_list_t));
  233. n_element->next = NULL;
  234. n_element->completion = *completion;
  235. n_element->auth_data = data;
  236. element->next = n_element;
  237. return;
  238. }
  239. static void get_auth_completions(auth_list_head_t *auth_list, auth_completion_list_t *a_list) {
  240. auth_info *element;
  241. element = auth_list->auth;
  242. if (element == NULL) {
  243. return;
  244. }
  245. while (element) {
  246. if (element->completion) {
  247. add_auth_completion(a_list, &element->completion, element->data);
  248. }
  249. element->completion = NULL;
  250. element = element->next;
  251. }
  252. return;
  253. }
  254. static void add_last_auth(auth_list_head_t *auth_list, auth_info *add_el) {
  255. auth_info *element;
  256. element = auth_list->auth;
  257. if (element == NULL) {
  258. //first element in the list
  259. auth_list->auth = add_el;
  260. return;
  261. }
  262. while (element->next != NULL) {
  263. element = element->next;
  264. }
  265. element->next = add_el;
  266. return;
  267. }
  268. static void init_auth_info(auth_list_head_t *auth_list)
  269. {
  270. auth_list->auth = NULL;
  271. }
  272. static void mark_active_auth(zhandle_t *zh) {
  273. auth_list_head_t auth_h = zh->auth_h;
  274. auth_info *element;
  275. if (auth_h.auth == NULL) {
  276. return;
  277. }
  278. element = auth_h.auth;
  279. while (element->next != NULL) {
  280. element->state = 1;
  281. element = element->next;
  282. }
  283. }
  284. static void free_auth_info(auth_list_head_t *auth_list)
  285. {
  286. auth_info *auth = auth_list->auth;
  287. while (auth != NULL) {
  288. auth_info* old_auth = NULL;
  289. if(auth->scheme!=NULL)
  290. free(auth->scheme);
  291. deallocate_Buffer(&auth->auth);
  292. old_auth = auth;
  293. auth = auth->next;
  294. free(old_auth);
  295. }
  296. init_auth_info(auth_list);
  297. }
  298. int is_unrecoverable(zhandle_t *zh)
  299. {
  300. return (zh->state<0)? ZINVALIDSTATE: ZOK;
  301. }
  302. zk_hashtable *exists_result_checker(zhandle_t *zh, int rc)
  303. {
  304. if (rc == ZOK) {
  305. return zh->active_node_watchers;
  306. } else if (rc == ZNONODE) {
  307. return zh->active_exist_watchers;
  308. }
  309. return 0;
  310. }
  311. zk_hashtable *data_result_checker(zhandle_t *zh, int rc)
  312. {
  313. return rc==ZOK ? zh->active_node_watchers : 0;
  314. }
  315. zk_hashtable *child_result_checker(zhandle_t *zh, int rc)
  316. {
  317. return rc==ZOK ? zh->active_child_watchers : 0;
  318. }
  319. /**
  320. * Frees and closes everything associated with a handle,
  321. * including the handle itself.
  322. */
  323. static void destroy(zhandle_t *zh)
  324. {
  325. if (zh == NULL) {
  326. return;
  327. }
  328. /* call any outstanding completions with a special error code */
  329. cleanup_bufs(zh,1,ZCLOSING);
  330. if (zh->hostname != 0) {
  331. free(zh->hostname);
  332. zh->hostname = NULL;
  333. }
  334. if (zh->fd != -1) {
  335. close(zh->fd);
  336. zh->fd = -1;
  337. zh->state = 0;
  338. }
  339. if (zh->addrs != 0) {
  340. free(zh->addrs);
  341. zh->addrs = NULL;
  342. }
  343. if (zh->chroot != 0) {
  344. free(zh->chroot);
  345. zh->chroot = NULL;
  346. }
  347. free_auth_info(&zh->auth_h);
  348. destroy_zk_hashtable(zh->active_node_watchers);
  349. destroy_zk_hashtable(zh->active_exist_watchers);
  350. destroy_zk_hashtable(zh->active_child_watchers);
  351. }
  352. static void setup_random()
  353. {
  354. int seed;
  355. int fd = open("/dev/urandom", O_RDONLY);
  356. if (fd == -1) {
  357. seed = getpid();
  358. } else {
  359. int rc = read(fd, &seed, sizeof(seed));
  360. assert(rc == sizeof(seed));
  361. close(fd);
  362. }
  363. srandom(seed);
  364. }
  365. #ifndef __CYGWIN__
  366. /**
  367. * get the errno from the return code
  368. * of get addrinfo. Errno is not set
  369. * with the call to getaddrinfo, so thats
  370. * why we have to do this.
  371. */
  372. static int getaddrinfo_errno(int rc) {
  373. switch(rc) {
  374. case EAI_NONAME:
  375. case EAI_NODATA:
  376. return ENOENT;
  377. case EAI_MEMORY:
  378. return ENOMEM;
  379. default:
  380. return EINVAL;
  381. }
  382. }
  383. #endif
  384. /**
  385. * fill in the addrs array of the zookeeper servers in the zhandle. after filling
  386. * them in, we will permute them for load balancing.
  387. */
  388. int getaddrs(zhandle_t *zh)
  389. {
  390. char *hosts = strdup(zh->hostname);
  391. char *host;
  392. char *strtok_last;
  393. struct sockaddr_storage *addr;
  394. int i;
  395. int rc;
  396. int alen = 0; /* the allocated length of the addrs array */
  397. zh->addrs_count = 0;
  398. if (zh->addrs) {
  399. free(zh->addrs);
  400. zh->addrs = 0;
  401. }
  402. if (!hosts) {
  403. LOG_ERROR(("out of memory"));
  404. errno=ENOMEM;
  405. return ZSYSTEMERROR;
  406. }
  407. zh->addrs = 0;
  408. host=strtok_r(hosts, ",", &strtok_last);
  409. while(host) {
  410. char *port_spec = strrchr(host, ':');
  411. char *end_port_spec;
  412. int port;
  413. if (!port_spec) {
  414. LOG_ERROR(("no port in %s", host));
  415. errno=EINVAL;
  416. rc=ZBADARGUMENTS;
  417. goto fail;
  418. }
  419. *port_spec = '\0';
  420. port_spec++;
  421. port = strtol(port_spec, &end_port_spec, 0);
  422. if (!*port_spec || *end_port_spec) {
  423. LOG_ERROR(("invalid port in %s", host));
  424. errno=EINVAL;
  425. rc=ZBADARGUMENTS;
  426. goto fail;
  427. }
  428. #if defined(__CYGWIN__)
  429. // sadly CYGWIN doesn't have getaddrinfo
  430. // but happily gethostbyname is threadsafe in windows
  431. {
  432. struct hostent *he;
  433. char **ptr;
  434. struct sockaddr_in *addr4;
  435. he = gethostbyname(host);
  436. if (!he) {
  437. LOG_ERROR(("could not resolve %s", host));
  438. errno=ENOENT;
  439. rc=ZBADARGUMENTS;
  440. goto fail;
  441. }
  442. /* Setup the address array */
  443. for(ptr = he->h_addr_list;*ptr != 0; ptr++) {
  444. if (zh->addrs_count == alen) {
  445. alen += 16;
  446. zh->addrs = realloc(zh->addrs, sizeof(*zh->addrs)*alen);
  447. if (zh->addrs == 0) {
  448. LOG_ERROR(("out of memory"));
  449. errno=ENOMEM;
  450. rc=ZSYSTEMERROR;
  451. goto fail;
  452. }
  453. }
  454. addr = &zh->addrs[zh->addrs_count];
  455. addr4 = (struct sockaddr_in*)addr;
  456. addr->ss_family = he->h_addrtype;
  457. if (addr->ss_family == AF_INET) {
  458. addr4->sin_port = htons(port);
  459. memset(&addr4->sin_zero, 0, sizeof(addr4->sin_zero));
  460. memcpy(&addr4->sin_addr, *ptr, he->h_length);
  461. zh->addrs_count++;
  462. }
  463. #if defined(AF_INET6)
  464. else if (addr->ss_family == AF_INET6) {
  465. struct sockaddr_in6 *addr6;
  466. addr6 = (struct sockaddr_in6*)addr;
  467. addr6->sin6_port = htons(port);
  468. addr6->sin6_scope_id = 0;
  469. addr6->sin6_flowinfo = 0;
  470. memcpy(&addr6->sin6_addr, *ptr, he->h_length);
  471. zh->addrs_count++;
  472. }
  473. #endif
  474. else {
  475. LOG_WARN(("skipping unknown address family %x for %s",
  476. addr->ss_family, zh->hostname));
  477. }
  478. }
  479. host = strtok_r(0, ",", &strtok_last);
  480. }
  481. #else
  482. {
  483. struct addrinfo hints, *res, *res0;
  484. memset(&hints, 0, sizeof(hints));
  485. #ifdef AI_ADDRCONFIG
  486. hints.ai_flags = AI_ADDRCONFIG;
  487. #else
  488. hints.ai_flags = 0;
  489. #endif
  490. hints.ai_family = AF_UNSPEC;
  491. hints.ai_socktype = SOCK_STREAM;
  492. hints.ai_protocol = IPPROTO_TCP;
  493. while(isspace(*host) && host != strtok_last)
  494. host++;
  495. if ((rc = getaddrinfo(host, port_spec, &hints, &res0)) != 0) {
  496. //bug in getaddrinfo implementation when it returns
  497. //EAI_BADFLAGS or EAI_ADDRFAMILY with AF_UNSPEC and
  498. // ai_flags as AI_ADDRCONFIG
  499. #ifdef AI_ADDRCONFIG
  500. if ((hints.ai_flags == AI_ADDRCONFIG) &&
  501. ((rc ==EAI_BADFLAGS) || (rc == EAI_ADDRFAMILY))) {
  502. //reset ai_flags to null
  503. hints.ai_flags = 0;
  504. //retry getaddrinfo
  505. rc = getaddrinfo(host, port_spec, &hints, &res0);
  506. }
  507. #endif
  508. if (rc != 0) {
  509. errno = getaddrinfo_errno(rc);
  510. LOG_ERROR(("getaddrinfo: %s\n", strerror(errno)));
  511. rc=ZSYSTEMERROR;
  512. goto fail;
  513. }
  514. }
  515. for (res = res0; res; res = res->ai_next) {
  516. // Expand address list if needed
  517. if (zh->addrs_count == alen) {
  518. void *tmpaddr;
  519. alen += 16;
  520. tmpaddr = realloc(zh->addrs, sizeof(*zh->addrs)*alen);
  521. if (tmpaddr == 0) {
  522. LOG_ERROR(("out of memory"));
  523. errno=ENOMEM;
  524. rc=ZSYSTEMERROR;
  525. goto fail;
  526. }
  527. zh->addrs=tmpaddr;
  528. }
  529. // Copy addrinfo into address list
  530. addr = &zh->addrs[zh->addrs_count];
  531. switch (res->ai_family) {
  532. case AF_INET:
  533. #if defined(AF_INET6)
  534. case AF_INET6:
  535. #endif
  536. memcpy(addr, res->ai_addr, res->ai_addrlen);
  537. ++zh->addrs_count;
  538. break;
  539. default:
  540. LOG_WARN(("skipping unknown address family %x for %s",
  541. res->ai_family, zh->hostname));
  542. break;
  543. }
  544. }
  545. freeaddrinfo(res0);
  546. host = strtok_r(0, ",", &strtok_last);
  547. }
  548. #endif
  549. }
  550. free(hosts);
  551. if(!disable_conn_permute){
  552. setup_random();
  553. /* Permute */
  554. for(i = 0; i < zh->addrs_count; i++) {
  555. struct sockaddr_storage *s1 = zh->addrs + random()%zh->addrs_count;
  556. struct sockaddr_storage *s2 = zh->addrs + random()%zh->addrs_count;
  557. if (s1 != s2) {
  558. struct sockaddr_storage t = *s1;
  559. *s1 = *s2;
  560. *s2 = t;
  561. }
  562. }
  563. }
  564. return ZOK;
  565. fail:
  566. if (zh->addrs) {
  567. free(zh->addrs);
  568. zh->addrs=0;
  569. }
  570. if (hosts) {
  571. free(hosts);
  572. }
  573. return rc;
  574. }
  575. const clientid_t *zoo_client_id(zhandle_t *zh)
  576. {
  577. return &zh->client_id;
  578. }
  579. static void null_watcher_fn(zhandle_t* p1, int p2, int p3,const char* p4,void*p5){}
  580. watcher_fn zoo_set_watcher(zhandle_t *zh,watcher_fn newFn)
  581. {
  582. watcher_fn oldWatcher=zh->watcher;
  583. if (newFn) {
  584. zh->watcher = newFn;
  585. } else {
  586. zh->watcher = null_watcher_fn;
  587. }
  588. return oldWatcher;
  589. }
  590. static void log_env() {
  591. char buf[2048];
  592. #ifdef HAVE_SYS_UTSNAME_H
  593. struct utsname utsname;
  594. #endif
  595. #if defined(HAVE_GETUID) && defined(HAVE_GETPWUID_R)
  596. struct passwd pw;
  597. struct passwd *pwp = NULL;
  598. uid_t uid = 0;
  599. #endif
  600. LOG_INFO(("Client environment:zookeeper.version=%s", PACKAGE_STRING));
  601. #ifdef HAVE_GETHOSTNAME
  602. gethostname(buf, sizeof(buf));
  603. LOG_INFO(("Client environment:host.name=%s", buf));
  604. #else
  605. LOG_INFO(("Client environment:host.name=<not implemented>"));
  606. #endif
  607. #ifdef HAVE_SYS_UTSNAME_H
  608. uname(&utsname);
  609. LOG_INFO(("Client environment:os.name=%s", utsname.sysname));
  610. LOG_INFO(("Client environment:os.arch=%s", utsname.release));
  611. LOG_INFO(("Client environment:os.version=%s", utsname.version));
  612. #else
  613. LOG_INFO(("Client environment:os.name=<not implemented>"));
  614. LOG_INFO(("Client environment:os.arch=<not implemented>"));
  615. LOG_INFO(("Client environment:os.version=<not implemented>"));
  616. #endif
  617. #ifdef HAVE_GETLOGIN
  618. LOG_INFO(("Client environment:user.name=%s", getlogin()));
  619. #else
  620. LOG_INFO(("Client environment:user.name=<not implemented>"));
  621. #endif
  622. #if defined(HAVE_GETUID) && defined(HAVE_GETPWUID_R)
  623. uid = getuid();
  624. if (!getpwuid_r(uid, &pw, buf, sizeof(buf), &pwp)) {
  625. LOG_INFO(("Client environment:user.home=%s", pw.pw_dir));
  626. } else {
  627. LOG_INFO(("Client environment:user.home=<NA>"));
  628. }
  629. #else
  630. LOG_INFO(("Client environment:user.home=<not implemented>"));
  631. #endif
  632. #ifdef HAVE_GETCWD
  633. if (!getcwd(buf, sizeof(buf))) {
  634. LOG_INFO(("Client environment:user.dir=<toolong>"));
  635. } else {
  636. LOG_INFO(("Client environment:user.dir=%s", buf));
  637. }
  638. #else
  639. LOG_INFO(("Client environment:user.dir=<not implemented>"));
  640. #endif
  641. }
  642. /**
  643. * Create a zookeeper handle associated with the given host and port.
  644. */
  645. zhandle_t *zookeeper_init(const char *host, watcher_fn watcher,
  646. int recv_timeout, const clientid_t *clientid, void *context, int flags)
  647. {
  648. int errnosave = 0;
  649. zhandle_t *zh = NULL;
  650. char *index_chroot = NULL;
  651. log_env();
  652. LOG_INFO(("Initiating client connection, host=%s sessionTimeout=%d watcher=%p"
  653. " sessionId=%#llx sessionPasswd=%s context=%p flags=%d",
  654. host,
  655. recv_timeout,
  656. watcher,
  657. (clientid == 0 ? 0 : clientid->client_id),
  658. ((clientid == 0) || (clientid->passwd == 0) ?
  659. "<null>" : "<hidden>"),
  660. context,
  661. flags));
  662. zh = calloc(1, sizeof(*zh));
  663. if (!zh) {
  664. return 0;
  665. }
  666. zh->fd = -1;
  667. zh->state = 0;
  668. zh->context = context;
  669. zh->recv_timeout = recv_timeout;
  670. init_auth_info(&zh->auth_h);
  671. if (watcher) {
  672. zh->watcher = watcher;
  673. } else {
  674. zh->watcher = null_watcher_fn;
  675. }
  676. if (host == 0 || *host == 0) { // what we shouldn't dup
  677. errno=EINVAL;
  678. goto abort;
  679. }
  680. //parse the host to get the chroot if
  681. //available
  682. index_chroot = strchr(host, '/');
  683. if (index_chroot) {
  684. zh->chroot = strdup(index_chroot);
  685. // if chroot is just / set it to null
  686. if (strlen(zh->chroot) == 1) {
  687. zh->chroot = NULL;
  688. }
  689. // cannot use strndup so allocate and strcpy
  690. zh->hostname = (char *) malloc(index_chroot - host + 1);
  691. zh->hostname = strncpy(zh->hostname, host, (index_chroot - host));
  692. //strncpy does not null terminate
  693. *(zh->hostname + (index_chroot - host)) = '\0';
  694. } else {
  695. zh->chroot = NULL;
  696. zh->hostname = strdup(host);
  697. }
  698. if (zh->chroot && !isValidPath(zh->chroot, 0)) {
  699. errno = EINVAL;
  700. goto abort;
  701. }
  702. if (zh->hostname == 0) {
  703. goto abort;
  704. }
  705. if(getaddrs(zh)!=0) {
  706. goto abort;
  707. }
  708. zh->connect_index = 0;
  709. if (clientid) {
  710. memcpy(&zh->client_id, clientid, sizeof(zh->client_id));
  711. } else {
  712. memset(&zh->client_id, 0, sizeof(zh->client_id));
  713. }
  714. zh->primer_buffer.buffer = zh->primer_storage_buffer;
  715. zh->primer_buffer.curr_offset = 0;
  716. zh->primer_buffer.len = sizeof(zh->primer_storage_buffer);
  717. zh->primer_buffer.next = 0;
  718. zh->last_zxid = 0;
  719. zh->next_deadline.tv_sec=zh->next_deadline.tv_usec=0;
  720. zh->socket_readable.tv_sec=zh->socket_readable.tv_usec=0;
  721. zh->active_node_watchers=create_zk_hashtable();
  722. zh->active_exist_watchers=create_zk_hashtable();
  723. zh->active_child_watchers=create_zk_hashtable();
  724. if (adaptor_init(zh) == -1) {
  725. goto abort;
  726. }
  727. return zh;
  728. abort:
  729. errnosave=errno;
  730. destroy(zh);
  731. free(zh);
  732. errno=errnosave;
  733. return 0;
  734. }
  735. /**
  736. * deallocated the free_path only its beeen allocated
  737. * and not equal to path
  738. */
  739. void free_duplicate_path(const char *free_path, const char* path) {
  740. if (free_path != path) {
  741. free((void*)free_path);
  742. }
  743. }
  744. /**
  745. prepend the chroot path if available else return the path
  746. */
  747. static char* prepend_string(zhandle_t *zh, const char* client_path) {
  748. char *ret_str;
  749. if (zh->chroot == NULL)
  750. return (char *) client_path;
  751. // handle the chroot itself, client_path = "/"
  752. if (strlen(client_path) == 1) {
  753. return strdup(zh->chroot);
  754. }
  755. ret_str = (char *) malloc(strlen(zh->chroot) + strlen(client_path) + 1);
  756. strcpy(ret_str, zh->chroot);
  757. return strcat(ret_str, client_path);
  758. }
  759. /**
  760. strip off the chroot string from the server path
  761. if there is one else return the exact path
  762. */
  763. char* sub_string(zhandle_t *zh, const char* server_path) {
  764. char *ret_str;
  765. if (zh->chroot == NULL)
  766. return (char *) server_path;
  767. if (strncmp(server_path, zh->chroot, strlen(zh->chroot) != 0)) {
  768. LOG_ERROR(("server path %s does not include chroot path %s",
  769. server_path, zh->chroot));
  770. return NULL;
  771. }
  772. if (strlen(server_path) == strlen(zh->chroot)) {
  773. //return "/"
  774. ret_str = strdup("/");
  775. return ret_str;
  776. }
  777. ret_str = strdup(server_path + strlen(zh->chroot));
  778. return ret_str;
  779. }
  780. static buffer_list_t *allocate_buffer(char *buff, int len)
  781. {
  782. buffer_list_t *buffer = calloc(1, sizeof(*buffer));
  783. if (buffer == 0)
  784. return 0;
  785. buffer->len = len==0?sizeof(*buffer):len;
  786. buffer->curr_offset = 0;
  787. buffer->buffer = buff;
  788. buffer->next = 0;
  789. return buffer;
  790. }
  791. static void free_buffer(buffer_list_t *b)
  792. {
  793. if (!b) {
  794. return;
  795. }
  796. if (b->buffer) {
  797. free(b->buffer);
  798. }
  799. free(b);
  800. }
  801. static buffer_list_t *dequeue_buffer(buffer_head_t *list)
  802. {
  803. buffer_list_t *b;
  804. lock_buffer_list(list);
  805. b = list->head;
  806. if (b) {
  807. list->head = b->next;
  808. if (!list->head) {
  809. assert(b == list->last);
  810. list->last = 0;
  811. }
  812. }
  813. unlock_buffer_list(list);
  814. return b;
  815. }
  816. static int remove_buffer(buffer_head_t *list)
  817. {
  818. buffer_list_t *b = dequeue_buffer(list);
  819. if (!b) {
  820. return 0;
  821. }
  822. free_buffer(b);
  823. return 1;
  824. }
  825. static void queue_buffer(buffer_head_t *list, buffer_list_t *b, int add_to_front)
  826. {
  827. b->next = 0;
  828. lock_buffer_list(list);
  829. if (list->head) {
  830. assert(list->last);
  831. // The list is not empty
  832. if (add_to_front) {
  833. b->next = list->head;
  834. list->head = b;
  835. } else {
  836. list->last->next = b;
  837. list->last = b;
  838. }
  839. }else{
  840. // The list is empty
  841. assert(!list->head);
  842. list->head = b;
  843. list->last = b;
  844. }
  845. unlock_buffer_list(list);
  846. }
  847. static int queue_buffer_bytes(buffer_head_t *list, char *buff, int len)
  848. {
  849. buffer_list_t *b = allocate_buffer(buff,len);
  850. if (!b)
  851. return ZSYSTEMERROR;
  852. queue_buffer(list, b, 0);
  853. return ZOK;
  854. }
  855. static int queue_front_buffer_bytes(buffer_head_t *list, char *buff, int len)
  856. {
  857. buffer_list_t *b = allocate_buffer(buff,len);
  858. if (!b)
  859. return ZSYSTEMERROR;
  860. queue_buffer(list, b, 1);
  861. return ZOK;
  862. }
  863. static __attribute__ ((unused)) int get_queue_len(buffer_head_t *list)
  864. {
  865. int i;
  866. buffer_list_t *ptr;
  867. lock_buffer_list(list);
  868. ptr = list->head;
  869. for (i=0; ptr!=0; ptr=ptr->next, i++)
  870. ;
  871. unlock_buffer_list(list);
  872. return i;
  873. }
  874. /* returns:
  875. * -1 if send failed,
  876. * 0 if send would block while sending the buffer (or a send was incomplete),
  877. * 1 if success
  878. */
  879. static int send_buffer(int fd, buffer_list_t *buff)
  880. {
  881. int len = buff->len;
  882. int off = buff->curr_offset;
  883. int rc = -1;
  884. if (off < 4) {
  885. /* we need to send the length at the beginning */
  886. int nlen = htonl(len);
  887. char *b = (char*)&nlen;
  888. rc = send(fd, b + off, sizeof(nlen) - off, 0);
  889. if (rc == -1) {
  890. if (errno != EAGAIN) {
  891. return -1;
  892. } else {
  893. return 0;
  894. }
  895. } else {
  896. buff->curr_offset += rc;
  897. }
  898. off = buff->curr_offset;
  899. }
  900. if (off >= 4) {
  901. /* want off to now represent the offset into the buffer */
  902. off -= sizeof(buff->len);
  903. rc = send(fd, buff->buffer + off, len - off, 0);
  904. if (rc == -1) {
  905. if (errno != EAGAIN) {
  906. return -1;
  907. }
  908. } else {
  909. buff->curr_offset += rc;
  910. }
  911. }
  912. return buff->curr_offset == len + sizeof(buff->len);
  913. }
  914. /* returns:
  915. * -1 if recv call failed,
  916. * 0 if recv would block,
  917. * 1 if success
  918. */
  919. static int recv_buffer(int fd, buffer_list_t *buff)
  920. {
  921. int off = buff->curr_offset;
  922. int rc = 0;
  923. //fprintf(LOGSTREAM, "rc = %d, off = %d, line %d\n", rc, off, __LINE__);
  924. /* if buffer is less than 4, we are reading in the length */
  925. if (off < 4) {
  926. char *buffer = (char*)&(buff->len);
  927. rc = recv(fd, buffer+off, sizeof(int)-off, 0);
  928. //fprintf(LOGSTREAM, "rc = %d, off = %d, line %d\n", rc, off, __LINE__);
  929. switch(rc) {
  930. case 0:
  931. errno = EHOSTDOWN;
  932. case -1:
  933. if (errno == EAGAIN) {
  934. return 0;
  935. }
  936. return -1;
  937. default:
  938. buff->curr_offset += rc;
  939. }
  940. off = buff->curr_offset;
  941. if (buff->curr_offset == sizeof(buff->len)) {
  942. buff->len = ntohl(buff->len);
  943. buff->buffer = calloc(1, buff->len);
  944. }
  945. }
  946. if (buff->buffer) {
  947. /* want off to now represent the offset into the buffer */
  948. off -= sizeof(buff->len);
  949. rc = recv(fd, buff->buffer+off, buff->len-off, 0);
  950. switch(rc) {
  951. case 0:
  952. errno = EHOSTDOWN;
  953. case -1:
  954. if (errno == EAGAIN) {
  955. break;
  956. }
  957. return -1;
  958. default:
  959. buff->curr_offset += rc;
  960. }
  961. }
  962. return buff->curr_offset == buff->len + sizeof(buff->len);
  963. }
  964. void free_buffers(buffer_head_t *list)
  965. {
  966. while (remove_buffer(list))
  967. ;
  968. }
  969. void free_completions(zhandle_t *zh,int callCompletion,int reason)
  970. {
  971. completion_head_t tmp_list;
  972. struct oarchive *oa;
  973. struct ReplyHeader h;
  974. void_completion_t auth_completion = NULL;
  975. auth_completion_list_t a_list, *a_tmp;
  976. lock_completion_list(&zh->sent_requests);
  977. tmp_list = zh->sent_requests;
  978. zh->sent_requests.head = 0;
  979. zh->sent_requests.last = 0;
  980. unlock_completion_list(&zh->sent_requests);
  981. while (tmp_list.head) {
  982. completion_list_t *cptr = tmp_list.head;
  983. tmp_list.head = cptr->next;
  984. if (cptr->c.data_result == SYNCHRONOUS_MARKER) {
  985. struct sync_completion
  986. *sc = (struct sync_completion*)cptr->data;
  987. sc->rc = reason;
  988. notify_sync_completion(sc);
  989. zh->outstanding_sync--;
  990. destroy_completion_entry(cptr);
  991. } else if (callCompletion) {
  992. if(cptr->xid == PING_XID){
  993. // Nothing to do with a ping response
  994. destroy_completion_entry(cptr);
  995. } else {
  996. // Fake the response
  997. buffer_list_t *bptr;
  998. h.xid = cptr->xid;
  999. h.zxid = -1;
  1000. h.err = reason;
  1001. oa = create_buffer_oarchive();
  1002. serialize_ReplyHeader(oa, "header", &h);
  1003. bptr = calloc(sizeof(*bptr), 1);
  1004. assert(bptr);
  1005. bptr->len = get_buffer_len(oa);
  1006. bptr->buffer = get_buffer(oa);
  1007. close_buffer_oarchive(&oa, 0);
  1008. cptr->buffer = bptr;
  1009. queue_completion(&zh->completions_to_process, cptr, 0);
  1010. }
  1011. }
  1012. }
  1013. a_list.completion = NULL;
  1014. a_list.next = NULL;
  1015. zoo_lock_auth(zh);
  1016. get_auth_completions(&zh->auth_h, &a_list);
  1017. zoo_unlock_auth(zh);
  1018. a_tmp = &a_list;
  1019. // chain call user's completion function
  1020. while (a_tmp->completion != NULL) {
  1021. auth_completion = a_tmp->completion;
  1022. auth_completion(reason, a_tmp->auth_data);
  1023. a_tmp = a_tmp->next;
  1024. if (a_tmp == NULL)
  1025. break;
  1026. }
  1027. free_auth_completion(&a_list);
  1028. }
  1029. static void cleanup_bufs(zhandle_t *zh,int callCompletion,int rc)
  1030. {
  1031. enter_critical(zh);
  1032. free_buffers(&zh->to_send);
  1033. free_buffers(&zh->to_process);
  1034. free_completions(zh,callCompletion,rc);
  1035. leave_critical(zh);
  1036. if (zh->input_buffer && zh->input_buffer != &zh->primer_buffer) {
  1037. free_buffer(zh->input_buffer);
  1038. zh->input_buffer = 0;
  1039. }
  1040. }
  1041. static void handle_error(zhandle_t *zh,int rc)
  1042. {
  1043. close(zh->fd);
  1044. if (is_unrecoverable(zh)) {
  1045. LOG_DEBUG(("Calling a watcher for a ZOO_SESSION_EVENT and the state=%s",
  1046. state2String(zh->state)));
  1047. PROCESS_SESSION_EVENT(zh, zh->state);
  1048. } else if (zh->state == ZOO_CONNECTED_STATE) {
  1049. LOG_DEBUG(("Calling a watcher for a ZOO_SESSION_EVENT and the state=CONNECTING_STATE"));
  1050. PROCESS_SESSION_EVENT(zh, ZOO_CONNECTING_STATE);
  1051. }
  1052. cleanup_bufs(zh,1,rc);
  1053. zh->fd = -1;
  1054. zh->connect_index++;
  1055. if (!is_unrecoverable(zh)) {
  1056. zh->state = 0;
  1057. }
  1058. if (process_async(zh->outstanding_sync)) {
  1059. process_completions(zh);
  1060. }
  1061. }
  1062. static int handle_socket_error_msg(zhandle_t *zh, int line, int rc,
  1063. const char* format, ...)
  1064. {
  1065. if(logLevel>=ZOO_LOG_LEVEL_ERROR){
  1066. va_list va;
  1067. char buf[1024];
  1068. va_start(va,format);
  1069. vsnprintf(buf, sizeof(buf)-1,format,va);
  1070. log_message(ZOO_LOG_LEVEL_ERROR,line,__func__,
  1071. format_log_message("Socket [%s] zk retcode=%d, errno=%d(%s): %s",
  1072. format_current_endpoint_info(zh),rc,errno,strerror(errno),buf));
  1073. va_end(va);
  1074. }
  1075. handle_error(zh,rc);
  1076. return rc;
  1077. }
  1078. static void auth_completion_func(int rc, zhandle_t* zh)
  1079. {
  1080. void_completion_t auth_completion = NULL;
  1081. auth_completion_list_t a_list;
  1082. auth_completion_list_t *a_tmp;
  1083. if(zh==NULL)
  1084. return;
  1085. zoo_lock_auth(zh);
  1086. if(rc!=0){
  1087. zh->state=ZOO_AUTH_FAILED_STATE;
  1088. }else{
  1089. //change state for all auths
  1090. mark_active_auth(zh);
  1091. }
  1092. a_list.completion = NULL;
  1093. a_list.next = NULL;
  1094. get_auth_completions(&zh->auth_h, &a_list);
  1095. zoo_unlock_auth(zh);
  1096. if (rc) {
  1097. LOG_ERROR(("Authentication scheme %s failed. Connection closed.",
  1098. zh->auth_h.auth->scheme));
  1099. }
  1100. else {
  1101. LOG_INFO(("Authentication scheme %s succeeded", zh->auth_h.auth->scheme));
  1102. }
  1103. a_tmp = &a_list;
  1104. // chain call user's completion function
  1105. while (a_tmp->completion != NULL) {
  1106. auth_completion = a_tmp->completion;
  1107. auth_completion(rc, a_tmp->auth_data);
  1108. a_tmp = a_tmp->next;
  1109. if (a_tmp == NULL)
  1110. break;
  1111. }
  1112. free_auth_completion(&a_list);
  1113. }
  1114. static int send_info_packet(zhandle_t *zh, auth_info* auth) {
  1115. struct oarchive *oa;
  1116. struct RequestHeader h = { .xid = AUTH_XID, .type = SETAUTH_OP};
  1117. struct AuthPacket req;
  1118. int rc;
  1119. oa = create_buffer_oarchive();
  1120. rc = serialize_RequestHeader(oa, "header", &h);
  1121. req.type=0; // ignored by the server
  1122. req.scheme = auth->scheme;
  1123. req.auth = auth->auth;
  1124. rc = rc < 0 ? rc : serialize_AuthPacket(oa, "req", &req);
  1125. /* add this buffer to the head of the send queue */
  1126. rc = rc < 0 ? rc : queue_front_buffer_bytes(&zh->to_send, get_buffer(oa),
  1127. get_buffer_len(oa));
  1128. /* We queued the buffer, so don't free it */
  1129. close_buffer_oarchive(&oa, 0);
  1130. return rc;
  1131. }
  1132. /** send all auths, not just the last one **/
  1133. static int send_auth_info(zhandle_t *zh) {
  1134. int rc = 0;
  1135. auth_info *auth = NULL;
  1136. zoo_lock_auth(zh);
  1137. auth = zh->auth_h.auth;
  1138. if (auth == NULL) {
  1139. zoo_unlock_auth(zh);
  1140. return ZOK;
  1141. }
  1142. while (auth->next != NULL) {
  1143. rc = send_info_packet(zh, auth);
  1144. auth = auth->next;
  1145. }
  1146. zoo_unlock_auth(zh);
  1147. LOG_DEBUG(("Sending all auth info request to %s", format_current_endpoint_info(zh)));
  1148. return (rc <0) ? ZMARSHALLINGERROR:ZOK;
  1149. }
  1150. static int send_last_auth_info(zhandle_t *zh)
  1151. {
  1152. int rc = 0;
  1153. auth_info *auth = NULL;
  1154. zoo_lock_auth(zh);
  1155. auth = get_last_auth(&zh->auth_h);
  1156. if(auth==NULL) {
  1157. zoo_unlock_auth(zh);
  1158. return ZOK; // there is nothing to send
  1159. }
  1160. rc = send_info_packet(zh, auth);
  1161. zoo_unlock_auth(zh);
  1162. LOG_DEBUG(("Sending auth info request to %s",format_current_endpoint_info(zh)));
  1163. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  1164. }
  1165. static void free_key_list(char **list, int count)
  1166. {
  1167. int i;
  1168. for(i = 0; i < count; i++) {
  1169. free(list[i]);
  1170. }
  1171. free(list);
  1172. }
  1173. static int send_set_watches(zhandle_t *zh)
  1174. {
  1175. struct oarchive *oa;
  1176. struct RequestHeader h = { .xid = SET_WATCHES_XID, .type = SETWATCHES_OP};
  1177. struct SetWatches req;
  1178. int rc;
  1179. req.relativeZxid = zh->last_zxid;
  1180. req.dataWatches.data = collect_keys(zh->active_node_watchers, (int*)&req.dataWatches.count);
  1181. req.existWatches.data = collect_keys(zh->active_exist_watchers, (int*)&req.existWatches.count);
  1182. req.childWatches.data = collect_keys(zh->active_child_watchers, (int*)&req.childWatches.count);
  1183. // return if there are no pending watches
  1184. if (!req.dataWatches.count && !req.existWatches.count &&
  1185. !req.childWatches.count) {
  1186. free_key_list(req.dataWatches.data, req.dataWatches.count);
  1187. free_key_list(req.existWatches.data, req.existWatches.count);
  1188. free_key_list(req.childWatches.data, req.childWatches.count);
  1189. return ZOK;
  1190. }
  1191. oa = create_buffer_oarchive();
  1192. rc = serialize_RequestHeader(oa, "header", &h);
  1193. rc = rc < 0 ? rc : serialize_SetWatches(oa, "req", &req);
  1194. /* add this buffer to the head of the send queue */
  1195. rc = rc < 0 ? rc : queue_front_buffer_bytes(&zh->to_send, get_buffer(oa),
  1196. get_buffer_len(oa));
  1197. /* We queued the buffer, so don't free it */
  1198. close_buffer_oarchive(&oa, 0);
  1199. free_key_list(req.dataWatches.data, req.dataWatches.count);
  1200. free_key_list(req.existWatches.data, req.existWatches.count);
  1201. free_key_list(req.childWatches.data, req.childWatches.count);
  1202. LOG_DEBUG(("Sending set watches request to %s",format_current_endpoint_info(zh)));
  1203. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  1204. }
  1205. static int serialize_prime_connect(struct connect_req *req, char* buffer){
  1206. //this should be the order of serialization
  1207. int offset = 0;
  1208. req->protocolVersion = htonl(req->protocolVersion);
  1209. memcpy(buffer + offset, &req->protocolVersion, sizeof(req->protocolVersion));
  1210. offset = offset + sizeof(req->protocolVersion);
  1211. req->lastZxidSeen = htonll(req->lastZxidSeen);
  1212. memcpy(buffer + offset, &req->lastZxidSeen, sizeof(req->lastZxidSeen));
  1213. offset = offset + sizeof(req->lastZxidSeen);
  1214. req->timeOut = htonl(req->timeOut);
  1215. memcpy(buffer + offset, &req->timeOut, sizeof(req->timeOut));
  1216. offset = offset + sizeof(req->timeOut);
  1217. req->sessionId = htonll(req->sessionId);
  1218. memcpy(buffer + offset, &req->sessionId, sizeof(req->sessionId));
  1219. offset = offset + sizeof(req->sessionId);
  1220. req->passwd_len = htonl(req->passwd_len);
  1221. memcpy(buffer + offset, &req->passwd_len, sizeof(req->passwd_len));
  1222. offset = offset + sizeof(req->passwd_len);
  1223. memcpy(buffer + offset, req->passwd, sizeof(req->passwd));
  1224. return 0;
  1225. }
  1226. static int deserialize_prime_response(struct prime_struct *req, char* buffer){
  1227. //this should be the order of deserialization
  1228. int offset = 0;
  1229. memcpy(&req->len, buffer + offset, sizeof(req->len));
  1230. offset = offset + sizeof(req->len);
  1231. req->len = ntohl(req->len);
  1232. memcpy(&req->protocolVersion, buffer + offset, sizeof(req->protocolVersion));
  1233. offset = offset + sizeof(req->protocolVersion);
  1234. req->protocolVersion = ntohl(req->protocolVersion);
  1235. memcpy(&req->timeOut, buffer + offset, sizeof(req->timeOut));
  1236. offset = offset + sizeof(req->timeOut);
  1237. req->timeOut = ntohl(req->timeOut);
  1238. memcpy(&req->sessionId, buffer + offset, sizeof(req->sessionId));
  1239. offset = offset + sizeof(req->sessionId);
  1240. req->sessionId = htonll(req->sessionId);
  1241. memcpy(&req->passwd_len, buffer + offset, sizeof(req->passwd_len));
  1242. offset = offset + sizeof(req->passwd_len);
  1243. req->passwd_len = ntohl(req->passwd_len);
  1244. memcpy(req->passwd, buffer + offset, sizeof(req->passwd));
  1245. return 0;
  1246. }
  1247. static int prime_connection(zhandle_t *zh)
  1248. {
  1249. int rc;
  1250. /*this is the size of buffer to serialize req into*/
  1251. char buffer_req[HANDSHAKE_REQ_SIZE];
  1252. int len = sizeof(buffer_req);
  1253. int hlen = 0;
  1254. struct connect_req req;
  1255. req.protocolVersion = 0;
  1256. req.sessionId = zh->client_id.client_id;
  1257. req.passwd_len = sizeof(req.passwd);
  1258. memcpy(req.passwd, zh->client_id.passwd, sizeof(zh->client_id.passwd));
  1259. req.timeOut = zh->recv_timeout;
  1260. req.lastZxidSeen = zh->last_zxid;
  1261. hlen = htonl(len);
  1262. /* We are running fast and loose here, but this string should fit in the initial buffer! */
  1263. rc=send(zh->fd, &hlen, sizeof(len), 0);
  1264. serialize_prime_connect(&req, buffer_req);
  1265. rc=rc<0 ? rc : send(zh->fd, buffer_req, len, 0);
  1266. if (rc<0) {
  1267. return handle_socket_error_msg(zh, __LINE__, ZCONNECTIONLOSS,
  1268. "failed to send a handshake packet: %s", strerror(errno));
  1269. }
  1270. zh->state = ZOO_ASSOCIATING_STATE;
  1271. zh->input_buffer = &zh->primer_buffer;
  1272. /* This seems a bit weird to to set the offset to 4, but we already have a
  1273. * length, so we skip reading the length (and allocating the buffer) by
  1274. * saying that we are already at offset 4 */
  1275. zh->input_buffer->curr_offset = 4;
  1276. return ZOK;
  1277. }
  1278. static inline int calculate_interval(const struct timeval *start,
  1279. const struct timeval *end)
  1280. {
  1281. int interval;
  1282. struct timeval i = *end;
  1283. i.tv_sec -= start->tv_sec;
  1284. i.tv_usec -= start->tv_usec;
  1285. interval = i.tv_sec * 1000 + (i.tv_usec/1000);
  1286. return interval;
  1287. }
  1288. static struct timeval get_timeval(int interval)
  1289. {
  1290. struct timeval tv;
  1291. if (interval < 0) {
  1292. interval = 0;
  1293. }
  1294. tv.tv_sec = interval/1000;
  1295. tv.tv_usec = (interval%1000)*1000;
  1296. return tv;
  1297. }
  1298. static int add_void_completion(zhandle_t *zh, int xid, void_completion_t dc,
  1299. const void *data);
  1300. static int add_string_completion(zhandle_t *zh, int xid,
  1301. string_completion_t dc, const void *data);
  1302. int send_ping(zhandle_t* zh)
  1303. {
  1304. int rc;
  1305. struct oarchive *oa = create_buffer_oarchive();
  1306. struct RequestHeader h = { .xid = PING_XID, .type = PING_OP };
  1307. rc = serialize_RequestHeader(oa, "header", &h);
  1308. enter_critical(zh);
  1309. gettimeofday(&zh->last_ping, 0);
  1310. rc = rc < 0 ? rc : add_void_completion(zh, h.xid, 0, 0);
  1311. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  1312. get_buffer_len(oa));
  1313. leave_critical(zh);
  1314. close_buffer_oarchive(&oa, 0);
  1315. return rc<0 ? rc : adaptor_send_queue(zh, 0);
  1316. }
  1317. int zookeeper_interest(zhandle_t *zh, int *fd, int *interest,
  1318. struct timeval *tv)
  1319. {
  1320. struct timeval now;
  1321. if(zh==0 || fd==0 ||interest==0 || tv==0)
  1322. return ZBADARGUMENTS;
  1323. if (is_unrecoverable(zh))
  1324. return ZINVALIDSTATE;
  1325. gettimeofday(&now, 0);
  1326. if(zh->next_deadline.tv_sec!=0 || zh->next_deadline.tv_usec!=0){
  1327. int time_left = calculate_interval(&zh->next_deadline, &now);
  1328. if (time_left > 10)
  1329. LOG_WARN(("Exceeded deadline by %dms", time_left));
  1330. }
  1331. api_prolog(zh);
  1332. *fd = zh->fd;
  1333. *interest = 0;
  1334. tv->tv_sec = 0;
  1335. tv->tv_usec = 0;
  1336. if (*fd == -1) {
  1337. if (zh->connect_index == zh->addrs_count) {
  1338. /* Wait a bit before trying again so that we don't spin */
  1339. zh->connect_index = 0;
  1340. }else {
  1341. int rc;
  1342. int on = 1;
  1343. zh->fd = socket(zh->addrs[zh->connect_index].ss_family, SOCK_STREAM, 0);
  1344. if (zh->fd < 0) {
  1345. return api_epilog(zh,handle_socket_error_msg(zh,__LINE__,
  1346. ZSYSTEMERROR, "socket() call failed"));
  1347. }
  1348. setsockopt(zh->fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(int));
  1349. fcntl(zh->fd, F_SETFL, O_NONBLOCK|fcntl(zh->fd, F_GETFL, 0));
  1350. #if defined(AF_INET6)
  1351. if (zh->addrs[zh->connect_index].ss_family == AF_INET6) {
  1352. rc = connect(zh->fd, (struct sockaddr*) &zh->addrs[zh->connect_index], sizeof(struct sockaddr_in6));
  1353. } else {
  1354. #else
  1355. {
  1356. #endif
  1357. rc = connect(zh->fd, (struct sockaddr*) &zh->addrs[zh->connect_index], sizeof(struct sockaddr_in));
  1358. }
  1359. if (rc == -1) {
  1360. /* we are handling the non-blocking connect according to
  1361. * the description in section 16.3 "Non-blocking connect"
  1362. * in UNIX Network Programming vol 1, 3rd edition */
  1363. if (errno == EWOULDBLOCK || errno == EINPROGRESS)
  1364. zh->state = ZOO_CONNECTING_STATE;
  1365. else
  1366. return api_epilog(zh,handle_socket_error_msg(zh,__LINE__,
  1367. ZCONNECTIONLOSS,"connect() call failed"));
  1368. } else {
  1369. if((rc=prime_connection(zh))!=0)
  1370. return api_epilog(zh,rc);
  1371. LOG_INFO(("Initiated connection to server [%s]",
  1372. format_endpoint_info(&zh->addrs[zh->connect_index])));
  1373. }
  1374. }
  1375. *fd = zh->fd;
  1376. *tv = get_timeval(zh->recv_timeout/3);
  1377. zh->last_recv = now;
  1378. zh->last_send = now;
  1379. zh->last_ping = now;
  1380. }
  1381. if (zh->fd != -1) {
  1382. int idle_recv = calculate_interval(&zh->last_recv, &now);
  1383. int idle_send = calculate_interval(&zh->last_send, &now);
  1384. int recv_to = zh->recv_timeout*2/3 - idle_recv;
  1385. int send_to = zh->recv_timeout/3;
  1386. // have we exceeded the receive timeout threshold?
  1387. if (recv_to <= 0) {
  1388. // We gotta cut our losses and connect to someone else
  1389. errno = ETIMEDOUT;
  1390. *fd=-1;
  1391. *interest=0;
  1392. *tv = get_timeval(0);
  1393. return api_epilog(zh,handle_socket_error_msg(zh,
  1394. __LINE__,ZOPERATIONTIMEOUT,
  1395. "connection timed out (exceeded timeout by %dms)",-recv_to));
  1396. }
  1397. // We only allow 1/3 of our timeout time to expire before sending
  1398. // a PING
  1399. if (zh->state==ZOO_CONNECTED_STATE) {
  1400. send_to = zh->recv_timeout/3 - idle_send;
  1401. if (send_to <= 0 && zh->sent_requests.head==0) {
  1402. // LOG_DEBUG(("Sending PING to %s (exceeded idle by %dms)",
  1403. // format_current_endpoint_info(zh),-send_to));
  1404. int rc=send_ping(zh);
  1405. if (rc < 0){
  1406. LOG_ERROR(("failed to send PING request (zk retcode=%d)",rc));
  1407. return api_epilog(zh,rc);
  1408. }
  1409. send_to = zh->recv_timeout/3;
  1410. }
  1411. }
  1412. // choose the lesser value as the timeout
  1413. *tv = get_timeval(recv_to < send_to? recv_to:send_to);
  1414. zh->next_deadline.tv_sec = now.tv_sec + tv->tv_sec;
  1415. zh->next_deadline.tv_usec = now.tv_usec + tv->tv_usec;
  1416. if (zh->next_deadline.tv_usec > 1000000) {
  1417. zh->next_deadline.tv_sec += zh->next_deadline.tv_usec / 1000000;
  1418. zh->next_deadline.tv_usec = zh->next_deadline.tv_usec % 1000000;
  1419. }
  1420. *interest = ZOOKEEPER_READ;
  1421. /* we are interested in a write if we are connected and have something
  1422. * to send, or we are waiting for a connect to finish. */
  1423. if ((zh->to_send.head && (zh->state == ZOO_CONNECTED_STATE))
  1424. || zh->state == ZOO_CONNECTING_STATE) {
  1425. *interest |= ZOOKEEPER_WRITE;
  1426. }
  1427. }
  1428. return api_epilog(zh,ZOK);
  1429. }
  1430. static int check_events(zhandle_t *zh, int events)
  1431. {
  1432. if (zh->fd == -1)
  1433. return ZINVALIDSTATE;
  1434. if ((events&ZOOKEEPER_WRITE)&&(zh->state == ZOO_CONNECTING_STATE)) {
  1435. int rc, error;
  1436. socklen_t len = sizeof(error);
  1437. rc = getsockopt(zh->fd, SOL_SOCKET, SO_ERROR, &error, &len);
  1438. /* the description in section 16.4 "Non-blocking connect"
  1439. * in UNIX Network Programming vol 1, 3rd edition, points out
  1440. * that sometimes the error is in errno and sometimes in error */
  1441. if (rc < 0 || error) {
  1442. if (rc == 0)
  1443. errno = error;
  1444. return handle_socket_error_msg(zh, __LINE__,ZCONNECTIONLOSS,
  1445. "server refused to accept the client");
  1446. }
  1447. if((rc=prime_connection(zh))!=0)
  1448. return rc;
  1449. LOG_INFO(("initiated connection to server [%s]",
  1450. format_endpoint_info(&zh->addrs[zh->connect_index])));
  1451. return ZOK;
  1452. }
  1453. if (zh->to_send.head && (events&ZOOKEEPER_WRITE)) {
  1454. /* make the flush call non-blocking by specifying a 0 timeout */
  1455. int rc=flush_send_queue(zh,0);
  1456. if (rc < 0)
  1457. return handle_socket_error_msg(zh,__LINE__,ZCONNECTIONLOSS,
  1458. "failed while flushing send queue");
  1459. }
  1460. if (events&ZOOKEEPER_READ) {
  1461. int rc;
  1462. if (zh->input_buffer == 0) {
  1463. zh->input_buffer = allocate_buffer(0,0);
  1464. }
  1465. rc = recv_buffer(zh->fd, zh->input_buffer);
  1466. if (rc < 0) {
  1467. return handle_socket_error_msg(zh, __LINE__,ZCONNECTIONLOSS,
  1468. "failed while receiving a server response");
  1469. }
  1470. if (rc > 0) {
  1471. gettimeofday(&zh->last_recv, 0);
  1472. if (zh->input_buffer != &zh->primer_buffer) {
  1473. queue_buffer(&zh->to_process, zh->input_buffer, 0);
  1474. } else {
  1475. int64_t oldid,newid;
  1476. //deserialize
  1477. deserialize_prime_response(&zh->primer_storage, zh->primer_buffer.buffer);
  1478. /* We are processing the primer_buffer, so we need to finish
  1479. * the connection handshake */
  1480. oldid = zh->client_id.client_id;
  1481. newid = zh->primer_storage.sessionId;
  1482. if (oldid != 0 && oldid != newid) {
  1483. zh->state = ZOO_EXPIRED_SESSION_STATE;
  1484. errno = ESTALE;
  1485. return handle_socket_error_msg(zh,__LINE__,ZSESSIONEXPIRED,
  1486. "sessionId=%#llx has expired.",oldid);
  1487. } else {
  1488. zh->recv_timeout = zh->primer_storage.timeOut;
  1489. zh->client_id.client_id = newid;
  1490. memcpy(zh->client_id.passwd, &zh->primer_storage.passwd,
  1491. sizeof(zh->client_id.passwd));
  1492. zh->state = ZOO_CONNECTED_STATE;
  1493. LOG_INFO(("session establishment complete on server [%s], sessionId=%#llx, negotiated timeout=%d",
  1494. format_endpoint_info(&zh->addrs[zh->connect_index]),
  1495. newid, zh->recv_timeout));
  1496. /* we want the auth to be sent for, but since both call push to front
  1497. we need to call send_watch_set first */
  1498. send_set_watches(zh);
  1499. /* send the authentication packet now */
  1500. send_auth_info(zh);
  1501. LOG_DEBUG(("Calling a watcher for a ZOO_SESSION_EVENT and the state=ZOO_CONNECTED_STATE"));
  1502. zh->input_buffer = 0; // just in case the watcher calls zookeeper_process() again
  1503. PROCESS_SESSION_EVENT(zh, ZOO_CONNECTED_STATE);
  1504. }
  1505. }
  1506. zh->input_buffer = 0;
  1507. } else {
  1508. // zookeeper_process was called but there was nothing to read
  1509. // from the socket
  1510. return ZNOTHING;
  1511. }
  1512. }
  1513. return ZOK;
  1514. }
  1515. void api_prolog(zhandle_t* zh)
  1516. {
  1517. inc_ref_counter(zh,1);
  1518. }
  1519. int api_epilog(zhandle_t *zh,int rc)
  1520. {
  1521. if(inc_ref_counter(zh,-1)==0 && zh->close_requested!=0)
  1522. zookeeper_close(zh);
  1523. return rc;
  1524. }
  1525. static __attribute__((unused)) void print_completion_queue(zhandle_t *zh)
  1526. {
  1527. completion_list_t* cptr;
  1528. if(logLevel<ZOO_LOG_LEVEL_DEBUG) return;
  1529. fprintf(LOGSTREAM,"Completion queue: ");
  1530. if (zh->sent_requests.head==0) {
  1531. fprintf(LOGSTREAM,"empty\n");
  1532. return;
  1533. }
  1534. cptr=zh->sent_requests.head;
  1535. while(cptr){
  1536. fprintf(LOGSTREAM,"%d,",cptr->xid);
  1537. cptr=cptr->next;
  1538. }
  1539. fprintf(LOGSTREAM,"end\n");
  1540. }
  1541. //#ifdef THREADED
  1542. // IO thread queues session events to be processed by the completion thread
  1543. static int queue_session_event(zhandle_t *zh, int state)
  1544. {
  1545. int rc;
  1546. struct WatcherEvent evt = { ZOO_SESSION_EVENT, state, "" };
  1547. struct ReplyHeader hdr = { WATCHER_EVENT_XID, 0, 0 };
  1548. struct oarchive *oa;
  1549. completion_list_t *cptr;
  1550. if ((oa=create_buffer_oarchive())==NULL) {
  1551. LOG_ERROR(("out of memory"));
  1552. goto error;
  1553. }
  1554. rc = serialize_ReplyHeader(oa, "hdr", &hdr);
  1555. rc = rc<0?rc: serialize_WatcherEvent(oa, "event", &evt);
  1556. if(rc<0){
  1557. close_buffer_oarchive(&oa, 1);
  1558. goto error;
  1559. }
  1560. cptr = create_completion_entry(WATCHER_EVENT_XID,-1,0,0,0);
  1561. cptr->buffer = allocate_buffer(get_buffer(oa), get_buffer_len(oa));
  1562. cptr->buffer->curr_offset = get_buffer_len(oa);
  1563. if (!cptr->buffer) {
  1564. free(cptr);
  1565. close_buffer_oarchive(&oa, 1);
  1566. goto error;
  1567. }
  1568. /* We queued the buffer, so don't free it */
  1569. close_buffer_oarchive(&oa, 0);
  1570. cptr->c.watcher_result = collectWatchers(zh, ZOO_SESSION_EVENT, "");
  1571. queue_completion(&zh->completions_to_process, cptr, 0);
  1572. if (process_async(zh->outstanding_sync)) {
  1573. process_completions(zh);
  1574. }
  1575. return ZOK;
  1576. error:
  1577. errno=ENOMEM;
  1578. return ZSYSTEMERROR;
  1579. }
  1580. //#endif
  1581. completion_list_t *dequeue_completion(completion_head_t *list)
  1582. {
  1583. completion_list_t *cptr;
  1584. lock_completion_list(list);
  1585. cptr = list->head;
  1586. if (cptr) {
  1587. list->head = cptr->next;
  1588. if (!list->head) {
  1589. assert(list->last == cptr);
  1590. list->last = 0;
  1591. }
  1592. }
  1593. unlock_completion_list(list);
  1594. return cptr;
  1595. }
  1596. /* handles async completion (both single- and multithreaded) */
  1597. void process_completions(zhandle_t *zh)
  1598. {
  1599. completion_list_t *cptr;
  1600. while ((cptr = dequeue_completion(&zh->completions_to_process)) != 0) {
  1601. struct ReplyHeader hdr;
  1602. buffer_list_t *bptr = cptr->buffer;
  1603. struct iarchive *ia = create_buffer_iarchive(bptr->buffer,
  1604. bptr->len);
  1605. deserialize_ReplyHeader(ia, "hdr", &hdr);
  1606. if (hdr.xid == WATCHER_EVENT_XID) {
  1607. int type, state;
  1608. struct WatcherEvent evt;
  1609. deserialize_WatcherEvent(ia, "event", &evt);
  1610. /* We are doing a notification, so there is no pending request */
  1611. type = evt.type;
  1612. state = evt.state;
  1613. /* This is a notification so there aren't any pending requests */
  1614. LOG_DEBUG(("Calling a watcher for node [%s], type = %d event=%s",
  1615. (evt.path==NULL?"NULL":evt.path), cptr->completion_type,
  1616. watcherEvent2String(type)));
  1617. deliverWatchers(zh,type,state,evt.path, &cptr->c.watcher_result);
  1618. deallocate_WatcherEvent(&evt);
  1619. } else {
  1620. int rc = hdr.err;
  1621. switch (cptr->completion_type) {
  1622. case COMPLETION_DATA:
  1623. LOG_DEBUG(("Calling COMPLETION_DATA for xid=%#x rc=%d",cptr->xid,rc));
  1624. if (rc) {
  1625. cptr->c.data_result(rc, 0, 0, 0, cptr->data);
  1626. } else {
  1627. struct GetDataResponse res;
  1628. deserialize_GetDataResponse(ia, "reply", &res);
  1629. cptr->c.data_result(rc, res.data.buff, res.data.len,
  1630. &res.stat, cptr->data);
  1631. deallocate_GetDataResponse(&res);
  1632. }
  1633. break;
  1634. case COMPLETION_STAT:
  1635. LOG_DEBUG(("Calling COMPLETION_STAT for xid=%#x rc=%d",cptr->xid,rc));
  1636. if (rc) {
  1637. cptr->c.stat_result(rc, 0, cptr->data);
  1638. } else {
  1639. struct SetDataResponse res;
  1640. deserialize_SetDataResponse(ia, "reply", &res);
  1641. cptr->c.stat_result(rc, &res.stat, cptr->data);
  1642. deallocate_SetDataResponse(&res);
  1643. }
  1644. break;
  1645. case COMPLETION_STRINGLIST:
  1646. LOG_DEBUG(("Calling COMPLETION_STRINGLIST for xid=%#x rc=%d",cptr->xid,rc));
  1647. if (rc) {
  1648. cptr->c.strings_result(rc, 0, cptr->data);
  1649. } else {
  1650. struct GetChildrenResponse res;
  1651. deserialize_GetChildrenResponse(ia, "reply", &res);
  1652. cptr->c.strings_result(rc, &res.children, cptr->data);
  1653. deallocate_GetChildrenResponse(&res);
  1654. }
  1655. break;
  1656. case COMPLETION_STRINGLIST_STAT:
  1657. LOG_DEBUG(("Calling COMPLETION_STRINGLIST_STAT for xid=%#x rc=%d",cptr->xid,rc));
  1658. if (rc) {
  1659. cptr->c.strings_stat_result(rc, 0, 0, cptr->data);
  1660. } else {
  1661. struct GetChildren2Response res;
  1662. deserialize_GetChildren2Response(ia, "reply", &res);
  1663. cptr->c.strings_stat_result(rc, &res.children, &res.stat, cptr->data);
  1664. deallocate_GetChildren2Response(&res);
  1665. }
  1666. break;
  1667. case COMPLETION_STRING:
  1668. LOG_DEBUG(("Calling COMPLETION_STRING for xid=%#x rc=%d",cptr->xid,rc));
  1669. if (rc) {
  1670. cptr->c.string_result(rc, 0, cptr->data);
  1671. } else {
  1672. struct CreateResponse res;
  1673. deserialize_CreateResponse(ia, "reply", &res);
  1674. cptr->c.string_result(rc, res.path, cptr->data);
  1675. deallocate_CreateResponse(&res);
  1676. }
  1677. break;
  1678. case COMPLETION_ACLLIST:
  1679. LOG_DEBUG(("Calling COMPLETION_ACLLIST for xid=%#x rc=%d",cptr->xid,rc));
  1680. if (rc) {
  1681. cptr->c.acl_result(rc, 0, 0, cptr->data);
  1682. } else {
  1683. struct GetACLResponse res;
  1684. deserialize_GetACLResponse(ia, "reply", &res);
  1685. cptr->c.acl_result(rc, &res.acl, &res.stat, cptr->data);
  1686. deallocate_GetACLResponse(&res);
  1687. }
  1688. break;
  1689. case COMPLETION_VOID:
  1690. LOG_DEBUG(("Calling COMPLETION_VOID for xid=%#x rc=%d",cptr->xid,rc));
  1691. if (hdr.xid == PING_XID) {
  1692. // We want to skip the ping
  1693. } else {
  1694. cptr->c.void_result(rc, cptr->data);
  1695. }
  1696. break;
  1697. }
  1698. }
  1699. destroy_completion_entry(cptr);
  1700. close_buffer_iarchive(&ia);
  1701. }
  1702. }
  1703. static void isSocketReadable(zhandle_t* zh)
  1704. {
  1705. struct pollfd fds;
  1706. fds.fd = zh->fd;
  1707. fds.events = POLLIN;
  1708. if (poll(&fds,1,0)<=0) {
  1709. // socket not readable -- no more responses to process
  1710. zh->socket_readable.tv_sec=zh->socket_readable.tv_usec=0;
  1711. }else{
  1712. gettimeofday(&zh->socket_readable,0);
  1713. }
  1714. }
  1715. static void checkResponseLatency(zhandle_t* zh)
  1716. {
  1717. int delay;
  1718. struct timeval now;
  1719. if(zh->socket_readable.tv_sec==0)
  1720. return;
  1721. gettimeofday(&now,0);
  1722. delay=calculate_interval(&zh->socket_readable, &now);
  1723. if(delay>20)
  1724. LOG_DEBUG(("The following server response has spent at least %dms sitting in the client socket recv buffer",delay));
  1725. zh->socket_readable.tv_sec=zh->socket_readable.tv_usec=0;
  1726. }
  1727. int zookeeper_process(zhandle_t *zh, int events)
  1728. {
  1729. buffer_list_t *bptr;
  1730. int rc;
  1731. if (zh==NULL)
  1732. return ZBADARGUMENTS;
  1733. if (is_unrecoverable(zh))
  1734. return ZINVALIDSTATE;
  1735. api_prolog(zh);
  1736. IF_DEBUG(checkResponseLatency(zh));
  1737. rc = check_events(zh, events);
  1738. if (rc!=ZOK)
  1739. return api_epilog(zh, rc);
  1740. IF_DEBUG(isSocketReadable(zh));
  1741. while (rc >= 0 && (bptr=dequeue_buffer(&zh->to_process))) {
  1742. struct ReplyHeader hdr;
  1743. struct iarchive *ia = create_buffer_iarchive(
  1744. bptr->buffer, bptr->curr_offset);
  1745. deserialize_ReplyHeader(ia, "hdr", &hdr);
  1746. if (hdr.zxid > 0) {
  1747. zh->last_zxid = hdr.zxid;
  1748. } else {
  1749. // fprintf(stderr, "Got %#x for %#x\n", hdr.zxid, hdr.xid);
  1750. }
  1751. if (hdr.xid == WATCHER_EVENT_XID) {
  1752. struct WatcherEvent evt;
  1753. int type = 0;
  1754. char *path = NULL;
  1755. completion_list_t *c = NULL;
  1756. LOG_DEBUG(("Processing WATCHER_EVENT"));
  1757. deserialize_WatcherEvent(ia, "event", &evt);
  1758. type = evt.type;
  1759. path = evt.path;
  1760. /* We are doing a notification, so there is no pending request */
  1761. c = create_completion_entry(WATCHER_EVENT_XID,-1,0,0,0);
  1762. c->buffer = bptr;
  1763. c->c.watcher_result = collectWatchers(zh, type, path);
  1764. // We cannot free until now, otherwise path will become invalid
  1765. deallocate_WatcherEvent(&evt);
  1766. queue_completion(&zh->completions_to_process, c, 0);
  1767. } else if (hdr.xid == SET_WATCHES_XID) {
  1768. LOG_DEBUG(("Processing SET_WATCHES"));
  1769. free_buffer(bptr);
  1770. } else if (hdr.xid == AUTH_XID){
  1771. LOG_DEBUG(("Processing AUTH_XID"));
  1772. /* special handling for the AUTH response as it may come back
  1773. * out-of-band */
  1774. auth_completion_func(hdr.err,zh);
  1775. free_buffer(bptr);
  1776. /* authentication completion may change the connection state to
  1777. * unrecoverable */
  1778. if(is_unrecoverable(zh)){
  1779. handle_error(zh, ZAUTHFAILED);
  1780. close_buffer_iarchive(&ia);
  1781. return api_epilog(zh, ZAUTHFAILED);
  1782. }
  1783. } else {
  1784. int rc = hdr.err;
  1785. /* Find the request corresponding to the response */
  1786. completion_list_t *cptr = dequeue_completion(&zh->sent_requests);
  1787. /* [ZOOKEEPER-804] Don't assert if zookeeper_close has been called. */
  1788. if (zh->close_requested == 1) {
  1789. if (cptr) {
  1790. destroy_completion_entry(cptr);
  1791. cptr = NULL;
  1792. }
  1793. return api_epilog(zh,ZINVALIDSTATE);
  1794. }
  1795. assert(cptr);
  1796. /* The requests are going to come back in order */
  1797. if (cptr->xid != hdr.xid) {
  1798. LOG_DEBUG(("Processing unexpected or out-of-order response!"));
  1799. // received unexpected (or out-of-order) response
  1800. close_buffer_iarchive(&ia);
  1801. free_buffer(bptr);
  1802. // put the completion back on the queue (so it gets properly
  1803. // signaled and deallocated) and disconnect from the server
  1804. queue_completion(&zh->sent_requests,cptr,1);
  1805. return handle_socket_error_msg(zh, __LINE__,ZRUNTIMEINCONSISTENCY,
  1806. "unexpected server response: expected %#x, but received %#x",
  1807. hdr.xid,cptr->xid);
  1808. }
  1809. activateWatcher(zh, cptr->watcher, rc);
  1810. if (cptr->c.void_result != SYNCHRONOUS_MARKER) {
  1811. if(hdr.xid == PING_XID){
  1812. int elapsed = 0;
  1813. struct timeval now;
  1814. gettimeofday(&now, 0);
  1815. elapsed = calculate_interval(&zh->last_ping, &now);
  1816. LOG_DEBUG(("Got ping response in %d ms", elapsed));
  1817. // Nothing to do with a ping response
  1818. free_buffer(bptr);
  1819. destroy_completion_entry(cptr);
  1820. } else {
  1821. LOG_DEBUG(("Queueing asynchronous response"));
  1822. cptr->buffer = bptr;
  1823. queue_completion(&zh->completions_to_process, cptr, 0);
  1824. }
  1825. } else {
  1826. struct sync_completion
  1827. *sc = (struct sync_completion*)cptr->data;
  1828. sc->rc = rc;
  1829. switch(cptr->completion_type) {
  1830. case COMPLETION_DATA:
  1831. LOG_DEBUG(("Calling COMPLETION_DATA for xid=%#x rc=%d",
  1832. cptr->xid, rc));
  1833. if (rc==0) {
  1834. struct GetDataResponse res;
  1835. int len;
  1836. deserialize_GetDataResponse(ia, "reply", &res);
  1837. if (res.data.len <= sc->u.data.buff_len) {
  1838. len = res.data.len;
  1839. } else {
  1840. len = sc->u.data.buff_len;
  1841. }
  1842. sc->u.data.buff_len = len;
  1843. // check if len is negative
  1844. // just of NULL which is -1 int
  1845. if (len == -1) {
  1846. sc->u.data.buffer = NULL;
  1847. } else {
  1848. memcpy(sc->u.data.buffer, res.data.buff, len);
  1849. }
  1850. sc->u.data.stat = res.stat;
  1851. deallocate_GetDataResponse(&res);
  1852. }
  1853. break;
  1854. case COMPLETION_STAT:
  1855. LOG_DEBUG(("Calling COMPLETION_STAT for xid=%#x rc=%d",
  1856. cptr->xid, rc));
  1857. if (rc == 0) {
  1858. struct SetDataResponse res;
  1859. deserialize_SetDataResponse(ia, "reply", &res);
  1860. sc->u.stat = res.stat;
  1861. deallocate_SetDataResponse(&res);
  1862. }
  1863. break;
  1864. case COMPLETION_STRINGLIST:
  1865. LOG_DEBUG(("Calling COMPLETION_STRINGLIST for xid=%#x rc=%d",
  1866. cptr->xid, rc));
  1867. if (rc == 0) {
  1868. struct GetChildrenResponse res;
  1869. deserialize_GetChildrenResponse(ia, "reply", &res);
  1870. sc->u.strs2 = res.children;
  1871. /* We don't deallocate since we are passing it back */
  1872. // deallocate_GetChildrenResponse(&res);
  1873. }
  1874. break;
  1875. case COMPLETION_STRINGLIST_STAT:
  1876. LOG_DEBUG(("Calling COMPLETION_STRINGLIST_STAT for xid=%#x rc=%d",
  1877. cptr->xid, rc));
  1878. if (rc == 0) {
  1879. struct GetChildren2Response res;
  1880. deserialize_GetChildren2Response(ia, "reply", &res);
  1881. sc->u.strs_stat.strs2 = res.children;
  1882. sc->u.strs_stat.stat2 = res.stat;
  1883. /* We don't deallocate since we are passing it back */
  1884. // deallocate_GetChildren2Response(&res);
  1885. }
  1886. break;
  1887. case COMPLETION_STRING:
  1888. LOG_DEBUG(("Calling COMPLETION_STRING for xid=%#x rc=%d",
  1889. cptr->xid, rc));
  1890. if (rc == 0) {
  1891. struct CreateResponse res;
  1892. int len;
  1893. deserialize_CreateResponse(ia, "reply", &res);
  1894. len = strlen(res.path) + 1;
  1895. if (len > sc->u.str.str_len) {
  1896. len = sc->u.str.str_len;
  1897. }
  1898. if (len > 0) {
  1899. memcpy(sc->u.str.str, res.path, len - 1);
  1900. sc->u.str.str[len - 1] = '\0';
  1901. }
  1902. deallocate_CreateResponse(&res);
  1903. }
  1904. break;
  1905. case COMPLETION_ACLLIST:
  1906. LOG_DEBUG(("Calling COMPLETION_ACLLIST for xid=%#x rc=%d",
  1907. cptr->xid, rc));
  1908. if (rc == 0) {
  1909. struct GetACLResponse res;
  1910. deserialize_GetACLResponse(ia, "reply", &res);
  1911. sc->u.acl.acl = res.acl;
  1912. sc->u.acl.stat = res.stat;
  1913. /* We don't deallocate since we are passing it back */
  1914. //deallocate_GetACLResponse(&res);
  1915. }
  1916. break;
  1917. case COMPLETION_VOID:
  1918. LOG_DEBUG(("Calling COMPLETION_VOID for xid=%#x rc=%d",
  1919. cptr->xid, rc));
  1920. break;
  1921. default:
  1922. LOG_DEBUG(("UNKNOWN response type xid=%#x rc=%d",
  1923. cptr->xid, rc));
  1924. break;
  1925. }
  1926. notify_sync_completion(sc);
  1927. free_buffer(bptr);
  1928. zh->outstanding_sync--;
  1929. destroy_completion_entry(cptr);
  1930. }
  1931. }
  1932. close_buffer_iarchive(&ia);
  1933. }
  1934. if (process_async(zh->outstanding_sync)) {
  1935. process_completions(zh);
  1936. }
  1937. return api_epilog(zh,ZOK);}
  1938. int zoo_state(zhandle_t *zh)
  1939. {
  1940. if(zh!=0)
  1941. return zh->state;
  1942. return 0;
  1943. }
  1944. static watcher_registration_t* create_watcher_registration(const char* path,
  1945. result_checker_fn checker,watcher_fn watcher,void* ctx){
  1946. watcher_registration_t* wo;
  1947. if(watcher==0)
  1948. return 0;
  1949. wo=calloc(1,sizeof(watcher_registration_t));
  1950. wo->path=strdup(path);
  1951. wo->watcher=watcher;
  1952. wo->context=ctx;
  1953. wo->checker=checker;
  1954. return wo;
  1955. }
  1956. static void destroy_watcher_registration(watcher_registration_t* wo){
  1957. if(wo!=0){
  1958. free((void*)wo->path);
  1959. free(wo);
  1960. }
  1961. }
  1962. static completion_list_t* create_completion_entry(int xid, int completion_type,
  1963. const void *dc, const void *data,watcher_registration_t* wo)
  1964. {
  1965. completion_list_t *c = calloc(1,sizeof(completion_list_t));
  1966. if (!c) {
  1967. LOG_ERROR(("out of memory"));
  1968. return 0;
  1969. }
  1970. c->completion_type = completion_type;
  1971. c->data = data;
  1972. switch(c->completion_type) {
  1973. case COMPLETION_VOID:
  1974. c->c.void_result = (void_completion_t)dc;
  1975. break;
  1976. case COMPLETION_STRING:
  1977. c->c.string_result = (string_completion_t)dc;
  1978. break;
  1979. case COMPLETION_DATA:
  1980. c->c.data_result = (data_completion_t)dc;
  1981. break;
  1982. case COMPLETION_STAT:
  1983. c->c.stat_result = (stat_completion_t)dc;
  1984. break;
  1985. case COMPLETION_STRINGLIST:
  1986. c->c.strings_result = (strings_completion_t)dc;
  1987. break;
  1988. case COMPLETION_STRINGLIST_STAT:
  1989. c->c.strings_stat_result = (strings_stat_completion_t)dc;
  1990. break;
  1991. case COMPLETION_ACLLIST:
  1992. c->c.acl_result = (acl_completion_t)dc;
  1993. break;
  1994. }
  1995. c->xid = xid;
  1996. c->watcher = wo;
  1997. return c;
  1998. }
  1999. static void destroy_completion_entry(completion_list_t* c){
  2000. if(c!=0){
  2001. destroy_watcher_registration(c->watcher);
  2002. if(c->buffer!=0)
  2003. free_buffer(c->buffer);
  2004. free(c);
  2005. }
  2006. }
  2007. static void queue_completion_nolock(completion_head_t *list,
  2008. completion_list_t *c,
  2009. int add_to_front)
  2010. {
  2011. c->next = 0;
  2012. /* appending a new entry to the back of the list */
  2013. if (list->last) {
  2014. assert(list->head);
  2015. // List is not empty
  2016. if (!add_to_front) {
  2017. list->last->next = c;
  2018. list->last = c;
  2019. } else {
  2020. c->next = list->head;
  2021. list->head = c;
  2022. }
  2023. } else {
  2024. // List is empty
  2025. assert(!list->head);
  2026. list->head = c;
  2027. list->last = c;
  2028. }
  2029. }
  2030. static void queue_completion(completion_head_t *list, completion_list_t *c,
  2031. int add_to_front)
  2032. {
  2033. lock_completion_list(list);
  2034. queue_completion_nolock(list, c, add_to_front);
  2035. unlock_completion_list(list);
  2036. }
  2037. static int add_completion(zhandle_t *zh, int xid, int completion_type,
  2038. const void *dc, const void *data, int add_to_front,
  2039. watcher_registration_t* wo)
  2040. {
  2041. completion_list_t *c =create_completion_entry(xid, completion_type, dc,
  2042. data,wo);
  2043. int rc = 0;
  2044. if (!c)
  2045. return ZSYSTEMERROR;
  2046. lock_completion_list(&zh->sent_requests);
  2047. if (zh->close_requested != 1) {
  2048. queue_completion_nolock(&zh->sent_requests, c, add_to_front);
  2049. if (dc == SYNCHRONOUS_MARKER) {
  2050. zh->outstanding_sync++;
  2051. }
  2052. rc = ZOK;
  2053. } else {
  2054. free(c);
  2055. rc = ZINVALIDSTATE;
  2056. }
  2057. unlock_completion_list(&zh->sent_requests);
  2058. return rc;
  2059. }
  2060. static int add_data_completion(zhandle_t *zh, int xid, data_completion_t dc,
  2061. const void *data,watcher_registration_t* wo)
  2062. {
  2063. return add_completion(zh, xid, COMPLETION_DATA, dc, data, 0,wo);
  2064. }
  2065. static int add_stat_completion(zhandle_t *zh, int xid, stat_completion_t dc,
  2066. const void *data,watcher_registration_t* wo)
  2067. {
  2068. return add_completion(zh, xid, COMPLETION_STAT, dc, data, 0,wo);
  2069. }
  2070. static int add_strings_completion(zhandle_t *zh, int xid,
  2071. strings_completion_t dc, const void *data,watcher_registration_t* wo)
  2072. {
  2073. return add_completion(zh, xid, COMPLETION_STRINGLIST, dc, data, 0,wo);
  2074. }
  2075. static int add_strings_stat_completion(zhandle_t *zh, int xid,
  2076. strings_stat_completion_t dc, const void *data,watcher_registration_t* wo)
  2077. {
  2078. return add_completion(zh, xid, COMPLETION_STRINGLIST_STAT, dc, data, 0,wo);
  2079. }
  2080. static int add_acl_completion(zhandle_t *zh, int xid, acl_completion_t dc,
  2081. const void *data)
  2082. {
  2083. return add_completion(zh, xid, COMPLETION_ACLLIST, dc, data, 0,0);
  2084. }
  2085. static int add_void_completion(zhandle_t *zh, int xid, void_completion_t dc,
  2086. const void *data)
  2087. {
  2088. return add_completion(zh, xid, COMPLETION_VOID, dc, data, 0,0);
  2089. }
  2090. static int add_string_completion(zhandle_t *zh, int xid,
  2091. string_completion_t dc, const void *data)
  2092. {
  2093. return add_completion(zh, xid, COMPLETION_STRING, dc, data, 0,0);
  2094. }
  2095. int zookeeper_close(zhandle_t *zh)
  2096. {
  2097. int rc=ZOK;
  2098. if (zh==0)
  2099. return ZBADARGUMENTS;
  2100. zh->close_requested=1;
  2101. if (inc_ref_counter(zh,0)!=0) {
  2102. /* Signal any syncronous completions before joining the threads */
  2103. enter_critical(zh);
  2104. free_completions(zh,1,ZCLOSING);
  2105. leave_critical(zh);
  2106. adaptor_finish(zh);
  2107. return ZOK;
  2108. }
  2109. if(zh->state==ZOO_CONNECTED_STATE){
  2110. struct oarchive *oa;
  2111. struct RequestHeader h = { .xid = get_xid(), .type = CLOSE_OP};
  2112. LOG_INFO(("Closing zookeeper sessionId=%#llx to [%s]\n",
  2113. zh->client_id.client_id,format_current_endpoint_info(zh)));
  2114. oa = create_buffer_oarchive();
  2115. rc = serialize_RequestHeader(oa, "header", &h);
  2116. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2117. get_buffer_len(oa));
  2118. /* We queued the buffer, so don't free it */
  2119. close_buffer_oarchive(&oa, 0);
  2120. if (rc < 0) {
  2121. rc = ZMARSHALLINGERROR;
  2122. goto finish;
  2123. }
  2124. /* make sure the close request is sent; we set timeout to an arbitrary
  2125. * (but reasonable) number of milliseconds since we want the call to block*/
  2126. rc=adaptor_send_queue(zh, 3000);
  2127. }else{
  2128. LOG_INFO(("Freeing zookeeper resources for sessionId=%#llx\n",
  2129. zh->client_id.client_id));
  2130. rc = ZOK;
  2131. }
  2132. finish:
  2133. destroy(zh);
  2134. adaptor_destroy(zh);
  2135. free(zh);
  2136. return rc;
  2137. }
  2138. static int isValidPath(const char* path, const int flags) {
  2139. int len = 0;
  2140. char lastc = '/';
  2141. char c;
  2142. int i = 0;
  2143. if (path == 0)
  2144. return 0;
  2145. len = strlen(path);
  2146. if (len == 0)
  2147. return 0;
  2148. if (path[0] != '/')
  2149. return 0;
  2150. if (len == 1) // done checking - it's the root
  2151. return 1;
  2152. if (path[len - 1] == '/' && !(flags & ZOO_SEQUENCE))
  2153. return 0;
  2154. i = 1;
  2155. for (; i < len; lastc = path[i], i++) {
  2156. c = path[i];
  2157. if (c == 0) {
  2158. return 0;
  2159. } else if (c == '/' && lastc == '/') {
  2160. return 0;
  2161. } else if (c == '.' && lastc == '.') {
  2162. if (path[i-2] == '/' && (((i + 1 == len) && !(flags & ZOO_SEQUENCE))
  2163. || path[i+1] == '/')) {
  2164. return 0;
  2165. }
  2166. } else if (c == '.') {
  2167. if ((path[i-1] == '/') && (((i + 1 == len) && !(flags & ZOO_SEQUENCE))
  2168. || path[i+1] == '/')) {
  2169. return 0;
  2170. }
  2171. } else if (c > 0x00 && c < 0x1f) {
  2172. return 0;
  2173. }
  2174. }
  2175. return 1;
  2176. }
  2177. int zoo_aget(zhandle_t *zh, const char *path, int watch, data_completion_t dc,
  2178. const void *data)
  2179. {
  2180. return zoo_awget(zh,path,watch?zh->watcher:0,zh->context,dc,data);
  2181. }
  2182. int zoo_awget(zhandle_t *zh, const char *path,
  2183. watcher_fn watcher, void* watcherCtx,
  2184. data_completion_t dc, const void *data)
  2185. {
  2186. struct oarchive *oa;
  2187. char *server_path = prepend_string(zh, path);
  2188. struct RequestHeader h = { .xid = get_xid(), .type = GETDATA_OP};
  2189. struct GetDataRequest req = { (char*)server_path, watcher!=0 };
  2190. int rc;
  2191. if (zh==0 || !isValidPath(server_path, 0)) {
  2192. free_duplicate_path(server_path, path);
  2193. return ZBADARGUMENTS;
  2194. }
  2195. if (is_unrecoverable(zh)) {
  2196. free_duplicate_path(server_path, path);
  2197. return ZINVALIDSTATE;
  2198. }
  2199. oa=create_buffer_oarchive();
  2200. rc = serialize_RequestHeader(oa, "header", &h);
  2201. rc = rc < 0 ? rc : serialize_GetDataRequest(oa, "req", &req);
  2202. enter_critical(zh);
  2203. rc = rc < 0 ? rc : add_data_completion(zh, h.xid, dc, data,
  2204. create_watcher_registration(server_path,data_result_checker,watcher,watcherCtx));
  2205. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2206. get_buffer_len(oa));
  2207. leave_critical(zh);
  2208. free_duplicate_path(server_path, path);
  2209. /* We queued the buffer, so don't free it */
  2210. close_buffer_oarchive(&oa, 0);
  2211. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2212. format_current_endpoint_info(zh)));
  2213. /* make a best (non-blocking) effort to send the requests asap */
  2214. adaptor_send_queue(zh, 0);
  2215. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2216. }
  2217. int zoo_aset(zhandle_t *zh, const char *path, const char *buffer, int buflen,
  2218. int version, stat_completion_t dc, const void *data)
  2219. {
  2220. struct oarchive *oa;
  2221. struct RequestHeader h = { .xid = get_xid(), .type = SETDATA_OP};
  2222. struct SetDataRequest req;
  2223. int rc;
  2224. char *server_path;
  2225. server_path = prepend_string(zh, path);
  2226. if (zh==0 || !isValidPath(server_path, 0)) {
  2227. free_duplicate_path(server_path, path);
  2228. return ZBADARGUMENTS;
  2229. }
  2230. if (is_unrecoverable(zh)) {
  2231. free_duplicate_path(server_path, path);
  2232. return ZINVALIDSTATE;
  2233. }
  2234. oa = create_buffer_oarchive();
  2235. req.path = (char*)server_path;
  2236. req.data.buff = (char*)buffer;
  2237. req.data.len = buflen;
  2238. req.version = version;
  2239. rc = serialize_RequestHeader(oa, "header", &h);
  2240. rc = rc < 0 ? rc : serialize_SetDataRequest(oa, "req", &req);
  2241. enter_critical(zh);
  2242. rc = rc < 0 ? rc : add_stat_completion(zh, h.xid, dc, data,0);
  2243. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2244. get_buffer_len(oa));
  2245. leave_critical(zh);
  2246. free_duplicate_path(server_path, path);
  2247. /* We queued the buffer, so don't free it */
  2248. close_buffer_oarchive(&oa, 0);
  2249. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2250. format_current_endpoint_info(zh)));
  2251. /* make a best (non-blocking) effort to send the requests asap */
  2252. adaptor_send_queue(zh, 0);
  2253. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2254. }
  2255. int zoo_acreate(zhandle_t *zh, const char *path, const char *value,
  2256. int valuelen, const struct ACL_vector *acl_entries, int flags,
  2257. string_completion_t completion, const void *data)
  2258. {
  2259. struct oarchive *oa;
  2260. struct RequestHeader h = { .xid = get_xid(), .type = CREATE_OP };
  2261. struct CreateRequest req;
  2262. int rc;
  2263. char *server_path;
  2264. server_path = prepend_string(zh, path);
  2265. if (zh==0 || !isValidPath(server_path, flags)) {
  2266. free_duplicate_path(server_path, path);
  2267. return ZBADARGUMENTS;
  2268. }
  2269. if (is_unrecoverable(zh)) {
  2270. free_duplicate_path(server_path, path);
  2271. return ZINVALIDSTATE;
  2272. }
  2273. oa = create_buffer_oarchive();
  2274. req.path = (char*)server_path;
  2275. req.flags = flags;
  2276. req.data.buff = (char*)value;
  2277. req.data.len = valuelen;
  2278. if (acl_entries == 0) {
  2279. req.acl.count = 0;
  2280. req.acl.data = 0;
  2281. } else {
  2282. req.acl = *acl_entries;
  2283. }
  2284. rc = serialize_RequestHeader(oa, "header", &h);
  2285. rc = rc < 0 ? rc : serialize_CreateRequest(oa, "req", &req);
  2286. enter_critical(zh);
  2287. rc = rc < 0 ? rc : add_string_completion(zh, h.xid, completion, data);
  2288. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2289. get_buffer_len(oa));
  2290. leave_critical(zh);
  2291. free_duplicate_path(server_path, path);
  2292. /* We queued the buffer, so don't free it */
  2293. close_buffer_oarchive(&oa, 0);
  2294. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2295. format_current_endpoint_info(zh)));
  2296. /* make a best (non-blocking) effort to send the requests asap */
  2297. adaptor_send_queue(zh, 0);
  2298. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2299. }
  2300. int zoo_adelete(zhandle_t *zh, const char *path, int version,
  2301. void_completion_t completion, const void *data)
  2302. {
  2303. struct oarchive *oa;
  2304. struct RequestHeader h = { .xid = get_xid(), .type = DELETE_OP};
  2305. struct DeleteRequest req;
  2306. int rc;
  2307. char *server_path;
  2308. server_path = prepend_string(zh, path);
  2309. if (zh==0 || !isValidPath(server_path, 0)) {
  2310. free_duplicate_path(server_path, path);
  2311. return ZBADARGUMENTS;
  2312. }
  2313. if (is_unrecoverable(zh)) {
  2314. free_duplicate_path(server_path, path);
  2315. return ZINVALIDSTATE;
  2316. }
  2317. oa = create_buffer_oarchive();
  2318. req.path = (char*)server_path;
  2319. req.version = version;
  2320. rc = serialize_RequestHeader(oa, "header", &h);
  2321. rc = rc < 0 ? rc : serialize_DeleteRequest(oa, "req", &req);
  2322. enter_critical(zh);
  2323. rc = rc < 0 ? rc : add_void_completion(zh, h.xid, completion, data);
  2324. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2325. get_buffer_len(oa));
  2326. leave_critical(zh);
  2327. free_duplicate_path(server_path, path);
  2328. /* We queued the buffer, so don't free it */
  2329. close_buffer_oarchive(&oa, 0);
  2330. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2331. format_current_endpoint_info(zh)));
  2332. /* make a best (non-blocking) effort to send the requests asap */
  2333. adaptor_send_queue(zh, 0);
  2334. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2335. }
  2336. int zoo_aexists(zhandle_t *zh, const char *path, int watch,
  2337. stat_completion_t sc, const void *data)
  2338. {
  2339. return zoo_awexists(zh,path,watch?zh->watcher:0,zh->context,sc,data);
  2340. }
  2341. int zoo_awexists(zhandle_t *zh, const char *path,
  2342. watcher_fn watcher, void* watcherCtx,
  2343. stat_completion_t completion, const void *data)
  2344. {
  2345. struct oarchive *oa;
  2346. struct RequestHeader h = { .xid = get_xid(), .type = EXISTS_OP };
  2347. char *server_path = prepend_string(zh, path);
  2348. struct ExistsRequest req = {(char*)server_path, watcher!=0 };
  2349. int rc;
  2350. if (zh==0 || !isValidPath(server_path, 0)) {
  2351. free_duplicate_path(server_path, path);
  2352. return ZBADARGUMENTS;
  2353. }
  2354. if (is_unrecoverable(zh)) {
  2355. free_duplicate_path(server_path, path);
  2356. return ZINVALIDSTATE;
  2357. }
  2358. oa = create_buffer_oarchive();
  2359. rc = serialize_RequestHeader(oa, "header", &h);
  2360. rc = rc < 0 ? rc : serialize_ExistsRequest(oa, "req", &req);
  2361. enter_critical(zh);
  2362. rc = rc < 0 ? rc : add_stat_completion(zh, h.xid, completion, data,
  2363. create_watcher_registration(server_path,exists_result_checker,
  2364. watcher,watcherCtx));
  2365. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2366. get_buffer_len(oa));
  2367. leave_critical(zh);
  2368. free_duplicate_path(server_path, path);
  2369. /* We queued the buffer, so don't free it */
  2370. close_buffer_oarchive(&oa, 0);
  2371. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2372. format_current_endpoint_info(zh)));
  2373. /* make a best (non-blocking) effort to send the requests asap */
  2374. adaptor_send_queue(zh, 0);
  2375. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2376. }
  2377. static int zoo_awget_children_(zhandle_t *zh, const char *path,
  2378. watcher_fn watcher, void* watcherCtx,
  2379. strings_completion_t sc,
  2380. const void *data)
  2381. {
  2382. struct oarchive *oa;
  2383. struct RequestHeader h = { .xid = get_xid(), .type = GETCHILDREN_OP};
  2384. char * server_path = prepend_string(zh, path);
  2385. struct GetChildrenRequest req = {(char*)server_path, watcher!=0 };
  2386. int rc;
  2387. if (zh==0 || !isValidPath(server_path, 0)) {
  2388. free_duplicate_path(server_path, path);
  2389. return ZBADARGUMENTS;
  2390. }
  2391. if (is_unrecoverable(zh)) {
  2392. free_duplicate_path(server_path, path);
  2393. return ZINVALIDSTATE;
  2394. }
  2395. oa = create_buffer_oarchive();
  2396. rc = serialize_RequestHeader(oa, "header", &h);
  2397. rc = rc < 0 ? rc : serialize_GetChildrenRequest(oa, "req", &req);
  2398. enter_critical(zh);
  2399. rc = rc < 0 ? rc : add_strings_completion(zh, h.xid, sc, data,
  2400. create_watcher_registration(server_path,child_result_checker,watcher,watcherCtx));
  2401. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2402. get_buffer_len(oa));
  2403. leave_critical(zh);
  2404. free_duplicate_path(server_path, path);
  2405. /* We queued the buffer, so don't free it */
  2406. close_buffer_oarchive(&oa, 0);
  2407. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2408. format_current_endpoint_info(zh)));
  2409. /* make a best (non-blocking) effort to send the requests asap */
  2410. adaptor_send_queue(zh, 0);
  2411. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2412. }
  2413. int zoo_aget_children(zhandle_t *zh, const char *path, int watch,
  2414. strings_completion_t dc, const void *data)
  2415. {
  2416. return zoo_awget_children_(zh,path,watch?zh->watcher:0,zh->context,dc,data);
  2417. }
  2418. int zoo_awget_children(zhandle_t *zh, const char *path,
  2419. watcher_fn watcher, void* watcherCtx,
  2420. strings_completion_t dc,
  2421. const void *data)
  2422. {
  2423. return zoo_awget_children_(zh,path,watcher,watcherCtx,dc,data);
  2424. }
  2425. static int zoo_awget_children2_(zhandle_t *zh, const char *path,
  2426. watcher_fn watcher, void* watcherCtx,
  2427. strings_stat_completion_t ssc,
  2428. const void *data)
  2429. {
  2430. /* invariant: (sc == NULL) != (sc == NULL) */
  2431. struct oarchive *oa;
  2432. struct RequestHeader h = { .xid = get_xid(), .type = GETCHILDREN2_OP};
  2433. char * server_path = prepend_string(zh, path);
  2434. struct GetChildren2Request req2 = {(char*)server_path, watcher!=0 };
  2435. int rc;
  2436. if (zh==0 || !isValidPath(server_path, 0)) {
  2437. free_duplicate_path(server_path, path);
  2438. return ZBADARGUMENTS;
  2439. }
  2440. if (is_unrecoverable(zh)) {
  2441. free_duplicate_path(server_path, path);
  2442. return ZINVALIDSTATE;
  2443. }
  2444. oa = create_buffer_oarchive();
  2445. rc = serialize_RequestHeader(oa, "header", &h);
  2446. rc = rc < 0 ? rc : serialize_GetChildren2Request(oa, "req", &req2);
  2447. enter_critical(zh);
  2448. rc = rc < 0 ? rc : add_strings_stat_completion(zh, h.xid, ssc, data,
  2449. create_watcher_registration(server_path,child_result_checker,watcher,watcherCtx));
  2450. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2451. get_buffer_len(oa));
  2452. leave_critical(zh);
  2453. free_duplicate_path(server_path, path);
  2454. /* We queued the buffer, so don't free it */
  2455. close_buffer_oarchive(&oa, 0);
  2456. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2457. format_current_endpoint_info(zh)));
  2458. /* make a best (non-blocking) effort to send the requests asap */
  2459. adaptor_send_queue(zh, 0);
  2460. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2461. }
  2462. int zoo_aget_children2(zhandle_t *zh, const char *path, int watch,
  2463. strings_stat_completion_t dc, const void *data)
  2464. {
  2465. return zoo_awget_children2_(zh,path,watch?zh->watcher:0,zh->context,dc,data);
  2466. }
  2467. int zoo_awget_children2(zhandle_t *zh, const char *path,
  2468. watcher_fn watcher, void* watcherCtx,
  2469. strings_stat_completion_t dc,
  2470. const void *data)
  2471. {
  2472. return zoo_awget_children2_(zh,path,watcher,watcherCtx,dc,data);
  2473. }
  2474. int zoo_async(zhandle_t *zh, const char *path,
  2475. string_completion_t completion, const void *data)
  2476. {
  2477. struct oarchive *oa;
  2478. struct RequestHeader h = { .xid = get_xid(), .type = SYNC_OP};
  2479. struct SyncRequest req;
  2480. int rc;
  2481. char *server_path;
  2482. server_path = prepend_string(zh, path);
  2483. if (zh==0 || !isValidPath(server_path, 0)) {
  2484. free_duplicate_path(server_path, path);
  2485. return ZBADARGUMENTS;
  2486. }
  2487. if (is_unrecoverable(zh)) {
  2488. free_duplicate_path(server_path, path);
  2489. return ZINVALIDSTATE;
  2490. }
  2491. oa = create_buffer_oarchive();
  2492. req.path = (char*)server_path;
  2493. rc = serialize_RequestHeader(oa, "header", &h);
  2494. rc = rc < 0 ? rc : serialize_SyncRequest(oa, "req", &req);
  2495. enter_critical(zh);
  2496. rc = rc < 0 ? rc : add_string_completion(zh, h.xid, completion, data);
  2497. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2498. get_buffer_len(oa));
  2499. leave_critical(zh);
  2500. free_duplicate_path(server_path, path);
  2501. /* We queued the buffer, so don't free it */
  2502. close_buffer_oarchive(&oa, 0);
  2503. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2504. format_current_endpoint_info(zh)));
  2505. /* make a best (non-blocking) effort to send the requests asap */
  2506. adaptor_send_queue(zh, 0);
  2507. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2508. }
  2509. int zoo_aget_acl(zhandle_t *zh, const char *path, acl_completion_t completion,
  2510. const void *data)
  2511. {
  2512. struct oarchive *oa;
  2513. struct RequestHeader h = { .xid = get_xid(), .type = GETACL_OP};
  2514. struct GetACLRequest req;
  2515. int rc;
  2516. char *server_path;
  2517. server_path = prepend_string(zh, path);
  2518. if (zh==0 || !isValidPath(server_path, 0)) {
  2519. free_duplicate_path(server_path, path);
  2520. return ZBADARGUMENTS;
  2521. }
  2522. if (is_unrecoverable(zh)) {
  2523. free_duplicate_path(server_path, path);
  2524. return ZINVALIDSTATE;
  2525. }
  2526. oa = create_buffer_oarchive();
  2527. req.path = (char*)server_path;
  2528. rc = serialize_RequestHeader(oa, "header", &h);
  2529. rc = rc < 0 ? rc : serialize_GetACLRequest(oa, "req", &req);
  2530. enter_critical(zh);
  2531. rc = rc < 0 ? rc : add_acl_completion(zh, h.xid, completion, data);
  2532. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2533. get_buffer_len(oa));
  2534. leave_critical(zh);
  2535. free_duplicate_path(server_path, path);
  2536. /* We queued the buffer, so don't free it */
  2537. close_buffer_oarchive(&oa, 0);
  2538. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2539. format_current_endpoint_info(zh)));
  2540. /* make a best (non-blocking) effort to send the requests asap */
  2541. adaptor_send_queue(zh, 0);
  2542. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2543. }
  2544. int zoo_aset_acl(zhandle_t *zh, const char *path, int version,
  2545. struct ACL_vector *acl, void_completion_t completion, const void *data)
  2546. {
  2547. struct oarchive *oa;
  2548. struct RequestHeader h = { .xid = get_xid(), .type = SETACL_OP};
  2549. struct SetACLRequest req;
  2550. int rc;
  2551. char *server_path;
  2552. server_path = prepend_string(zh, path);
  2553. if (zh==0 || !isValidPath(server_path, 0)) {
  2554. free_duplicate_path(server_path, path);
  2555. return ZBADARGUMENTS;
  2556. }
  2557. if (is_unrecoverable(zh)) {
  2558. free_duplicate_path(server_path, path);
  2559. return ZINVALIDSTATE;
  2560. }
  2561. oa = create_buffer_oarchive();
  2562. req.path = (char*)server_path;
  2563. req.acl = *acl;
  2564. req.version = version;
  2565. rc = serialize_RequestHeader(oa, "header", &h);
  2566. rc = rc < 0 ? rc : serialize_SetACLRequest(oa, "req", &req);
  2567. enter_critical(zh);
  2568. rc = rc < 0 ? rc : add_void_completion(zh, h.xid, completion, data);
  2569. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2570. get_buffer_len(oa));
  2571. leave_critical(zh);
  2572. free_duplicate_path(server_path, path);
  2573. /* We queued the buffer, so don't free it */
  2574. close_buffer_oarchive(&oa, 0);
  2575. LOG_DEBUG(("Sending request xid=%#x for path [%s] to %s",h.xid,path,
  2576. format_current_endpoint_info(zh)));
  2577. /* make a best (non-blocking) effort to send the requests asap */
  2578. adaptor_send_queue(zh, 0);
  2579. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  2580. }
  2581. /* specify timeout of 0 to make the function non-blocking */
  2582. /* timeout is in milliseconds */
  2583. int flush_send_queue(zhandle_t*zh, int timeout)
  2584. {
  2585. int rc= ZOK;
  2586. struct timeval started;
  2587. gettimeofday(&started,0);
  2588. // we can't use dequeue_buffer() here because if (non-blocking) send_buffer()
  2589. // returns EWOULDBLOCK we'd have to put the buffer back on the queue.
  2590. // we use a recursive lock instead and only dequeue the buffer if a send was
  2591. // successful
  2592. lock_buffer_list(&zh->to_send);
  2593. while (zh->to_send.head != 0&& zh->state == ZOO_CONNECTED_STATE) {
  2594. if(timeout!=0){
  2595. int elapsed;
  2596. struct pollfd fds;
  2597. struct timeval now;
  2598. gettimeofday(&now,0);
  2599. elapsed=calculate_interval(&started,&now);
  2600. if (elapsed>timeout) {
  2601. rc = ZOPERATIONTIMEOUT;
  2602. break;
  2603. }
  2604. fds.fd = zh->fd;
  2605. fds.events = POLLOUT;
  2606. fds.revents = 0;
  2607. rc = poll(&fds, 1, timeout-elapsed);
  2608. if (rc<=0) {
  2609. /* timed out or an error or POLLERR */
  2610. rc = rc==0 ? ZOPERATIONTIMEOUT : ZSYSTEMERROR;
  2611. break;
  2612. }
  2613. }
  2614. rc = send_buffer(zh->fd, zh->to_send.head);
  2615. if(rc==0 && timeout==0){
  2616. /* send_buffer would block while sending this buffer */
  2617. rc = ZOK;
  2618. break;
  2619. }
  2620. if (rc < 0) {
  2621. rc = ZCONNECTIONLOSS;
  2622. break;
  2623. }
  2624. // if the buffer has been sent successfully, remove it from the queue
  2625. if (rc > 0)
  2626. remove_buffer(&zh->to_send);
  2627. gettimeofday(&zh->last_send, 0);
  2628. rc = ZOK;
  2629. }
  2630. unlock_buffer_list(&zh->to_send);
  2631. return rc;
  2632. }
  2633. const char* zerror(int c)
  2634. {
  2635. switch (c){
  2636. case ZOK:
  2637. return "ok";
  2638. case ZSYSTEMERROR:
  2639. return "system error";
  2640. case ZRUNTIMEINCONSISTENCY:
  2641. return "run time inconsistency";
  2642. case ZDATAINCONSISTENCY:
  2643. return "data inconsistency";
  2644. case ZCONNECTIONLOSS:
  2645. return "connection loss";
  2646. case ZMARSHALLINGERROR:
  2647. return "marshalling error";
  2648. case ZUNIMPLEMENTED:
  2649. return "unimplemented";
  2650. case ZOPERATIONTIMEOUT:
  2651. return "operation timeout";
  2652. case ZBADARGUMENTS:
  2653. return "bad arguments";
  2654. case ZINVALIDSTATE:
  2655. return "invalid zhandle state";
  2656. case ZAPIERROR:
  2657. return "api error";
  2658. case ZNONODE:
  2659. return "no node";
  2660. case ZNOAUTH:
  2661. return "not authenticated";
  2662. case ZBADVERSION:
  2663. return "bad version";
  2664. case ZNOCHILDRENFOREPHEMERALS:
  2665. return "no children for ephemerals";
  2666. case ZNODEEXISTS:
  2667. return "node exists";
  2668. case ZNOTEMPTY:
  2669. return "not empty";
  2670. case ZSESSIONEXPIRED:
  2671. return "session expired";
  2672. case ZINVALIDCALLBACK:
  2673. return "invalid callback";
  2674. case ZINVALIDACL:
  2675. return "invalid acl";
  2676. case ZAUTHFAILED:
  2677. return "authentication failed";
  2678. case ZCLOSING:
  2679. return "zookeeper is closing";
  2680. case ZNOTHING:
  2681. return "(not error) no server responses to process";
  2682. case ZSESSIONMOVED:
  2683. return "session moved to another server, so operation is ignored";
  2684. }
  2685. if (c > 0) {
  2686. return strerror(c);
  2687. }
  2688. return "unknown error";
  2689. }
  2690. int zoo_add_auth(zhandle_t *zh,const char* scheme,const char* cert,
  2691. int certLen,void_completion_t completion, const void *data)
  2692. {
  2693. struct buffer auth;
  2694. auth_info *authinfo;
  2695. if(scheme==NULL || zh==NULL)
  2696. return ZBADARGUMENTS;
  2697. if (is_unrecoverable(zh))
  2698. return ZINVALIDSTATE;
  2699. // [ZOOKEEPER-800] zoo_add_auth should return ZINVALIDSTATE if
  2700. // the connection is closed.
  2701. if (zoo_state(zh) == 0) {
  2702. return ZINVALIDSTATE;
  2703. }
  2704. if(cert!=NULL && certLen!=0){
  2705. auth.buff=calloc(1,certLen);
  2706. if(auth.buff==0) {
  2707. return ZSYSTEMERROR;
  2708. }
  2709. memcpy(auth.buff,cert,certLen);
  2710. auth.len=certLen;
  2711. } else {
  2712. auth.buff = 0;
  2713. auth.len = 0;
  2714. }
  2715. zoo_lock_auth(zh);
  2716. authinfo = (auth_info*) malloc(sizeof(auth_info));
  2717. authinfo->scheme=strdup(scheme);
  2718. authinfo->auth=auth;
  2719. authinfo->completion=completion;
  2720. authinfo->data=data;
  2721. authinfo->next = NULL;
  2722. add_last_auth(&zh->auth_h, authinfo);
  2723. zoo_unlock_auth(zh);
  2724. if(zh->state == ZOO_CONNECTED_STATE || zh->state == ZOO_ASSOCIATING_STATE)
  2725. return send_last_auth_info(zh);
  2726. return ZOK;
  2727. }
  2728. static const char* format_endpoint_info(const struct sockaddr_storage* ep)
  2729. {
  2730. static char buf[128];
  2731. char addrstr[128];
  2732. void *inaddr;
  2733. int port;
  2734. if(ep==0)
  2735. return "null";
  2736. #if defined(AF_INET6)
  2737. if(ep->ss_family==AF_INET6){
  2738. inaddr=&((struct sockaddr_in6*)ep)->sin6_addr;
  2739. port=((struct sockaddr_in6*)ep)->sin6_port;
  2740. } else {
  2741. #endif
  2742. inaddr=&((struct sockaddr_in*)ep)->sin_addr;
  2743. port=((struct sockaddr_in*)ep)->sin_port;
  2744. #if defined(AF_INET6)
  2745. }
  2746. #endif
  2747. inet_ntop(ep->ss_family,inaddr,addrstr,sizeof(addrstr)-1);
  2748. sprintf(buf,"%s:%d",addrstr,ntohs(port));
  2749. return buf;
  2750. }
  2751. static const char* format_current_endpoint_info(zhandle_t* zh)
  2752. {
  2753. return format_endpoint_info(&zh->addrs[zh->connect_index]);
  2754. }
  2755. void zoo_deterministic_conn_order(int yesOrNo)
  2756. {
  2757. disable_conn_permute=yesOrNo;
  2758. }
  2759. /* ****************************************************************************
  2760. * sync API
  2761. */
  2762. int zoo_create(zhandle_t *zh, const char *path, const char *value,
  2763. int valuelen, const struct ACL_vector *acl, int flags,
  2764. char *path_buffer, int path_buffer_len)
  2765. {
  2766. struct sync_completion *sc = alloc_sync_completion();
  2767. int rc;
  2768. if (!sc) {
  2769. return ZSYSTEMERROR;
  2770. }
  2771. sc->u.str.str = path_buffer;
  2772. sc->u.str.str_len = path_buffer_len;
  2773. rc=zoo_acreate(zh, path, value, valuelen, acl, flags, SYNCHRONOUS_MARKER, sc);
  2774. if(rc==ZOK){
  2775. wait_sync_completion(sc);
  2776. rc = sc->rc;
  2777. }
  2778. free_sync_completion(sc);
  2779. return rc;
  2780. }
  2781. int zoo_delete(zhandle_t *zh, const char *path, int version)
  2782. {
  2783. struct sync_completion *sc = alloc_sync_completion();
  2784. int rc;
  2785. if (!sc) {
  2786. return ZSYSTEMERROR;
  2787. }
  2788. rc=zoo_adelete(zh, path, version, SYNCHRONOUS_MARKER, sc);
  2789. if(rc==ZOK){
  2790. wait_sync_completion(sc);
  2791. rc = sc->rc;
  2792. }
  2793. free_sync_completion(sc);
  2794. return rc;
  2795. }
  2796. int zoo_exists(zhandle_t *zh, const char *path, int watch, struct Stat *stat)
  2797. {
  2798. return zoo_wexists(zh,path,watch?zh->watcher:0,zh->context,stat);
  2799. }
  2800. int zoo_wexists(zhandle_t *zh, const char *path,
  2801. watcher_fn watcher, void* watcherCtx, struct Stat *stat)
  2802. {
  2803. struct sync_completion *sc = alloc_sync_completion();
  2804. int rc;
  2805. if (!sc) {
  2806. return ZSYSTEMERROR;
  2807. }
  2808. rc=zoo_awexists(zh,path,watcher,watcherCtx,SYNCHRONOUS_MARKER, sc);
  2809. if(rc==ZOK){
  2810. wait_sync_completion(sc);
  2811. rc = sc->rc;
  2812. if (rc == 0&& stat) {
  2813. *stat = sc->u.stat;
  2814. }
  2815. }
  2816. free_sync_completion(sc);
  2817. return rc;
  2818. }
  2819. int zoo_get(zhandle_t *zh, const char *path, int watch, char *buffer,
  2820. int* buffer_len, struct Stat *stat)
  2821. {
  2822. return zoo_wget(zh,path,watch?zh->watcher:0,zh->context,
  2823. buffer,buffer_len,stat);
  2824. }
  2825. int zoo_wget(zhandle_t *zh, const char *path,
  2826. watcher_fn watcher, void* watcherCtx,
  2827. char *buffer, int* buffer_len, struct Stat *stat)
  2828. {
  2829. struct sync_completion *sc;
  2830. int rc=0;
  2831. if(buffer_len==NULL)
  2832. return ZBADARGUMENTS;
  2833. if((sc=alloc_sync_completion())==NULL)
  2834. return ZSYSTEMERROR;
  2835. sc->u.data.buffer = buffer;
  2836. sc->u.data.buff_len = *buffer_len;
  2837. rc=zoo_awget(zh, path, watcher, watcherCtx, SYNCHRONOUS_MARKER, sc);
  2838. if(rc==ZOK){
  2839. wait_sync_completion(sc);
  2840. rc = sc->rc;
  2841. if (rc == 0) {
  2842. if(stat)
  2843. *stat = sc->u.data.stat;
  2844. *buffer_len = sc->u.data.buff_len;
  2845. }
  2846. }
  2847. free_sync_completion(sc);
  2848. return rc;
  2849. }
  2850. int zoo_set(zhandle_t *zh, const char *path, const char *buffer, int buflen,
  2851. int version)
  2852. {
  2853. return zoo_set2(zh, path, buffer, buflen, version, 0);
  2854. }
  2855. int zoo_set2(zhandle_t *zh, const char *path, const char *buffer, int buflen,
  2856. int version, struct Stat *stat)
  2857. {
  2858. struct sync_completion *sc = alloc_sync_completion();
  2859. int rc;
  2860. if (!sc) {
  2861. return ZSYSTEMERROR;
  2862. }
  2863. rc=zoo_aset(zh, path, buffer, buflen, version, SYNCHRONOUS_MARKER, sc);
  2864. if(rc==ZOK){
  2865. wait_sync_completion(sc);
  2866. rc = sc->rc;
  2867. if (rc == 0 && stat) {
  2868. *stat = sc->u.stat;
  2869. }
  2870. }
  2871. free_sync_completion(sc);
  2872. return rc;
  2873. }
  2874. static int zoo_wget_children_(zhandle_t *zh, const char *path,
  2875. watcher_fn watcher, void* watcherCtx,
  2876. struct String_vector *strings)
  2877. {
  2878. struct sync_completion *sc = alloc_sync_completion();
  2879. int rc;
  2880. if (!sc) {
  2881. return ZSYSTEMERROR;
  2882. }
  2883. rc= zoo_awget_children (zh, path, watcher, watcherCtx, SYNCHRONOUS_MARKER, sc);
  2884. if(rc==ZOK){
  2885. wait_sync_completion(sc);
  2886. rc = sc->rc;
  2887. if (rc == 0) {
  2888. if (strings) {
  2889. *strings = sc->u.strs2;
  2890. } else {
  2891. deallocate_String_vector(&sc->u.strs2);
  2892. }
  2893. }
  2894. }
  2895. free_sync_completion(sc);
  2896. return rc;
  2897. }
  2898. static int zoo_wget_children2_(zhandle_t *zh, const char *path,
  2899. watcher_fn watcher, void* watcherCtx,
  2900. struct String_vector *strings, struct Stat *stat)
  2901. {
  2902. struct sync_completion *sc = alloc_sync_completion();
  2903. int rc;
  2904. if (!sc) {
  2905. return ZSYSTEMERROR;
  2906. }
  2907. rc= zoo_awget_children2(zh, path, watcher, watcherCtx, SYNCHRONOUS_MARKER, sc);
  2908. if(rc==ZOK){
  2909. wait_sync_completion(sc);
  2910. rc = sc->rc;
  2911. if (rc == 0) {
  2912. *stat = sc->u.strs_stat.stat2;
  2913. if (strings) {
  2914. *strings = sc->u.strs_stat.strs2;
  2915. } else {
  2916. deallocate_String_vector(&sc->u.strs_stat.strs2);
  2917. }
  2918. }
  2919. }
  2920. free_sync_completion(sc);
  2921. return rc;
  2922. }
  2923. int zoo_get_children(zhandle_t *zh, const char *path, int watch,
  2924. struct String_vector *strings)
  2925. {
  2926. return zoo_wget_children_(zh,path,watch?zh->watcher:0,zh->context,strings);
  2927. }
  2928. int zoo_wget_children(zhandle_t *zh, const char *path,
  2929. watcher_fn watcher, void* watcherCtx,
  2930. struct String_vector *strings)
  2931. {
  2932. return zoo_wget_children_(zh,path,watcher,watcherCtx,strings);
  2933. }
  2934. int zoo_get_children2(zhandle_t *zh, const char *path, int watch,
  2935. struct String_vector *strings, struct Stat *stat)
  2936. {
  2937. return zoo_wget_children2_(zh,path,watch?zh->watcher:0,zh->context,strings,stat);
  2938. }
  2939. int zoo_wget_children2(zhandle_t *zh, const char *path,
  2940. watcher_fn watcher, void* watcherCtx,
  2941. struct String_vector *strings, struct Stat *stat)
  2942. {
  2943. return zoo_wget_children2_(zh,path,watcher,watcherCtx,strings,stat);
  2944. }
  2945. int zoo_get_acl(zhandle_t *zh, const char *path, struct ACL_vector *acl,
  2946. struct Stat *stat)
  2947. {
  2948. struct sync_completion *sc = alloc_sync_completion();
  2949. int rc;
  2950. if (!sc) {
  2951. return ZSYSTEMERROR;
  2952. }
  2953. rc=zoo_aget_acl(zh, path, SYNCHRONOUS_MARKER, sc);
  2954. if(rc==ZOK){
  2955. wait_sync_completion(sc);
  2956. rc = sc->rc;
  2957. if (rc == 0&& stat) {
  2958. *stat = sc->u.acl.stat;
  2959. }
  2960. if (rc == 0) {
  2961. if (acl) {
  2962. *acl = sc->u.acl.acl;
  2963. } else {
  2964. deallocate_ACL_vector(&sc->u.acl.acl);
  2965. }
  2966. }
  2967. }
  2968. free_sync_completion(sc);
  2969. return rc;
  2970. }
  2971. int zoo_set_acl(zhandle_t *zh, const char *path, int version,
  2972. const struct ACL_vector *acl)
  2973. {
  2974. struct sync_completion *sc = alloc_sync_completion();
  2975. int rc;
  2976. if (!sc) {
  2977. return ZSYSTEMERROR;
  2978. }
  2979. rc=zoo_aset_acl(zh, path, version, (struct ACL_vector*)acl,
  2980. SYNCHRONOUS_MARKER, sc);
  2981. if(rc==ZOK){
  2982. wait_sync_completion(sc);
  2983. rc = sc->rc;
  2984. }
  2985. free_sync_completion(sc);
  2986. return rc;
  2987. }