memcachedplugin.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2014 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include "memcachedplugin.hpp"
  15. #include "eclrtl.hpp"
  16. #include "jexcept.hpp"
  17. #include "jstring.hpp"
  18. #include "jthread.hpp"
  19. #include <libmemcached/memcached.hpp>
  20. #include <libmemcached/util.h>
  21. #define MEMCACHED_VERSION "memcached plugin 1.0.0"
  22. ECL_MEMCACHED_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  23. {
  24. if (pb->size != sizeof(ECLPluginDefinitionBlock))
  25. return false;
  26. pb->magicVersion = PLUGIN_VERSION;
  27. pb->version = MEMCACHED_VERSION;
  28. pb->moduleName = "lib_memcached";
  29. pb->ECL = NULL;
  30. pb->flags = PLUGIN_IMPLICIT_MODULE;
  31. pb->description = "ECL plugin library for the C/C++ API libmemcached (http://libmemcached.org/)\n";
  32. return true;
  33. }
  34. namespace MemCachedPlugin {
  35. enum eclDataType {
  36. ECL_BOOLEAN,
  37. ECL_DATA,
  38. ECL_INTEGER,
  39. ECL_REAL,
  40. ECL_STRING,
  41. ECL_UTF8,
  42. ECL_UNICODE,
  43. ECL_UNSIGNED,
  44. ECL_NONE
  45. };
  46. const char * enumToStr(eclDataType type)
  47. {
  48. switch(type)
  49. {
  50. case ECL_BOOLEAN:
  51. return "BOOLEAN";
  52. case ECL_INTEGER:
  53. return "INTEGER";
  54. case ECL_UNSIGNED:
  55. return "UNSIGNED";
  56. case ECL_REAL:
  57. return "REAL";
  58. case ECL_STRING:
  59. return "STRING";
  60. case ECL_UTF8:
  61. return "UTF8";
  62. case ECL_UNICODE:
  63. return "UNICODE";
  64. case ECL_DATA:
  65. return "DATA";
  66. case ECL_NONE:
  67. return "Nonexistent";
  68. default:
  69. return "UNKNOWN";
  70. }
  71. }
  72. class MCached : public CInterface
  73. {
  74. public :
  75. MCached(ICodeContext * ctx, const char * _options);
  76. ~MCached();
  77. //set
  78. template <class type> void set(ICodeContext * ctx, const char * partitionKey, const char * key, type value, unsigned __int64 expire, eclDataType eclType);
  79. template <class type> void set(ICodeContext * ctx, const char * partitionKey, const char * key, size32_t valueLength, const type * value, unsigned __int64 expire, eclDataType eclType);
  80. //get
  81. template <class type> void get(ICodeContext * ctx, const char * partitionKey, const char * key, type & value, eclDataType eclType);
  82. template <class type> void get(ICodeContext * ctx, const char * partitionKey, const char * key, size_t & valueLength, type * & value, eclDataType eclType);
  83. void getVoidPtrLenPair(ICodeContext * ctx, const char * partitionKey, const char * key, size_t & valueLength, void * & value, eclDataType eclType);
  84. void clear(ICodeContext * ctx, unsigned when);
  85. bool exists(ICodeContext * ctx, const char * key, const char * partitionKey);
  86. void deleteKey(ICodeContext * ctx, const char * key, const char * partitionKey);
  87. eclDataType getKeyType(const char * key, const char * partitionKey);
  88. bool isSameConnection(const char * _options) const;
  89. private :
  90. void checkServersUp(ICodeContext * ctx);
  91. void assertOnError(memcached_return_t rc, const char * _msg);
  92. const char * appendIfKeyNotFoundMsg(memcached_return_t rc, const char * key, StringBuffer & target) const;
  93. void connect(ICodeContext * ctx);
  94. bool logErrorOnFail(ICodeContext * ctx, memcached_return_t rc, const char * _msg);
  95. void reportKeyTypeMismatch(ICodeContext * ctx, const char * key, uint32_t flag, eclDataType eclType);
  96. void * cpy(const char * src, size_t length);
  97. void logServerStats(ICodeContext * ctx);
  98. void init(ICodeContext * ctx);
  99. void invokePoolSecurity(ICodeContext * ctx);
  100. void invokeConnectionSecurity(ICodeContext * ctx);
  101. void setPoolSettings();
  102. void assertPool();//For internal purposes to insure correct order of the above processes and instantiation.
  103. private :
  104. memcached_st * connection;
  105. memcached_pool_st * pool;
  106. StringAttr options;
  107. bool alreadyInitialized;
  108. unsigned typeMismatchCount;
  109. };
  110. typedef Owned<MCached> OwnedMCached;
  111. static const unsigned MAX_TYPEMISMATCHCOUNT = 10;
  112. static __thread MCached * cachedConnection;
  113. static __thread ThreadTermFunc threadHookChain;
  114. static __thread bool threadHooked;
  115. //The following class is here to ensure destruction of the cachedConnection within the main thread
  116. //as this is not handled by the thread hook mechanism.
  117. static class mainThreadCachedConnection
  118. {
  119. public :
  120. mainThreadCachedConnection() { }
  121. ~mainThreadCachedConnection()
  122. {
  123. if (cachedConnection)
  124. {
  125. cachedConnection->Release();
  126. cachedConnection = NULL;
  127. }
  128. }
  129. } mainThread;
  130. static void releaseContext()
  131. {
  132. if (cachedConnection)
  133. {
  134. cachedConnection->Release();
  135. cachedConnection = NULL;
  136. }
  137. if (threadHookChain)
  138. {
  139. (*threadHookChain)();
  140. threadHookChain = NULL;
  141. }
  142. threadHooked = false;
  143. }
  144. MCached * createConnection(ICodeContext * ctx, const char * options)
  145. {
  146. if (!cachedConnection)
  147. {
  148. cachedConnection = new MemCachedPlugin::MCached(ctx, options);
  149. if (!threadHooked)
  150. {
  151. threadHookChain = addThreadTermFunc(releaseContext);
  152. threadHooked = true;
  153. }
  154. return LINK(cachedConnection);
  155. }
  156. if (cachedConnection->isSameConnection(options))
  157. return LINK(cachedConnection);
  158. cachedConnection->Release();
  159. cachedConnection = NULL;
  160. cachedConnection = new MemCachedPlugin::MCached(ctx, options);
  161. return LINK(cachedConnection);
  162. }
  163. //-------------------------------------------SET-----------------------------------------
  164. template<class type> void MSet(ICodeContext * ctx, const char * _options, const char * partitionKey, const char * key, type value, unsigned __int64 expire, eclDataType eclType)
  165. {
  166. OwnedMCached serverPool = createConnection(ctx, _options);
  167. serverPool->set(ctx, partitionKey, key, value, expire, eclType);
  168. }
  169. //Set pointer types
  170. template<class type> void MSet(ICodeContext * ctx, const char * _options, const char * partitionKey, const char * key, size32_t valueLength, const type * value, unsigned __int64 expire, eclDataType eclType)
  171. {
  172. OwnedMCached serverPool = createConnection(ctx, _options);
  173. serverPool->set(ctx, partitionKey, key, valueLength, value, expire, eclType);
  174. }
  175. //-------------------------------------------GET-----------------------------------------
  176. template<class type> void MGet(ICodeContext * ctx, const char * options, const char * partitionKey, const char * key, type & returnValue, eclDataType eclType)
  177. {
  178. OwnedMCached serverPool = createConnection(ctx, options);
  179. serverPool->get(ctx, partitionKey, key, returnValue, eclType);
  180. }
  181. template<class type> void MGet(ICodeContext * ctx, const char * options, const char * partitionKey, const char * key, size_t & returnLength, type * & returnValue, eclDataType eclType)
  182. {
  183. OwnedMCached serverPool = createConnection(ctx, options);
  184. serverPool->get(ctx, partitionKey, key, returnLength, returnValue, eclType);
  185. }
  186. void MGetVoidPtrLenPair(ICodeContext * ctx, const char * options, const char * partitionKey, const char * key, size_t & returnLength, void * & returnValue, eclDataType eclType)
  187. {
  188. OwnedMCached serverPool = createConnection(ctx, options);
  189. serverPool->getVoidPtrLenPair(ctx, partitionKey, key, returnLength, returnValue, eclType);
  190. }
  191. //----------------------------------SET----------------------------------------
  192. template<class type> void MemCachedPlugin::MCached::set(ICodeContext * ctx, const char * partitionKey, const char * key, type value, unsigned __int64 expire, eclDataType eclType)
  193. {
  194. const char * _value = reinterpret_cast<const char *>(&value);//Do this even for char * to prevent compiler complaining
  195. size_t partitionKeyLength = strlen(partitionKey);
  196. const char * msg = "'Set' request failed - ";
  197. if (partitionKeyLength)
  198. assertOnError(memcached_set_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key), _value, sizeof(value), (time_t)expire, (uint32_t)eclType), msg);
  199. else
  200. assertOnError(memcached_set(connection, key, strlen(key), _value, sizeof(value), (time_t)expire, (uint32_t)eclType), msg);
  201. }
  202. template<class type> void MemCachedPlugin::MCached::set(ICodeContext * ctx, const char * partitionKey, const char * key, size32_t valueLength, const type * value, unsigned __int64 expire, eclDataType eclType)
  203. {
  204. const char * _value = reinterpret_cast<const char *>(value);//Do this even for char * to prevent compiler complaining
  205. size_t partitionKeyLength = strlen(partitionKey);
  206. const char * msg = "'Set' request failed - ";
  207. if (partitionKeyLength)
  208. assertOnError(memcached_set_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key), _value, (size_t)(valueLength), (time_t)expire, (uint32_t)eclType), msg);
  209. else
  210. assertOnError(memcached_set(connection, key, strlen(key), _value, (size_t)(valueLength), (time_t)expire, (uint32_t)eclType), msg);
  211. }
  212. //----------------------------------GET----------------------------------------
  213. template<class type> void MemCachedPlugin::MCached::get(ICodeContext * ctx, const char * partitionKey, const char * key, type & returnValue, eclDataType eclType)
  214. {
  215. uint32_t flag = 0;
  216. size_t returnLength = 0;
  217. memcached_return_t rc;
  218. OwnedMalloc<char> value;
  219. size_t partitionKeyLength = strlen(partitionKey);
  220. if (partitionKeyLength)
  221. value.setown(memcached_get_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key), &returnLength, &flag, &rc));
  222. else
  223. value.setown(memcached_get(connection, key, strlen(key), &returnLength, &flag, &rc));
  224. StringBuffer keyMsg = "'Get<type>' request failed - ";
  225. assertOnError(rc, appendIfKeyNotFoundMsg(rc, key, keyMsg));
  226. reportKeyTypeMismatch(ctx, key, flag, eclType);
  227. if (sizeof(type)!=returnLength)
  228. {
  229. VStringBuffer msg("MemCachedPlugin: ERROR - Requested type of different size (%uB) from that stored (%uB). Check logs for more information.", (unsigned)sizeof(type), (unsigned)returnLength);
  230. rtlFail(0, msg.str());
  231. }
  232. memcpy(&returnValue, value, returnLength);
  233. }
  234. template<class type> void MemCachedPlugin::MCached::get(ICodeContext * ctx, const char * partitionKey, const char * key, size_t & returnLength, type * & returnValue, eclDataType eclType)
  235. {
  236. uint32_t flag = 0;
  237. memcached_return_t rc;
  238. OwnedMalloc<char> value;
  239. size_t partitionKeyLength = strlen(partitionKey);
  240. if (partitionKeyLength)
  241. value.setown(memcached_get_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key), &returnLength, &flag, &rc));
  242. else
  243. value.setown(memcached_get(connection, key, strlen(key), &returnLength, &flag, &rc));
  244. StringBuffer keyMsg = "'Get<type>' request failed - ";
  245. assertOnError(rc, appendIfKeyNotFoundMsg(rc, key, keyMsg));
  246. reportKeyTypeMismatch(ctx, key, flag, eclType);
  247. returnValue = reinterpret_cast<type*>(cpy(value, returnLength));
  248. }
  249. void MemCachedPlugin::MCached::getVoidPtrLenPair(ICodeContext * ctx, const char * partitionKey, const char * key, size_t & returnLength, void * & returnValue, eclDataType eclType)
  250. {
  251. uint32_t flag = 0;
  252. size_t returnValueLength = 0;
  253. memcached_return_t rc;
  254. OwnedMalloc<char> value;
  255. size_t partitionKeyLength = strlen(partitionKey);
  256. if (partitionKeyLength)
  257. value.setown(memcached_get_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key), &returnValueLength, &flag, &rc));
  258. else
  259. value.setown(memcached_get(connection, key, strlen(key), &returnValueLength, &flag, &rc));
  260. StringBuffer keyMsg = "'Get<type>' request failed - ";
  261. assertOnError(rc, appendIfKeyNotFoundMsg(rc, key, keyMsg));
  262. reportKeyTypeMismatch(ctx, key, flag, eclType);
  263. returnLength = (size32_t)(returnValueLength);
  264. returnValue = reinterpret_cast<void*>(cpy(value, returnLength));
  265. }
  266. MemCachedPlugin::MCached::MCached(ICodeContext * ctx, const char * _options)
  267. {
  268. alreadyInitialized = false;
  269. connection = NULL;
  270. pool = NULL;
  271. options.set(_options);
  272. typeMismatchCount = 0;
  273. #if (LIBMEMCACHED_VERSION_HEX<0x53000)
  274. memcached_st *memc = memcached_create(NULL);
  275. memcached_return_t rc;
  276. memcached_server_st *servers = NULL;
  277. try
  278. {
  279. unsigned pool_min = 1;
  280. unsigned pool_max = 1;
  281. StringArray optionStrings;
  282. optionStrings.appendList(_options, " ");
  283. ForEachItemIn(idx, optionStrings)
  284. {
  285. const char *opt = optionStrings.item(idx);
  286. if (strncmp(opt, "--SERVER=", 9) ==0)
  287. {
  288. opt += 9;
  289. StringArray splitPort;
  290. splitPort.appendList(opt, ":");
  291. unsigned port;
  292. if (splitPort.ordinality()==2)
  293. port = atoi(splitPort.item(1));
  294. else
  295. port = 11211;
  296. servers = memcached_server_list_append(NULL, splitPort.item(0), port, &rc);
  297. assertOnError(rc, "memcached_server_list_append failed - ");
  298. }
  299. else if (strncmp(opt, "--POOL-MIN=", 11) ==0)
  300. pool_min = atoi(opt+11);
  301. else if (strncmp(opt, "--POOL-MAX=", 11) ==0)
  302. pool_max = atoi(opt+11);
  303. else
  304. {
  305. VStringBuffer err("MemCachedPlugin: unsupported option string %s", opt);
  306. rtlFail(0, err.str());
  307. }
  308. }
  309. if (!servers)
  310. rtlFail(0, "No servers specified");
  311. rc = memcached_server_push(memc, servers);
  312. memcached_server_list_free(servers);
  313. assertOnError(rc, "memcached_server_push failed - ");
  314. pool = memcached_pool_create(memc, pool_min, pool_max); // takes ownership of memc
  315. }
  316. catch (...)
  317. {
  318. if (servers)
  319. memcached_server_list_free(servers);
  320. if (memc)
  321. memcached_free(memc);
  322. throw;
  323. }
  324. #else
  325. pool = memcached_pool(_options, strlen(_options));
  326. #endif
  327. assertPool();
  328. setPoolSettings();
  329. invokePoolSecurity(ctx);
  330. connect(ctx);
  331. checkServersUp(ctx);
  332. }
  333. //-----------------------------------------------------------------------------
  334. MemCachedPlugin::MCached::~MCached()
  335. {
  336. if (pool)
  337. {
  338. #if (LIBMEMCACHED_VERSION_HEX<0x53000)
  339. memcached_pool_push(pool, connection);
  340. #else
  341. memcached_pool_release(pool, connection);
  342. #endif
  343. connection = NULL;//For safety (from changing this destructor) as not implicit in either the above or below.
  344. memcached_st *memc = memcached_pool_destroy(pool);
  345. if (memc)
  346. memcached_free(memc);
  347. }
  348. else if (connection)//This should never be needed but just in case.
  349. {
  350. memcached_free(connection);
  351. }
  352. }
  353. bool MemCachedPlugin::MCached::isSameConnection(const char * _options) const
  354. {
  355. if (!_options)
  356. return false;
  357. return stricmp(options.get(), _options) == 0;
  358. }
  359. void MemCachedPlugin::MCached::assertPool()
  360. {
  361. if (!pool)
  362. {
  363. StringBuffer msg = "Memcached Plugin: Failed to instantiate server pool with:";
  364. msg.newline().append(options);
  365. rtlFail(0, msg.str());
  366. }
  367. }
  368. void * MemCachedPlugin::MCached::cpy(const char * src, size_t length)
  369. {
  370. void * value = rtlMalloc(length);
  371. return memcpy(value, src, length);
  372. }
  373. void MemCachedPlugin::MCached::checkServersUp(ICodeContext * ctx)
  374. {
  375. memcached_return_t rc;
  376. char * args = NULL;
  377. OwnedMalloc<memcached_stat_st> stats;
  378. stats.setown(memcached_stat(connection, args, &rc));
  379. assertex(stats);
  380. unsigned int numberOfServers = memcached_server_count(connection);
  381. unsigned int numberOfServersDown = 0;
  382. for (unsigned i = 0; i < numberOfServers; ++i)
  383. {
  384. if (stats[i].pid == -1)//perhaps not the best test?
  385. {
  386. numberOfServersDown++;
  387. VStringBuffer msg("Memcached Plugin: Failed connecting to entry %u\nwithin the server list: %s", i+1, options.str());
  388. ctx->logString(msg.str());
  389. }
  390. }
  391. if (numberOfServersDown == numberOfServers)
  392. rtlFail(0,"Memcached Plugin: Failed connecting to ALL servers. Check memcached on all servers and \"memcached -B ascii\" not used.");
  393. //check memcached version homogeneity
  394. for (unsigned i = 0; i < numberOfServers-1; ++i)
  395. {
  396. if (strcmp(stats[i].version, stats[i+1].version) != 0)
  397. ctx->logString("Memcached Plugin: Inhomogeneous versions of memcached across servers.");
  398. }
  399. }
  400. bool MemCachedPlugin::MCached::logErrorOnFail(ICodeContext * ctx, memcached_return_t rc, const char * _msg)
  401. {
  402. if (rc == MEMCACHED_SUCCESS)
  403. return false;
  404. VStringBuffer msg("Memcached Plugin: %s%s", _msg, memcached_strerror(connection, rc));
  405. ctx->logString(msg.str());
  406. return true;
  407. }
  408. void MemCachedPlugin::MCached::assertOnError(memcached_return_t rc, const char * _msg)
  409. {
  410. if (rc != MEMCACHED_SUCCESS)
  411. {
  412. VStringBuffer msg("Memcached Plugin: %s%s", _msg, memcached_strerror(connection, rc));
  413. rtlFail(0, msg.str());
  414. }
  415. }
  416. const char * MemCachedPlugin::MCached::appendIfKeyNotFoundMsg(memcached_return_t rc, const char * key, StringBuffer & target) const
  417. {
  418. if (rc == MEMCACHED_NOTFOUND)
  419. target.append("(key: '").append(key).append("') ");
  420. return target.str();
  421. }
  422. void MemCachedPlugin::MCached::clear(ICodeContext * ctx, unsigned when)
  423. {
  424. //NOTE: memcached_flush is the actual cache flush/clear/delete and not an io buffer flush.
  425. assertOnError(memcached_flush(connection, (time_t)(when)), "'Clear' request failed - ");
  426. }
  427. bool MemCachedPlugin::MCached::exists(ICodeContext * ctx, const char * key, const char * partitionKey)
  428. {
  429. #if (LIBMEMCACHED_VERSION_HEX<0x53000)
  430. throw makeStringException(0, "memcached_exist not supported in this version of libmemcached");
  431. #else
  432. memcached_return_t rc;
  433. size_t partitionKeyLength = strlen(partitionKey);
  434. if (partitionKeyLength)
  435. rc = memcached_exist_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key));
  436. else
  437. rc = memcached_exist(connection, key, strlen(key));
  438. if (rc == MEMCACHED_NOTFOUND)
  439. return false;
  440. else
  441. {
  442. assertOnError(rc, "'Exists' request failed - ");
  443. return true;
  444. }
  445. #endif
  446. }
  447. void MemCachedPlugin::MCached::deleteKey(ICodeContext * ctx, const char * key, const char * partitionKey)
  448. {
  449. memcached_return_t rc;
  450. size_t partitionKeyLength = strlen(partitionKey);
  451. if (partitionKeyLength)
  452. rc = memcached_delete_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key), (time_t)0);
  453. else
  454. rc = memcached_delete(connection, key, strlen(key), (time_t)0);
  455. assertOnError(rc, "'Delete' request failed - ");
  456. }
  457. MemCachedPlugin::eclDataType MemCachedPlugin::MCached::getKeyType(const char * key, const char * partitionKey)
  458. {
  459. size_t returnValueLength;
  460. uint32_t flag;
  461. memcached_return_t rc;
  462. size_t partitionKeyLength = strlen(partitionKey);
  463. if (partitionKeyLength)
  464. memcached_get_by_key(connection, partitionKey, partitionKeyLength, key, strlen(key), &returnValueLength, &flag, &rc);
  465. else
  466. memcached_get(connection, key, strlen(key), &returnValueLength, &flag, &rc);
  467. if (rc == MEMCACHED_SUCCESS)
  468. return (MemCachedPlugin::eclDataType)(flag);
  469. else if (rc == MEMCACHED_NOTFOUND)
  470. return ECL_NONE;
  471. else
  472. {
  473. VStringBuffer msg("Memcached Plugin: 'KeyType' request failed - %s", memcached_strerror(connection, rc));
  474. rtlFail(0, msg.str());
  475. }
  476. }
  477. void MemCachedPlugin::MCached::reportKeyTypeMismatch(ICodeContext * ctx, const char * key, uint32_t flag, eclDataType eclType)
  478. {
  479. if (flag && eclType != ECL_DATA && flag != eclType)
  480. {
  481. VStringBuffer msg("Memcached Plugin: The requested key '%s' is of type %s, not %s as requested.", key, enumToStr((eclDataType)(flag)), enumToStr(eclType));
  482. if (++typeMismatchCount <= MAX_TYPEMISMATCHCOUNT)
  483. ctx->logString(msg.str());
  484. }
  485. }
  486. void MemCachedPlugin::MCached::logServerStats(ICodeContext * ctx)
  487. {
  488. //NOTE: errors are ignored here so that at least some info is reported, such as non-connection related libmemcached version numbers
  489. memcached_return_t rc;
  490. char * args = NULL;
  491. OwnedMalloc<memcached_stat_st> stats;
  492. stats.setown(memcached_stat(connection, args, &rc));
  493. OwnedMalloc<char*> keys;
  494. keys.setown(memcached_stat_get_keys(connection, stats, &rc));
  495. unsigned int numberOfServers = memcached_server_count(connection);
  496. for (unsigned int i = 0; i < numberOfServers; ++i)
  497. {
  498. StringBuffer statsStr;
  499. unsigned j = 0;
  500. do
  501. {
  502. OwnedMalloc<char> value;
  503. value.setown(memcached_stat_get_value(connection, &stats[i], keys[j], &rc));
  504. statsStr.newline().append("libmemcached server stat - ").append(keys[j]).append(":").append(value);
  505. } while (keys[++j]);
  506. statsStr.newline().append("libmemcached client stat - libmemcached version:").append(memcached_lib_version());
  507. ctx->logString(statsStr.str());
  508. }
  509. }
  510. void MemCachedPlugin::MCached::init(ICodeContext * ctx)
  511. {
  512. logServerStats(ctx);
  513. }
  514. void MemCachedPlugin::MCached::setPoolSettings()
  515. {
  516. assertPool();
  517. const char * msg = "memcached_pool_behavior_set failed - ";
  518. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_HASH_WITH_PREFIX_KEY, 1), msg);//key set in invokeConnectionSecurity. Only hashed with keys and not partitionKeys
  519. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_KETAMA, 1), msg);//NOTE: alias of MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA amongst others.
  520. memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_USE_UDP, 0); // Note that this fails on early versions of libmemcached, so ignore result
  521. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, 1), msg);
  522. #if (LIBMEMCACHED_VERSION_HEX>=0x50000)
  523. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_REMOVE_FAILED_SERVERS, 1), msg);
  524. #endif
  525. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_NO_BLOCK, 0), msg);
  526. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_CONNECT_TIMEOUT, 1000), msg);//units of ms.
  527. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_SND_TIMEOUT, 1000000), msg);//units of mu-s.
  528. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, 1000000), msg);//units of mu-s.
  529. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_BUFFER_REQUESTS, 0), msg);// Buffering does not work with the ecl runtime paradigm
  530. }
  531. void MemCachedPlugin::MCached::invokePoolSecurity(ICodeContext * ctx)
  532. {
  533. assertPool();
  534. assertOnError(memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1), "memcached_pool_behavior_set failed - ");
  535. }
  536. void MemCachedPlugin::MCached::invokeConnectionSecurity(ICodeContext * ctx)
  537. {
  538. //NOTE: Whether to assert or just report? This depends on when this is called. If before checkServersUp() and
  539. //a server is down, it will cause the following to fail if asserted with only a 'poor' libmemcached error message.
  540. //Reporting means that these 'security' measures may not be carried out. Moving checkServersUp() to here is probably the best
  541. //soln. however, this comes with extra overhead.
  542. logErrorOnFail(ctx, memcached_verbosity(connection, (uint32_t)(0)), "memcached_verbosity=0 failed - ");
  543. }
  544. void MemCachedPlugin::MCached::connect(ICodeContext * ctx)
  545. {
  546. assertPool();
  547. if (connection)
  548. #if (LIBMEMCACHED_VERSION_HEX<0x53000)
  549. memcached_pool_push(pool, connection);
  550. #else
  551. memcached_pool_release(pool, connection);
  552. #endif
  553. memcached_return_t rc;
  554. #if (LIBMEMCACHED_VERSION_HEX<0x53000)
  555. connection = memcached_pool_pop(pool, (struct timespec *)0 , &rc);
  556. #else
  557. connection = memcached_pool_fetch(pool, (struct timespec *)0 , &rc);
  558. #endif
  559. invokeConnectionSecurity(ctx);
  560. if (!alreadyInitialized)//Do this now rather than after assert. Better to have something even if it could be jiberish.
  561. {
  562. init(ctx);//doesn't necessarily initialize anything, instead outputs specs etc for debugging
  563. alreadyInitialized = true;
  564. }
  565. assertOnError(rc, "memcached_pool_pop failed - ");
  566. }
  567. //--------------------------------------------------------------------------------
  568. // ECL SERVICE ENTRYPOINTS
  569. //--------------------------------------------------------------------------------
  570. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MClear(ICodeContext * ctx, const char * options)
  571. {
  572. OwnedMCached serverPool = MemCachedPlugin::createConnection(ctx, options);
  573. serverPool->clear(ctx, 0);
  574. }
  575. ECL_MEMCACHED_API bool ECL_MEMCACHED_CALL MExists(ICodeContext * ctx, const char * key, const char * options, const char * partitionKey)
  576. {
  577. OwnedMCached serverPool = MemCachedPlugin::createConnection(ctx, options);
  578. return serverPool->exists(ctx, key, partitionKey);
  579. }
  580. ECL_MEMCACHED_API const char * ECL_MEMCACHED_CALL MKeyType(ICodeContext * ctx, const char * key, const char * options, const char * partitionKey)
  581. {
  582. OwnedMCached serverPool = MemCachedPlugin::createConnection(ctx, options);
  583. const char * keyType = enumToStr(serverPool->getKeyType(key, partitionKey));
  584. return keyType;
  585. }
  586. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MDelete(ICodeContext * ctx, const char * key, const char * options, const char * partitionKey)
  587. {
  588. OwnedMCached serverPool = MemCachedPlugin::createConnection(ctx, options);
  589. serverPool->deleteKey(ctx, key, partitionKey);
  590. }
  591. //-----------------------------------SET------------------------------------------
  592. //NOTE: These were all overloaded by 'value' type, however; this caused problems since ecl implicitly casts and doesn't type check.
  593. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSet(ICodeContext * ctx, const char * key, size32_t valueLength, const char * value, const char * options, const char * partitionKey, unsigned __int64 expire /* = 0 (ECL default)*/)
  594. {
  595. MemCachedPlugin::MSet(ctx, options, partitionKey, key, valueLength, value, expire, MemCachedPlugin::ECL_STRING);
  596. }
  597. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSet(ICodeContext * ctx, const char * key, size32_t valueLength, const UChar * value, const char * options, const char * partitionKey, unsigned __int64 expire /* = 0 (ECL default)*/)
  598. {
  599. MemCachedPlugin::MSet(ctx, options, partitionKey, key, (valueLength)*sizeof(UChar), value, expire, MemCachedPlugin::ECL_UNICODE);
  600. }
  601. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSet(ICodeContext * ctx, const char * key, signed __int64 value, const char * options, const char * partitionKey, unsigned __int64 expire /* = 0 (ECL default)*/)
  602. {
  603. MemCachedPlugin::MSet(ctx, options, partitionKey, key, value, expire, MemCachedPlugin::ECL_INTEGER);
  604. }
  605. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSet(ICodeContext * ctx, const char * key, unsigned __int64 value, const char * options, const char * partitionKey, unsigned __int64 expire /* = 0 (ECL default)*/)
  606. {
  607. MemCachedPlugin::MSet(ctx, options, partitionKey, key, value, expire, MemCachedPlugin::ECL_UNSIGNED);
  608. }
  609. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSet(ICodeContext * ctx, const char * key, double value, const char * options, const char * partitionKey, unsigned __int64 expire /* = 0 (ECL default)*/)
  610. {
  611. MemCachedPlugin::MSet(ctx, options, partitionKey, key, value, expire, MemCachedPlugin::ECL_REAL);
  612. }
  613. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSet(ICodeContext * ctx, const char * key, bool value, const char * options, const char * partitionKey, unsigned __int64 expire)
  614. {
  615. MemCachedPlugin::MSet(ctx, options, partitionKey, key, value, expire, MemCachedPlugin::ECL_BOOLEAN);
  616. }
  617. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSetData(ICodeContext * ctx, const char * key, size32_t valueLength, const void * value, const char * options, const char * partitionKey, unsigned __int64 expire)
  618. {
  619. MemCachedPlugin::MSet(ctx, options, partitionKey, key, valueLength, value, expire, MemCachedPlugin::ECL_DATA);
  620. }
  621. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MSetUtf8(ICodeContext * ctx, const char * key, size32_t valueLength, const char * value, const char * options, const char * partitionKey, unsigned __int64 expire /* = 0 (ECL default)*/)
  622. {
  623. MemCachedPlugin::MSet(ctx, options, partitionKey, key, rtlUtf8Size(valueLength, value), value, expire, MemCachedPlugin::ECL_UTF8);
  624. }
  625. //-------------------------------------GET----------------------------------------
  626. ECL_MEMCACHED_API bool ECL_MEMCACHED_CALL MGetBool(ICodeContext * ctx, const char * key, const char * options, const char * partitionKey)
  627. {
  628. bool value;
  629. MemCachedPlugin::MGet(ctx, options, partitionKey, key, value, MemCachedPlugin::ECL_BOOLEAN);
  630. return value;
  631. }
  632. ECL_MEMCACHED_API double ECL_MEMCACHED_CALL MGetDouble(ICodeContext * ctx, const char * key, const char * options, const char * partitionKey)
  633. {
  634. double value;
  635. MemCachedPlugin::MGet(ctx, options, partitionKey, key, value, MemCachedPlugin::ECL_REAL);
  636. return value;
  637. }
  638. ECL_MEMCACHED_API signed __int64 ECL_MEMCACHED_CALL MGetInt8(ICodeContext * ctx, const char * key, const char * options, const char * partitionKey)
  639. {
  640. signed __int64 value;
  641. MemCachedPlugin::MGet(ctx, options, partitionKey, key, value, MemCachedPlugin::ECL_INTEGER);
  642. return value;
  643. }
  644. ECL_MEMCACHED_API unsigned __int64 ECL_MEMCACHED_CALL MGetUint8(ICodeContext * ctx, const char * key, const char * options, const char * partitionKey)
  645. {
  646. unsigned __int64 value;
  647. MemCachedPlugin::MGet(ctx, options, partitionKey, key, value, MemCachedPlugin::ECL_UNSIGNED);
  648. return value;
  649. }
  650. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MGetStr(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, const char * options, const char * partitionKey)
  651. {
  652. size_t _returnLength;
  653. MemCachedPlugin::MGet(ctx, options, partitionKey, key, _returnLength, returnValue, MemCachedPlugin::ECL_STRING);
  654. returnLength = static_cast<size32_t>(_returnLength);
  655. }
  656. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MGetUChar(ICodeContext * ctx, size32_t & returnLength, UChar * & returnValue, const char * key, const char * options, const char * partitionKey)
  657. {
  658. size_t _returnSize;
  659. MemCachedPlugin::MGet(ctx, options, partitionKey, key, _returnSize, returnValue, MemCachedPlugin::ECL_UNICODE);
  660. returnLength = static_cast<size32_t>(_returnSize/sizeof(UChar));
  661. }
  662. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MGetUtf8(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, const char * options, const char * partitionKey)
  663. {
  664. size_t returnSize;
  665. MemCachedPlugin::MGet(ctx, options, partitionKey, key, returnSize, returnValue, MemCachedPlugin::ECL_UTF8);
  666. returnLength = static_cast<size32_t>(rtlUtf8Length(returnSize, returnValue));
  667. }
  668. ECL_MEMCACHED_API void ECL_MEMCACHED_CALL MGetData(ICodeContext * ctx, size32_t & returnLength, void * & returnValue, const char * key, const char * options, const char * partitionKey)
  669. {
  670. size_t _returnLength;
  671. MemCachedPlugin::MGetVoidPtrLenPair(ctx, options, partitionKey, key, _returnLength, returnValue, MemCachedPlugin::ECL_DATA);
  672. returnLength = static_cast<size32_t>(_returnLength);
  673. }
  674. }//close namespace