redis.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2015 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 "jthread.hpp"
  15. #include "eclrtl.hpp"
  16. #include "jstring.hpp"
  17. #include "jmutex.hpp"
  18. #include "redis.hpp"
  19. #include "hiredis/hiredis.h"
  20. #define REDIS_VERSION "redis plugin 1.0.0"
  21. ECL_REDIS_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  22. {
  23. if (pb->size != sizeof(ECLPluginDefinitionBlock))
  24. return false;
  25. pb->magicVersion = PLUGIN_VERSION;
  26. pb->version = REDIS_VERSION;
  27. pb->moduleName = "lib_redis";
  28. pb->ECL = NULL;
  29. pb->flags = PLUGIN_IMPLICIT_MODULE;
  30. pb->description = "ECL plugin library for the C API hiredis\n";
  31. return true;
  32. }
  33. namespace RedisPlugin {
  34. class Connection;
  35. static const char * REDIS_LOCK_PREFIX = "redis_ecl_lock";
  36. static __thread Connection * cachedConnection = nullptr;
  37. static __thread Connection * cachedPubConnection = nullptr;//database should always = 0
  38. #if HIREDIS_VERSION_OK_FOR_CACHING
  39. static CriticalSection critsec;
  40. static __thread ThreadTermFunc threadHookChain = nullptr;
  41. static __thread bool threadHooked = false;
  42. #define NO_CONNECTION_CACHING 0
  43. #define ALLOW_CONNECTION_CACHING 1
  44. #define CACHE_ALL_CONNECTIONS 2
  45. static int connectionCachingLevel = ALLOW_CONNECTION_CACHING;
  46. static std::atomic<bool> connectionCachingLevelChecked(false);
  47. #endif
  48. static void * allocateAndCopy(const void * src, size_t size)
  49. {
  50. return memcpy(rtlMalloc(size), src, size);
  51. }
  52. static StringBuffer & appendExpire(StringBuffer & buffer, unsigned expire)
  53. {
  54. if (expire > 0)
  55. buffer.append(" PX ").append(expire);
  56. return buffer;
  57. }
  58. class Reply : public CInterface
  59. {
  60. public :
  61. inline Reply() : reply(NULL) { };
  62. inline Reply(void * _reply) : reply((redisReply*)_reply) { }
  63. inline Reply(redisReply * _reply) : reply(_reply) { }
  64. inline ~Reply()
  65. {
  66. if (reply)
  67. freeReplyObject(reply);
  68. }
  69. static Reply * createReply(void * _reply) { return new Reply(_reply); }
  70. inline const redisReply * query() const { return reply; }
  71. void setClear(void * _reply) { setClear((redisReply*)_reply); }
  72. void setClear(redisReply * _reply)
  73. {
  74. if (reply)
  75. freeReplyObject(reply);
  76. reply = _reply;
  77. }
  78. private :
  79. redisReply * reply;
  80. };
  81. typedef Owned<RedisPlugin::Reply> OwnedReply;
  82. class TimeoutHandler
  83. {
  84. public :
  85. TimeoutHandler(unsigned _timeout) : timeout(_timeout), t0(msTick()) { }
  86. inline void reset(unsigned _timeout) { timeout = _timeout; t0 = msTick(); }
  87. unsigned timeLeft() const
  88. {
  89. unsigned dt = msTick() - t0;
  90. if (dt < timeout)
  91. return timeout - dt;
  92. return 0;
  93. }
  94. inline unsigned getTimeout() { return timeout; }
  95. private :
  96. unsigned timeout;
  97. unsigned t0;
  98. };
  99. class Connection : public CInterface
  100. {
  101. public :
  102. Connection(ICodeContext * ctx, const char * _options, int database, const char * password, unsigned _timeout);
  103. Connection(ICodeContext * ctx, const char * _options, const char * _ip, int _port, unsigned _serverIpPortPasswordHash, int _database, const char * password, unsigned _timeout);
  104. ~Connection()
  105. {
  106. if (context)
  107. redisFree(context);
  108. }
  109. static Connection * createConnection(ICodeContext * ctx, Connection * & _cachedConnection, const char * options, int database, const char * password, unsigned _timeout, bool cacheConnections);
  110. //set
  111. template <class type> void set(ICodeContext * ctx, const char * key, type value, unsigned expire);
  112. template <class type> void set(ICodeContext * ctx, const char * key, size32_t valueSize, const type * value, unsigned expire);
  113. //get
  114. template <class type> void get(ICodeContext * ctx, const char * key, type & value);
  115. template <class type> void get(ICodeContext * ctx, const char * key, size_t & valueSize, type * & value);
  116. //-------------------------------LOCKING------------------------------------------------
  117. void lockSet(ICodeContext * ctx, const char * key, size32_t valueSize, const char * value, unsigned expire);
  118. void lockGet(ICodeContext * ctx, const char * key, size_t & valueSize, char * & value, const char * password, unsigned expire);
  119. void unlock(ICodeContext * ctx, const char * key);
  120. //--------------------------------------------------------------------------------------
  121. //-------------------------------PUB/SUB------------------------------------------------
  122. unsigned __int64 publish(ICodeContext * ctx, const char * keyOrChannel, size32_t messageSize, const char * message, int _database, bool lockedKey);
  123. void subscribe(ICodeContext * ctx, const char * keyOrChannel, size_t & messageSize, char * & message, int _database, bool lockedKey);
  124. //--------------------------------------------------------------------------------------
  125. void persist(ICodeContext * ctx, const char * key);
  126. void expire(ICodeContext * ctx, const char * key, unsigned _expire);
  127. void del(ICodeContext * ctx, const char * key);
  128. void clear(ICodeContext * ctx);
  129. unsigned __int64 dbSize(ICodeContext * ctx);
  130. bool exists(ICodeContext * ctx, const char * key);
  131. protected :
  132. void redisSetTimeout();
  133. void redisConnect();
  134. unsigned timeLeft();
  135. void parseOptions(ICodeContext * ctx, const char * _options);
  136. void connect(ICodeContext * ctx, int _database, const char * password);
  137. void selectDB(ICodeContext * ctx, int _database);
  138. void readReply(Reply * reply);
  139. void readReplyAndAssert(Reply * reply, const char * msg);
  140. void readReplyAndAssertWithCmdMsg(Reply * reply, const char * msg, const char * key = NULL);
  141. void assertKey(const redisReply * reply, const char * key);
  142. void assertAuthorization(const redisReply * reply);
  143. void assertOnError(const redisReply * reply, const char * _msg);
  144. void assertOnErrorWithCmdMsg(const redisReply * reply, const char * cmd, const char * key = NULL);
  145. void assertConnection(const char * _msg);
  146. void assertConnectionWithCmdMsg(const char * cmd, const char * key = NULL);
  147. void fail(const char * cmd, const char * errmsg, const char * key = NULL);
  148. void * redisCommand(redisContext * context, const char * format, ...);
  149. #if HIREDIS_VERSION_OK_FOR_CACHING
  150. static unsigned hashServerIpPortPassword(ICodeContext * ctx, const char * _options, const char * password);
  151. bool isSameConnection(ICodeContext * ctx, const char * _options, const char * password) const;
  152. void reset(ICodeContext * ctx, const char * password, unsigned _timeout);
  153. #endif
  154. //-------------------------------LOCKING------------------------------------------------
  155. void handleLockOnSet(ICodeContext * ctx, const char * key, const char * value, size_t size, unsigned expire);
  156. void handleLockOnGet(ICodeContext * ctx, const char * key, MemoryAttr * retVal, const char * password, unsigned expire);
  157. void encodeChannel(StringBuffer & channel, const char * key, int _database) const;
  158. bool noScript(const redisReply * reply) const;
  159. bool lock(ICodeContext * ctx, const char * key, const char * channel, unsigned expire);
  160. //--------------------------------------------------------------------------------------
  161. protected :
  162. redisContext * context = nullptr;
  163. StringAttr options;
  164. StringAttr ip; //The default is set in parseOptions as "localhost"
  165. unsigned serverIpPortPasswordHash;
  166. int port = 6379; //Default redis-server port
  167. TimeoutHandler timeout;
  168. int database = 0; //NOTE: redis stores the maximum number of dbs as an 'int'.
  169. };
  170. #if HIREDIS_VERSION_OK_FOR_CACHING
  171. static void releaseContext()
  172. {
  173. if (cachedConnection)
  174. {
  175. cachedConnection->Release();
  176. cachedConnection = NULL;
  177. }
  178. if (cachedPubConnection)
  179. {
  180. cachedPubConnection->Release();
  181. cachedPubConnection = NULL;
  182. }
  183. if (threadHookChain)
  184. {
  185. (*threadHookChain)();
  186. threadHookChain = NULL;
  187. }
  188. threadHooked = false;
  189. }
  190. //The following class is here to ensure destruction of the cachedConnection within the main thread
  191. //as this is not handled by the thread hook mechanism.
  192. static class MainThreadCachedConnection
  193. {
  194. public :
  195. MainThreadCachedConnection() { }
  196. ~MainThreadCachedConnection() { releaseContext(); }
  197. } mainThread;
  198. #endif
  199. Connection::Connection(ICodeContext * ctx, const char * _options, int _database, const char * password, unsigned _timeout)
  200. : timeout(_timeout), serverIpPortPasswordHash(0)
  201. {
  202. #if HIREDIS_VERSION_OK_FOR_CACHING
  203. serverIpPortPasswordHash = hashServerIpPortPassword(ctx, _options, password);
  204. #endif
  205. options.set(_options, strlen(_options));
  206. parseOptions(ctx, _options);
  207. connect(ctx, _database, password);
  208. }
  209. Connection::Connection(ICodeContext * ctx, const char * _options, const char * _ip, int _port, unsigned _serverIpPortPasswordHash, int _database, const char * password, unsigned _timeout)
  210. : timeout(_timeout), serverIpPortPasswordHash(_serverIpPortPasswordHash)
  211. {
  212. port = _port;
  213. options.set(_options, strlen(_options));
  214. ip.set(_ip, strlen(_ip));
  215. connect(ctx, _database, password);
  216. }
  217. void Connection::redisConnect()
  218. {
  219. if (timeout.getTimeout() == 0)
  220. context = ::redisConnect(ip.str(), port);
  221. else
  222. {
  223. int _timeLeft = (int) timeLeft();
  224. struct timeval to = { _timeLeft/1000, (_timeLeft%1000)*1000 };
  225. context = ::redisConnectWithTimeout(ip.str(), port, to);
  226. }
  227. assertConnection("connection");
  228. }
  229. void Connection::connect(ICodeContext * ctx, int _database, const char * password)
  230. {
  231. redisConnect();
  232. //The following is the dissemination of the two methods authenticate(ctx, password) & selectDB(ctx, _database)
  233. //such that they may be pipelined to save an extra round trip to the server and back.
  234. if (password && *password)
  235. redisAppendCommand(context, "AUTH %b", password, strlen(password));
  236. if (database != _database)
  237. {
  238. VStringBuffer cmd("SELECT %d", _database);
  239. redisAppendCommand(context, cmd.str());
  240. }
  241. //Now read replies.
  242. OwnedReply reply = new Reply();
  243. if (password && *password)
  244. readReplyAndAssert(reply, "server authentication");
  245. if (database != _database)
  246. {
  247. VStringBuffer cmd("SELECT %d", _database);
  248. readReplyAndAssertWithCmdMsg(reply, cmd.str());
  249. database = _database;
  250. }
  251. }
  252. void * Connection::redisCommand(redisContext * context, const char * format, ...)
  253. {
  254. //Copied from https://github.com/redis/hiredis/blob/master/hiredis.c ~line:1008 void * redisCommand(redisContext * context, const char * format, ...)
  255. //with redisSetTimeout(); added.
  256. va_list parameters;
  257. void * reply = NULL;
  258. va_start(parameters, format);
  259. redisSetTimeout();
  260. reply = ::redisvCommand(context, format, parameters);
  261. va_end(parameters);
  262. return reply;
  263. }
  264. unsigned Connection::timeLeft()
  265. {
  266. unsigned _timeLeft = timeout.timeLeft();
  267. if (_timeLeft == 0 && timeout.getTimeout() != 0)
  268. ::rtlFail(0, "Redis Plugin: ERROR - function timed out internally.");
  269. return _timeLeft;
  270. }
  271. void Connection::redisSetTimeout()
  272. {
  273. int _timeLeft = (int) timeLeft();
  274. if (_timeLeft == 0)
  275. return;
  276. struct timeval to = { _timeLeft/1000, (_timeLeft%1000)*1000 };
  277. assertex(context);
  278. if (::redisSetTimeout(context, to) != REDIS_OK)
  279. {
  280. assertConnection("request to set timeout");
  281. throwUnexpected();//In case there is a bug in hiredis such that the above err is not reflected in the 'context' (checked in assertConnection) as expected.
  282. }
  283. }
  284. #if HIREDIS_VERSION_OK_FOR_CACHING
  285. bool Connection::isSameConnection(ICodeContext * ctx, const char * _options, const char * password) const
  286. {
  287. return (hashServerIpPortPassword(ctx, _options, password) == serverIpPortPasswordHash);
  288. }
  289. unsigned Connection::hashServerIpPortPassword(ICodeContext * ctx, const char * _options, const char * password)
  290. {
  291. return hashc((const unsigned char*)_options, strlen(_options), hashc((const unsigned char*)password, strlen(password), 0));
  292. }
  293. void Connection::reset(ICodeContext * ctx, const char * password, unsigned _timeout)
  294. {
  295. timeout.reset(_timeout);
  296. if (context && context->err != REDIS_OK)
  297. {
  298. redisFree(context);
  299. context = NULL;
  300. database = 0;
  301. connect(ctx, 0, password);
  302. }
  303. }
  304. #endif
  305. void Connection::parseOptions(ICodeContext * ctx, const char * _options)
  306. {
  307. StringArray optionStrings;
  308. optionStrings.appendList(_options, " ");
  309. ForEachItemIn(idx, optionStrings)
  310. {
  311. const char *opt = optionStrings.item(idx);
  312. if (strncmp(opt, "--SERVER=", 9) == 0)
  313. {
  314. opt += 9;
  315. StringArray splitPort;
  316. splitPort.appendList(opt, ":");
  317. if (splitPort.ordinality()==2)
  318. {
  319. ip.set(splitPort.item(0));
  320. port = atoi(splitPort.item(1));
  321. }
  322. }
  323. else
  324. {
  325. VStringBuffer err("Redis Plugin: ERROR - unsupported option string '%s'", opt);
  326. ::rtlFail(0, err.str());
  327. }
  328. }
  329. if (ip.isEmpty())
  330. {
  331. ip.set("localhost");
  332. if (ctx)
  333. {
  334. VStringBuffer msg("Redis Plugin: WARNING - using default cache (%s:%d)", ip.str(), port);
  335. ctx->logString(msg.str());
  336. }
  337. }
  338. }
  339. void Connection::readReply(Reply * reply)
  340. {
  341. redisReply * nakedReply = NULL;
  342. redisSetTimeout();
  343. redisGetReply(context, (void**)&nakedReply);
  344. reply->setClear(nakedReply);
  345. }
  346. void Connection::readReplyAndAssert(Reply * reply, const char * msg)
  347. {
  348. readReply(reply);
  349. assertOnError(reply->query(), msg);
  350. }
  351. void Connection::readReplyAndAssertWithCmdMsg(Reply * reply, const char * msg, const char * key)
  352. {
  353. readReply(reply);
  354. assertOnErrorWithCmdMsg(reply->query(), msg, key);
  355. }
  356. Connection * Connection::createConnection(ICodeContext * ctx, Connection * & _cachedConnection, const char * options, int _database, const char * password, unsigned _timeout, bool cacheConnections)
  357. {
  358. #if HIREDIS_VERSION_OK_FOR_CACHING
  359. //Fetch connection caching level
  360. if (!connectionCachingLevelChecked)//test to guard against unnecessary critical section
  361. {
  362. CriticalBlock block(critsec);
  363. if (!connectionCachingLevelChecked)
  364. {
  365. const char * tmp = getenv("HPCC_REDIS_PLUGIN_CONNECTION_CACHING_LEVEL"); // 0 = NO_CONNECTION_CACHING, 1 = ALLOW_CONNECTION_CACHING, 2 = CACHE_ALL_CONNECTIONS
  366. //connectionCachingLevel is already defaulted to ALLOW_CONNECTION_CACHING
  367. if (tmp && *tmp)
  368. connectionCachingLevel = atoi(tmp); //don't bother range checking
  369. connectionCachingLevelChecked = true;
  370. }
  371. }
  372. if ((connectionCachingLevel && cacheConnections) || connectionCachingLevel == CACHE_ALL_CONNECTIONS)
  373. {
  374. if (!_cachedConnection)
  375. {
  376. _cachedConnection = new Connection(ctx, options, _database, password, _timeout);
  377. if (!threadHooked)
  378. {
  379. threadHookChain = addThreadTermFunc(releaseContext);
  380. threadHooked = true;
  381. }
  382. return LINK(_cachedConnection);
  383. }
  384. if (_cachedConnection->isSameConnection(ctx, options, password))
  385. {
  386. //MORE: should perhaps check that the connection has not expired (think hiredis REDIS_KEEPALIVE_INTERVAL is defaulted to 15s).
  387. _cachedConnection->reset(ctx, password, _timeout);
  388. _cachedConnection->selectDB(ctx, _database);
  389. return LINK(_cachedConnection);
  390. }
  391. _cachedConnection->Release();
  392. _cachedConnection = NULL;
  393. _cachedConnection = new Connection(ctx, options, _database, password, _timeout);
  394. return LINK(_cachedConnection);
  395. }
  396. else
  397. #endif
  398. return new Connection(ctx, options, _database, password, _timeout);
  399. }
  400. void Connection::selectDB(ICodeContext * ctx, int _database)
  401. {
  402. if (database == _database)
  403. return;
  404. database = _database;
  405. VStringBuffer cmd("SELECT %d", database);
  406. OwnedReply reply = Reply::createReply(redisCommand(context, cmd.str()));
  407. assertOnErrorWithCmdMsg(reply->query(), cmd.str());
  408. }
  409. void Connection::fail(const char * cmd, const char * errmsg, const char * key)
  410. {
  411. if (key)
  412. {
  413. VStringBuffer msg("Redis Plugin: ERROR - %s '%s' on database %d for %s:%d failed : %s", cmd, key, database, ip.str(), port, errmsg);
  414. ::rtlFail(0, msg.str());
  415. }
  416. VStringBuffer msg("Redis Plugin: ERROR - %s on database %d for %s:%d failed : %s", cmd, database, ip.str(), port, errmsg);
  417. ::rtlFail(0, msg.str());
  418. }
  419. void Connection::assertOnError(const redisReply * reply, const char * _msg)
  420. {
  421. if (!reply)
  422. {
  423. assertConnection(_msg);
  424. throwUnexpected();
  425. }
  426. else if (reply->type == REDIS_REPLY_ERROR)
  427. {
  428. assertAuthorization(reply);
  429. VStringBuffer msg("Redis Plugin: %s - %s", _msg, reply->str);
  430. ::rtlFail(0, msg.str());
  431. }
  432. }
  433. void Connection::assertOnErrorWithCmdMsg(const redisReply * reply, const char * cmd, const char * key)
  434. {
  435. if (!reply)
  436. {
  437. assertConnectionWithCmdMsg(cmd, key);
  438. throwUnexpected();
  439. }
  440. else if (reply->type == REDIS_REPLY_ERROR)
  441. {
  442. assertAuthorization(reply);
  443. fail(cmd, reply->str, key);
  444. }
  445. }
  446. void Connection::assertAuthorization(const redisReply * reply)
  447. {
  448. if (reply && reply->str && ( strncmp(reply->str, "NOAUTH", 6) == 0 || strncmp(reply->str, "ERR operation not permitted", 27) == 0 ))
  449. {
  450. VStringBuffer msg("Redis Plugin: ERROR - authentication for %s:%d failed : %s", ip.str(), port, reply->str);
  451. ::rtlFail(0, msg.str());
  452. }
  453. }
  454. void Connection::assertKey(const redisReply * reply, const char * key)
  455. {
  456. if (reply && reply->type == REDIS_REPLY_NIL)
  457. {
  458. VStringBuffer msg("Redis Plugin: ERROR - the requested key '%s' does not exist on database %d on %s:%d", key, database, ip.str(), port);
  459. ::rtlFail(0, msg.str());
  460. }
  461. }
  462. void Connection::assertConnectionWithCmdMsg(const char * cmd, const char * key)
  463. {
  464. if (!context)
  465. fail(cmd, "neither 'reply' nor connection error available", key);
  466. else if (context->err)
  467. fail(cmd, context->errstr, key);
  468. }
  469. void Connection::assertConnection(const char * _msg)
  470. {
  471. if (!context)
  472. {
  473. VStringBuffer msg("Redis Plugin: ERROR - %s for %s:%d failed : neither 'reply' nor connection error available", _msg, ip.str(), port);
  474. ::rtlFail(0, msg.str());
  475. }
  476. else if (context->err)
  477. {
  478. VStringBuffer msg("Redis Plugin: ERROR - %s for %s:%d failed : %s", _msg, ip.str(), port, context->errstr);
  479. ::rtlFail(0, msg.str());
  480. }
  481. }
  482. void Connection::clear(ICodeContext * ctx)
  483. {
  484. //NOTE: flush is the actual cache flush/clear/delete and not an io buffer flush.
  485. OwnedReply reply = Reply::createReply(redisCommand(context, "FLUSHDB"));//NOTE: FLUSHDB deletes current database where as FLUSHALL deletes all dbs.
  486. //NOTE: documented as never failing, but in case
  487. assertOnErrorWithCmdMsg(reply->query(), "FlushDB");
  488. }
  489. void Connection::del(ICodeContext * ctx, const char * key)
  490. {
  491. OwnedReply reply = Reply::createReply(redisCommand(context, "DEL %b", key, strlen(key)));
  492. assertOnErrorWithCmdMsg(reply->query(), "Del", key);
  493. }
  494. void Connection::persist(ICodeContext * ctx, const char * key)
  495. {
  496. OwnedReply reply = Reply::createReply(redisCommand(context, "PERSIST %b", key, strlen(key)));
  497. assertOnErrorWithCmdMsg(reply->query(), "Persist", key);
  498. }
  499. void Connection::expire(ICodeContext * ctx, const char * key, unsigned _expire)
  500. {
  501. OwnedReply reply = Reply::createReply(redisCommand(context, "PEXPIRE %b %u", key, strlen(key), _expire));
  502. assertOnErrorWithCmdMsg(reply->query(), "Expire", key);
  503. }
  504. bool Connection::exists(ICodeContext * ctx, const char * key)
  505. {
  506. OwnedReply reply = Reply::createReply(redisCommand(context, "EXISTS %b", key, strlen(key)));
  507. assertOnErrorWithCmdMsg(reply->query(), "Exists", key);
  508. return (reply->query()->integer != 0);
  509. }
  510. unsigned __int64 Connection::dbSize(ICodeContext * ctx)
  511. {
  512. OwnedReply reply = Reply::createReply(redisCommand(context, "DBSIZE"));
  513. assertOnErrorWithCmdMsg(reply->query(), "DBSIZE");
  514. return reply->query()->integer;
  515. }
  516. //-------------------------------------------SET-----------------------------------------
  517. //--OUTER--
  518. template<class type> void SyncRSet(ICodeContext * ctx, const char * _options, const char * key, type value, int database, unsigned expire, const char * password, unsigned _timeout, bool cacheConnections)
  519. {
  520. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, _options, database, password, _timeout, cacheConnections);
  521. master->set(ctx, key, value, expire);
  522. }
  523. //Set pointer types
  524. template<class type> void SyncRSet(ICodeContext * ctx, const char * _options, const char * key, size32_t valueSize, const type * value, int database, unsigned expire, const char * password, unsigned _timeout, bool cacheConnections)
  525. {
  526. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, _options, database, password, _timeout, cacheConnections);
  527. master->set(ctx, key, valueSize, value, expire);
  528. }
  529. //--INNER--
  530. template<class type> void Connection::set(ICodeContext * ctx, const char * key, type value, unsigned expire)
  531. {
  532. const char * _value = reinterpret_cast<const char *>(&value);//Do this even for char * to prevent compiler complaining
  533. StringBuffer cmd("SET %b %b");
  534. appendExpire(cmd, expire);
  535. OwnedReply reply = Reply::createReply(redisCommand(context, cmd.str(), key, strlen(key), _value, sizeof(type)));
  536. assertOnErrorWithCmdMsg(reply->query(), "SET", key);
  537. }
  538. template<class type> void Connection::set(ICodeContext * ctx, const char * key, size32_t valueSize, const type * value, unsigned expire)
  539. {
  540. const char * _value = reinterpret_cast<const char *>(value);//Do this even for char * to prevent compiler complaining
  541. StringBuffer cmd("SET %b %b");
  542. appendExpire(cmd, expire);
  543. OwnedReply reply = Reply::createReply(redisCommand(context, cmd.str(), key, strlen(key), _value, (size_t)valueSize));
  544. assertOnErrorWithCmdMsg(reply->query(), "SET", key);
  545. }
  546. //-------------------------------------------GET-----------------------------------------
  547. //--OUTER--
  548. template<class type> void SyncRGet(ICodeContext * ctx, const char * options, const char * key, type & returnValue, int database, const char * password, unsigned _timeout, bool cacheConnections)
  549. {
  550. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, _timeout, cacheConnections);
  551. master->get(ctx, key, returnValue);
  552. }
  553. template<class type> void SyncRGet(ICodeContext * ctx, const char * options, const char * key, size_t & returnSize, type * & returnValue, int database, const char * password, unsigned _timeout, bool cacheConnections)
  554. {
  555. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, _timeout, cacheConnections);
  556. master->get(ctx, key, returnSize, returnValue);
  557. }
  558. //--INNER--
  559. template<class type> void Connection::get(ICodeContext * ctx, const char * key, type & returnValue)
  560. {
  561. OwnedReply reply = Reply::createReply(redisCommand(context, "GET %b", key, strlen(key)));
  562. assertOnErrorWithCmdMsg(reply->query(), "GET", key);
  563. assertKey(reply->query(), key);
  564. size_t returnSize = reply->query()->len;
  565. if (sizeof(type)!=returnSize)
  566. {
  567. VStringBuffer msg("requested type of different size (%uB) from that stored (%uB)", (unsigned)sizeof(type), (unsigned)returnSize);
  568. fail("GET", msg.str(), key);
  569. }
  570. memcpy(&returnValue, reply->query()->str, returnSize);
  571. }
  572. template<class type> void Connection::get(ICodeContext * ctx, const char * key, size_t & returnSize, type * & returnValue)
  573. {
  574. OwnedReply reply = Reply::createReply(redisCommand(context, "GET %b", key, strlen(key)));
  575. assertOnErrorWithCmdMsg(reply->query(), "GET", key);
  576. assertKey(reply->query(), key);
  577. returnSize = reply->query()->len;
  578. returnValue = reinterpret_cast<type*>(allocateAndCopy(reply->query()->str, returnSize));
  579. }
  580. unsigned __int64 Connection::publish(ICodeContext * ctx, const char * keyOrChannel, size32_t messageSize, const char * message, int _database, bool lockedKey)
  581. {
  582. StringBuffer channel;
  583. if (lockedKey)
  584. encodeChannel(channel, keyOrChannel, _database);
  585. else
  586. channel.set(keyOrChannel);
  587. OwnedReply reply = Reply::createReply(redisCommand(context, "PUBLISH %b %b", channel.str(), (size_t)channel.length(), message, (size_t)messageSize));
  588. assertOnErrorWithCmdMsg(reply->query(), "PUBLISH", channel.str());
  589. if (reply->query()->type == REDIS_REPLY_INTEGER)
  590. {
  591. if (reply->query()->integer >= 0)
  592. return (unsigned __int64)reply->query()->integer;
  593. else
  594. throwUnexpected();
  595. }
  596. throwUnexpected();
  597. }
  598. void Connection::subscribe(ICodeContext * ctx, const char * keyOrChannel, size_t & messageSize, char * & message, int _database, bool lockedKey)
  599. {
  600. StringBuffer channel;
  601. if (lockedKey)
  602. encodeChannel(channel, keyOrChannel, _database);
  603. else
  604. channel.set(keyOrChannel);
  605. #if(0)//Replicate a lingering SUBSCRIBE to test channel comparison test when reading message.
  606. {
  607. OwnedReply reply = Reply::createReply(redisCommand(context, "SUBSCRIBE oldChannel"));
  608. assertOnErrorWithCmdMsg(reply->query(), "Test lingering SUBSCRIBE", "oldChannel");
  609. }
  610. #endif
  611. OwnedReply reply = Reply::createReply(redisCommand(context, "SUBSCRIBE %b", channel.str(), (size_t)channel.length()));
  612. assertOnErrorWithCmdMsg(reply->query(), "SUBSCRIBE", channel.str());
  613. if (reply->query()->type != REDIS_REPLY_ARRAY || strcmp("subscribe", reply->query()->element[0]->str) != 0 )
  614. fail("SUBSCRIBE", "failed to register SUB", channel.str());
  615. readReply(reply);
  616. assertOnErrorWithCmdMsg(reply->query(), "SUBSCRIBE", channel.str());
  617. if (reply->query()->type == REDIS_REPLY_ARRAY && strcmp("message", reply->query()->element[0]->str) == 0 && reply->query()->elements == 3)
  618. {
  619. if (reply->query()->element[2]->len > 0)
  620. {
  621. messageSize = (size_t)reply->query()->element[2]->len;
  622. message = reinterpret_cast<char*>(allocateAndCopy(reply->query()->element[2]->str, messageSize));
  623. }
  624. else
  625. {
  626. messageSize = 0;
  627. message = NULL;
  628. }
  629. return;
  630. }
  631. throwUnexpected();
  632. }
  633. //--------------------------------------------------------------------------------
  634. // ECL SERVICE ENTRYPOINTS
  635. //--------------------------------------------------------------------------------
  636. ECL_REDIS_API unsigned __int64 ECL_REDIS_CALL SyncRPub(ICodeContext * ctx, const char * keyOrChannel, size32_t messageSize, const char * message, const char * options, int database, const char * password, unsigned timeout, bool lockedKey, bool cacheConnections)
  637. {
  638. Owned<Connection> master = Connection::createConnection(ctx, cachedPubConnection, options, 0, password, timeout, cacheConnections);
  639. return master->publish(ctx, keyOrChannel, messageSize, message, database, lockedKey);
  640. }
  641. ECL_REDIS_API void ECL_REDIS_CALL SyncRSub(ICodeContext * ctx, size32_t & messageSize, char * & message, const char * keyOrChannel, const char * options, int database, const char * password, unsigned timeout, bool lockedKey, bool cacheConnections)
  642. {
  643. size_t _messageSize = 0;
  644. Owned<Connection> master = new Connection(ctx, options, 0, password, timeout);
  645. master->subscribe(ctx, keyOrChannel, _messageSize, message, database, lockedKey);
  646. messageSize = static_cast<size32_t>(_messageSize);
  647. }
  648. ECL_REDIS_API void ECL_REDIS_CALL RClear(ICodeContext * ctx, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  649. {
  650. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, timeout, cacheConnections);
  651. master->clear(ctx);
  652. }
  653. ECL_REDIS_API bool ECL_REDIS_CALL RExist(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  654. {
  655. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, timeout, cacheConnections);
  656. return master->exists(ctx, key);
  657. }
  658. ECL_REDIS_API void ECL_REDIS_CALL RDel(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  659. {
  660. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, timeout, cacheConnections);
  661. master->del(ctx, key);
  662. }
  663. ECL_REDIS_API void ECL_REDIS_CALL RPersist(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  664. {
  665. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, timeout, cacheConnections);
  666. master->persist(ctx, key);
  667. }
  668. ECL_REDIS_API void ECL_REDIS_CALL RExpire(ICodeContext * ctx, const char * key, const char * options, int database, unsigned _expire, const char * password, unsigned timeout, bool cacheConnections)
  669. {
  670. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, timeout, cacheConnections);
  671. master->expire(ctx, key, _expire);
  672. }
  673. ECL_REDIS_API unsigned __int64 ECL_REDIS_CALL RDBSize(ICodeContext * ctx, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  674. {
  675. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, timeout, cacheConnections);
  676. return master->dbSize(ctx);
  677. }
  678. //-----------------------------------SET------------------------------------------
  679. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetStr(ICodeContext * ctx, const char * key, size32_t valueSize, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  680. {
  681. SyncRSet(ctx, options, key, valueSize, value, database, expire, password, timeout, cacheConnections);
  682. }
  683. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetUChar(ICodeContext * ctx, const char * key, size32_t valueLength, const UChar * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  684. {
  685. SyncRSet(ctx, options, key, (valueLength)*sizeof(UChar), value, database, expire, password, timeout, cacheConnections);
  686. }
  687. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetInt(ICodeContext * ctx, const char * key, signed __int64 value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  688. {
  689. SyncRSet(ctx, options, key, value, database, expire, password, timeout, cacheConnections);
  690. }
  691. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetUInt(ICodeContext * ctx, const char * key, unsigned __int64 value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  692. {
  693. SyncRSet(ctx, options, key, value, database, expire, password, timeout, cacheConnections);
  694. }
  695. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetReal(ICodeContext * ctx, const char * key, double value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  696. {
  697. SyncRSet(ctx, options, key, value, database, expire, password, timeout, cacheConnections);
  698. }
  699. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetBool(ICodeContext * ctx, const char * key, bool value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  700. {
  701. SyncRSet(ctx, options, key, value, database, expire, password, timeout, cacheConnections);
  702. }
  703. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetData(ICodeContext * ctx, const char * key, size32_t valueSize, const void * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  704. {
  705. SyncRSet(ctx, options, key, valueSize, value, database, expire, password, timeout, cacheConnections);
  706. }
  707. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetUtf8(ICodeContext * ctx, const char * key, size32_t valueLength, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  708. {
  709. SyncRSet(ctx, options, key, rtlUtf8Size(valueLength, value), value, database, expire, password, timeout, cacheConnections);
  710. }
  711. //-------------------------------------GET----------------------------------------
  712. ECL_REDIS_API bool ECL_REDIS_CALL SyncRGetBool(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  713. {
  714. bool value;
  715. SyncRGet(ctx, options, key, value, database, password, timeout, cacheConnections);
  716. return value;
  717. }
  718. ECL_REDIS_API double ECL_REDIS_CALL SyncRGetDouble(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  719. {
  720. double value;
  721. SyncRGet(ctx, options, key, value, database, password, timeout, cacheConnections);
  722. return value;
  723. }
  724. ECL_REDIS_API signed __int64 ECL_REDIS_CALL SyncRGetInt8(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  725. {
  726. signed __int64 value;
  727. SyncRGet(ctx, options, key, value, database, password, timeout, cacheConnections);
  728. return value;
  729. }
  730. ECL_REDIS_API unsigned __int64 ECL_REDIS_CALL SyncRGetUint8(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  731. {
  732. unsigned __int64 value;
  733. SyncRGet(ctx, options, key, value, database, password, timeout, cacheConnections);
  734. return value;
  735. }
  736. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetStr(ICodeContext * ctx, size32_t & returnSize, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  737. {
  738. size_t _returnSize;
  739. SyncRGet(ctx, options, key, _returnSize, returnValue, database, password, timeout, cacheConnections);
  740. returnSize = static_cast<size32_t>(_returnSize);
  741. }
  742. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetUChar(ICodeContext * ctx, size32_t & returnLength, UChar * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  743. {
  744. size_t returnSize;
  745. SyncRGet(ctx, options, key, returnSize, returnValue, database, password, timeout, cacheConnections);
  746. returnLength = static_cast<size32_t>(returnSize/sizeof(UChar));
  747. }
  748. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetUtf8(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  749. {
  750. size_t returnSize;
  751. SyncRGet(ctx, options, key, returnSize, returnValue, database, password, timeout, cacheConnections);
  752. returnLength = static_cast<size32_t>(rtlUtf8Length(returnSize, returnValue));
  753. }
  754. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetData(ICodeContext * ctx, size32_t & returnSize, void * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  755. {
  756. size_t _returnSize;
  757. SyncRGet(ctx, options, key, _returnSize, returnValue, database, password, timeout, cacheConnections);
  758. returnSize = static_cast<size32_t>(_returnSize);
  759. }
  760. //----------------------------------LOCK------------------------------------------
  761. //-----------------------------------SET-----------------------------------------
  762. //Set pointer types
  763. void SyncLockRSet(ICodeContext * ctx, const char * _options, const char * key, size32_t valueSize, const char * value, int database, unsigned expire, const char * password, unsigned _timeout, bool cacheConnections)
  764. {
  765. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, _options, database, password, _timeout, cacheConnections);
  766. master->lockSet(ctx, key, valueSize, value, expire);
  767. }
  768. //--INNER--
  769. void Connection::lockSet(ICodeContext * ctx, const char * key, size32_t valueSize, const char * value, unsigned expire)
  770. {
  771. const char * _value = reinterpret_cast<const char *>(value);//Do this even for char * to prevent compiler complaining
  772. handleLockOnSet(ctx, key, _value, (size_t)valueSize, expire);
  773. }
  774. //-------------------------------------------GET-----------------------------------------
  775. //--OUTER--
  776. void SyncLockRGet(ICodeContext * ctx, const char * options, const char * key, size_t & returnSize, char * & returnValue, int database, unsigned expire, const char * password, unsigned _timeout, bool cacheConnections)
  777. {
  778. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, _timeout, cacheConnections);
  779. master->lockGet(ctx, key, returnSize, returnValue, password, expire);
  780. }
  781. //--INNER--
  782. void Connection::lockGet(ICodeContext * ctx, const char * key, size_t & returnSize, char * & returnValue, const char * password, unsigned expire)
  783. {
  784. MemoryAttr retVal;
  785. handleLockOnGet(ctx, key, &retVal, password, expire);
  786. returnSize = retVal.length();
  787. returnValue = reinterpret_cast<char*>(retVal.detach());
  788. }
  789. //---------------------------------------------------------------------------------------
  790. void Connection::encodeChannel(StringBuffer & channel, const char * key, int _database) const
  791. {
  792. channel.append(REDIS_LOCK_PREFIX).append("_").append(key).append("_").append(_database);
  793. }
  794. bool Connection::lock(ICodeContext * ctx, const char * key, const char * channel, unsigned expire)
  795. {
  796. if (expire == 0)
  797. fail("GetOrLock<type>", "invalid value for 'expire', persistent locks not allowed.", key);
  798. StringBuffer cmd("SET %b %b NX PX ");
  799. cmd.append(expire);
  800. OwnedReply reply = Reply::createReply(redisCommand(context, cmd.str(), key, strlen(key), channel, strlen(channel)));
  801. assertOnErrorWithCmdMsg(reply->query(), cmd.str(), key);
  802. return (reply->query()->type == REDIS_REPLY_STATUS && strcmp(reply->query()->str, "OK") == 0);
  803. }
  804. void Connection::unlock(ICodeContext * ctx, const char * key)
  805. {
  806. //WATCH key, if altered between WATCH and EXEC abort all commands inbetween
  807. redisAppendCommand(context, "WATCH %b", key, strlen(key));
  808. redisAppendCommand(context, "GET %b", key, strlen(key));
  809. //Read replies
  810. OwnedReply reply = new Reply();
  811. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//WATCH reply
  812. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//GET reply
  813. //check if locked
  814. if (strncmp(reply->query()->str, REDIS_LOCK_PREFIX, strlen(REDIS_LOCK_PREFIX)) == 0)
  815. {
  816. //MULTI - all commands between MULTI and EXEC are considered an atomic transaction on the server
  817. redisAppendCommand(context, "MULTI");//MULTI
  818. redisAppendCommand(context, "DEL %b", key, strlen(key));//DEL
  819. redisAppendCommand(context, "EXEC");//EXEC
  820. #if(0)//Quick draw! You have 10s to manually send (via redis-cli) "set testlock foobar". The second myRedis.Exists('testlock') in redislockingtest.ecl should now return TRUE.
  821. sleep(10);
  822. #endif
  823. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//MULTI reply
  824. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//DEL reply
  825. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//EXEC reply
  826. }
  827. //If the above is aborted, let the lock expire.
  828. }
  829. void Connection::handleLockOnGet(ICodeContext * ctx, const char * key, MemoryAttr * retVal, const char * password, unsigned expire)
  830. {
  831. //NOTE: This routine can only return an empty string under one condition, that which indicates to the caller that the key was successfully locked.
  832. StringBuffer channel;
  833. encodeChannel(channel, key, database);
  834. //Query key and set lock if non existent
  835. if (lock(ctx, key, channel.str(), expire))
  836. return;
  837. #if(0)//Test empty string handling by deleting the lock/value, and thus GET returns REDIS_REPLY_NIL as the reply type and an empty string.
  838. {
  839. OwnedReply pubReply = Reply::createReply(redisCommand(context, "DEL %b", key, strlen(key)));
  840. assertOnError(pubReply->query(), "del fail");
  841. }
  842. #endif
  843. //SUB before GET
  844. //Requires separate connection from GET so that the replies are not mangled. This could be averted
  845. Owned<Connection> subConnection = new Connection(ctx, options.str(), ip.str(), port, serverIpPortPasswordHash, database, password, timeLeft());
  846. OwnedReply subReply = Reply::createReply(redisCommand(subConnection->context, "SUBSCRIBE %b", channel.str(), (size_t)channel.length()));
  847. //Defer checking of reply/connection errors until actually needed.
  848. #if(0)//Test publish before GET.
  849. {
  850. OwnedReply pubReply = Reply::createReply(redisCommand(context, "PUBLISH %b %b", channel.str(), (size_t)channel.length(), "foo", (size_t)3));
  851. assertOnError(pubReply->query(), "pub fail");
  852. }
  853. #endif
  854. //Now GET
  855. OwnedReply getReply = Reply::createReply((redisReply*)redisCommand(context, "GET %b", key, strlen(key)));
  856. assertOnErrorWithCmdMsg(getReply->query(), "GetOrLock<type>", key);
  857. #if(0)//Test publish after GET.
  858. {
  859. OwnedReply pubReply = Reply::createReply(redisCommand(context, "PUBLISH %b %b", channel.str(), (size_t)channel.length(), "foo", (size_t)3));
  860. assertOnError(pubReply->query(), "pub fail");
  861. }
  862. #endif
  863. //Only return an actual value, i.e. neither the lock value nor an empty string. The latter is unlikely since we know that lock()
  864. //failed, indicating that the key existed. If this is an actual value, it is however, possible for it to have been DELeted in the interim.
  865. if (getReply->query()->type != REDIS_REPLY_NIL && getReply->query()->str && strncmp(getReply->query()->str, REDIS_LOCK_PREFIX, strlen(REDIS_LOCK_PREFIX)) != 0)
  866. {
  867. retVal->set(getReply->query()->len, getReply->query()->str);
  868. return;
  869. }
  870. else
  871. {
  872. //Check that the lock was set by this plugin and thus that we subscribed to the expected channel.
  873. if (getReply->query()->str && strcmp(getReply->query()->str, channel.str()) !=0 )
  874. {
  875. VStringBuffer msg("key locked with a channel ('%s') different to that subscribed to (%s).", getReply->query()->str, channel.str());
  876. fail("GetOrLock<type>", msg.str(), key);
  877. //MORE: In theory, it is possible to recover at this stage by subscribing to the channel that the key was actually locked with.
  878. //However, we may have missed the massage publication already or by then, but could SUB again in case we haven't.
  879. //More importantly and furthermore, the publication (in SetAndPublish<type>) will only publish to the channel encoded by
  880. //this plugin, rather than the string retrieved as the lock value (the value of the locked key).
  881. }
  882. getReply.clear();
  883. #if(0)//Added to allow for manual pub testing via redis-cli
  884. struct timeval to = { 10, 0 };//10secs
  885. ::redisSetTimeout(subConnection->context, to);
  886. #endif
  887. //Locked so SUBSCRIBE
  888. subConnection->assertOnErrorWithCmdMsg(subReply->query(), "GetOrLock<type>", key);
  889. if (subReply->query()->type != REDIS_REPLY_ARRAY || strcmp("subscribe", subReply->query()->element[0]->str) != 0 )
  890. fail("GetOrLock<type>", "failed to register SUB", key);//NOTE: In this instance better to be this->fail rather than subConnection->fail - due to database reported in msg.
  891. subConnection->readReply(subReply);
  892. subConnection->assertOnErrorWithCmdMsg(subReply->query(), "GetOrLock<type>", key);
  893. if (subReply->query()->type == REDIS_REPLY_ARRAY && strcmp("message", subReply->query()->element[0]->str) == 0)
  894. {
  895. //We are about to return a value, to conform with other Get<type> functions, fail if the key did not exist.
  896. //Since the value is sent via a published message, there is no direct reply struct so assume that an empty
  897. //string is equivalent to a non-existent key.
  898. //More importantly, it is paramount that this routine only return an empty string under one condition, that
  899. //which indicates to the caller that the key was successfully locked.
  900. //NOTE: it is possible for an empty message to have been PUBLISHed.
  901. if (subReply->query()->element[2]->len > 0)
  902. {
  903. retVal->set(subReply->query()->element[2]->len, subReply->query()->element[2]->str);//return the published value rather than another (WATCHed) GET.
  904. return;
  905. }
  906. //fail that key does not exist
  907. redisReply fakeReply;
  908. fakeReply.type = REDIS_REPLY_NIL;
  909. assertKey(&fakeReply, key);
  910. }
  911. }
  912. throwUnexpected();
  913. }
  914. void Connection::handleLockOnSet(ICodeContext * ctx, const char * key, const char * value, size_t size, unsigned expire)
  915. {
  916. //Due to locking logic surfacing into ECL, any locking.set (such as this is) assumes that they own the lock and therefore go ahead and set regardless.
  917. StringBuffer channel;
  918. encodeChannel(channel, key, database);
  919. if (size > 29)//c.f. 1st note below.
  920. {
  921. OwnedReply replyContainer = new Reply();
  922. if (expire == 0)
  923. {
  924. const char * luaScriptSHA1 = "2a4a976d9bbd806756b2c7fc1e2bc2cb905e68c3"; //NOTE: update this if luaScript is updated!
  925. replyContainer->setClear(redisCommand(context, "EVALSHA %b %d %b %b %b", luaScriptSHA1, (size_t)40, 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size));
  926. if (noScript(replyContainer->query()))
  927. {
  928. const char * luaScript = "redis.call('SET', KEYS[1], ARGV[2]) redis.call('PUBLISH', ARGV[1], ARGV[2]) return";//NOTE: MUST update luaScriptSHA1 if luaScript is updated!
  929. replyContainer->setClear(redisCommand(context, "EVAL %b %d %b %b %b", luaScript, strlen(luaScript), 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size));
  930. }
  931. }
  932. else
  933. {
  934. const char * luaScriptWithExpireSHA1 = "6f6bc88ccea7c6853ccc395eaa7abd8cb91fb2d8"; //NOTE: update this if luaScriptWithExpire is updated!
  935. replyContainer->setClear(redisCommand(context, "EVALSHA %b %d %b %b %b %d", luaScriptWithExpireSHA1, (size_t)40, 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size, expire));
  936. if (noScript(replyContainer->query()))
  937. {
  938. const char * luaScriptWithExpire = "redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3]) redis.call('PUBLISH', ARGV[1], ARGV[2]) return";//NOTE: MUST update luaScriptWithExpireSHA1 if luaScriptWithExpire is updated!
  939. replyContainer->setClear(redisCommand(context, "EVAL %b %d %b %b %b %d", luaScriptWithExpire, strlen(luaScriptWithExpire), 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size, expire));
  940. }
  941. }
  942. assertOnErrorWithCmdMsg(replyContainer->query(), "SET", key);
  943. }
  944. else
  945. {
  946. StringBuffer cmd("SET %b %b");
  947. RedisPlugin::appendExpire(cmd, expire);
  948. redisAppendCommand(context, "MULTI");
  949. redisAppendCommand(context, cmd.str(), key, strlen(key), value, size);//SET
  950. redisAppendCommand(context, "PUBLISH %b %b", channel.str(), (size_t)channel.length(), value, size);//PUB
  951. redisAppendCommand(context, "EXEC");
  952. //Now read and assert replies
  953. OwnedReply reply = new Reply();
  954. readReplyAndAssertWithCmdMsg(reply, "SET", key);//MULTI reply
  955. readReplyAndAssertWithCmdMsg(reply, "SET", key);//SET reply
  956. readReplyAndAssertWithCmdMsg(reply, "PUB for the key", key);//PUB reply
  957. readReplyAndAssertWithCmdMsg(reply, "SET", key);//EXEC reply
  958. }
  959. //NOTE: When setting and publishing the data with a pipelined MULTI-SET-PUB-EXEC, the data is sent twice, once with the SET and again with the PUBLISH.
  960. //To prevent this, send the data to the server only once with a server-side lua script that then sets and publishes the data from the server.
  961. //However, there is a transmission overhead for this method that may still be larger than sending the data twice if it is small enough.
  962. //multi-set-pub-exec (via strings) has a transmission length of - "MULTI SET" + key + value + "PUBLISH" + channel + value = 5 + 3 + key + 7 + value + channel + value + 4
  963. //The lua script (assuming the script already exists on the server) a length of - "EVALSHA" + digest + "1" + key + channel + value = 7 + 40 + 1 + key + channel + value
  964. //Therefore, they have same length when: 19 + value = 48 => value = 29.
  965. //NOTE: Pipelining the above commands may not be the expected behaviour, instead only PUBLISH upon a successful SET. Doing both regardless, does however ensure
  966. //(assuming only the SET fails) that any subscribers do in fact get their requested key-value even if the SET fails. This may not be expected behaviour
  967. //as it is now possible for the key-value to NOT actually exist in the cache though it was retrieved via a redis plugin get function. This is documented in the README.
  968. //Further more, it is possible that the locked value and thus the channel stored within the key is not that expected, i.e. computed via encodeChannel() (e.g.
  969. //if set by a non-conforming external client/process). It is however, possible to account for this via using a GETSET instead of just the SET. This returns the old
  970. //value stored, this can then be checked if it is a lock (i.e. has at least the "redis_key_lock prefix"), if it doesn't, PUB on the channel from encodeChannel(),
  971. //otherwise PUB on the value retrieved from GETSET or possibly only if it at least has the prefix "redis_key_lock".
  972. //This would however, prevent the two commands from being pipelined, as the GETSET would need to return before publishing. It would also mean sending the data twice.
  973. }
  974. bool Connection::noScript(const redisReply * reply) const
  975. {
  976. return (reply && reply->type == REDIS_REPLY_ERROR && strncmp(reply->str, "NOSCRIPT", 8) == 0);
  977. }
  978. //--------------------------------------------------------------------------------
  979. // ECL SERVICE ENTRYPOINTS
  980. //--------------------------------------------------------------------------------
  981. //-----------------------------------SET------------------------------------------
  982. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRSetStr(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, size32_t valueLength, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  983. {
  984. SyncLockRSet(ctx, options, key, valueLength, value, database, expire, password, timeout, cacheConnections);
  985. returnLength = valueLength;
  986. returnValue = (char*)allocateAndCopy(value, valueLength);
  987. }
  988. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRSetUChar(ICodeContext * ctx, size32_t & returnLength, UChar * & returnValue, const char * key, size32_t valueLength, const UChar * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  989. {
  990. unsigned valueSize = (valueLength)*sizeof(UChar);
  991. SyncLockRSet(ctx, options, key, valueSize, (char*)value, database, expire, password, timeout, cacheConnections);
  992. returnLength= valueLength;
  993. returnValue = (UChar*)allocateAndCopy(value, valueSize);
  994. }
  995. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRSetUtf8(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, size32_t valueLength, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cacheConnections)
  996. {
  997. unsigned valueSize = rtlUtf8Size(valueLength, value);
  998. SyncLockRSet(ctx, options, key, valueSize, value, database, expire, password, timeout, cacheConnections);
  999. returnLength = valueLength;
  1000. returnValue = (char*)allocateAndCopy(value, valueSize);
  1001. }
  1002. //-------------------------------------GET----------------------------------------
  1003. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRGetStr(ICodeContext * ctx, size32_t & returnSize, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, unsigned expire, bool cacheConnections)
  1004. {
  1005. size_t _returnSize;
  1006. SyncLockRGet(ctx, options, key, _returnSize, returnValue, database, expire, password, timeout, cacheConnections);
  1007. returnSize = static_cast<size32_t>(_returnSize);
  1008. }
  1009. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRGetUChar(ICodeContext * ctx, size32_t & returnLength, UChar * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, unsigned expire, bool cacheConnections)
  1010. {
  1011. size_t returnSize;
  1012. char * _returnValue;
  1013. SyncLockRGet(ctx, options, key, returnSize, _returnValue, database, expire, password, timeout, cacheConnections);
  1014. returnValue = (UChar*)_returnValue;
  1015. returnLength = static_cast<size32_t>(returnSize/sizeof(UChar));
  1016. }
  1017. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRGetUtf8(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, unsigned expire, bool cacheConnections)
  1018. {
  1019. size_t returnSize;
  1020. SyncLockRGet(ctx, options, key, returnSize, returnValue, database, expire, password, timeout, cacheConnections);
  1021. returnLength = static_cast<size32_t>(rtlUtf8Length(returnSize, returnValue));
  1022. }
  1023. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRUnlock(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cacheConnections)
  1024. {
  1025. Owned<Connection> master = Connection::createConnection(ctx, cachedConnection, options, database, password, timeout, cacheConnections);
  1026. master->unlock(ctx, key);
  1027. }
  1028. }//close namespace