redis.cpp 46 KB

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