redis.cpp 47 KB

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