redis.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2015 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include "jthread.hpp"
  15. #include "eclrtl.hpp"
  16. #include "jstring.hpp"
  17. #include "jmutex.hpp"
  18. #include "redis.hpp"
  19. extern "C"
  20. {
  21. #include "hiredis/hiredis.h"
  22. }
  23. #define REDIS_VERSION "redis plugin 1.0.0"
  24. ECL_REDIS_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  25. {
  26. if (pb->size != sizeof(ECLPluginDefinitionBlock))
  27. return false;
  28. pb->magicVersion = PLUGIN_VERSION;
  29. pb->version = REDIS_VERSION;
  30. pb->moduleName = "lib_redis";
  31. pb->ECL = nullptr;
  32. pb->flags = PLUGIN_IMPLICIT_MODULE;
  33. pb->description = "ECL plugin library for the C API hiredis\n";
  34. return true;
  35. }
  36. namespace RedisPlugin {
  37. class Connection;
  38. static const char * REDIS_LOCK_PREFIX = "redis_ecl_lock";
  39. static __thread Connection * cachedConnection = nullptr;
  40. static __thread Connection * cachedPubConnection = nullptr;//database should always = 0
  41. static __thread Connection * cachedSubscriptionConnection = nullptr;
  42. #define NO_CONNECTION_CACHING 0
  43. #define ALLOW_CONNECTION_CACHING 1
  44. #define CACHE_ALL_CONNECTIONS 2
  45. #define INTERNAL_TIMEOUT -2
  46. #define DUMMY_IP 0
  47. #define DUMMY_PORT 0
  48. static CriticalSection critsec;
  49. static __thread ThreadTermFunc threadHookChain = nullptr;
  50. static __thread bool threadHooked = false;
  51. static int connectionCachingLevel = ALLOW_CONNECTION_CACHING;
  52. static std::atomic<bool> connectionCachingLevelChecked(false);
  53. static bool cacheSubConnections = true;
  54. static std::atomic<bool> cacheSubConnectionsOptChecked(false);
  55. static int unsubscribeTimeout = 100;//ms
  56. static std::atomic<bool> unsubscribeTimeoutChecked(false);
  57. static unsigned unsubscribeReadAttempts = 2;//The max number of possible socket read attempts when wanting the desired unsubscribe confirmation, otherwise give up.
  58. static std::atomic<bool> unsubscribeReadAttemptsChecked(false);
  59. static void * allocateAndCopy(const void * src, size_t size)
  60. {
  61. return memcpy(rtlMalloc(size), src, size);
  62. }
  63. static StringBuffer & appendExpire(StringBuffer & buffer, unsigned expire)
  64. {
  65. if (expire > 0)
  66. buffer.append(" PX ").append(expire);
  67. return buffer;
  68. }
  69. class Reply : public CInterface
  70. {
  71. public :
  72. inline Reply() { };
  73. inline Reply(void * _reply) : reply((redisReply*)_reply) { }
  74. inline Reply(redisReply * _reply) : reply(_reply) { }
  75. inline ~Reply()
  76. {
  77. if (reply)
  78. freeReplyObject(reply);
  79. }
  80. static inline Reply * createReply(void * _reply) { return new Reply(_reply); }
  81. inline const redisReply * query() const { return reply; }
  82. inline void setClear(void * _reply) { setClear((redisReply*)_reply); }
  83. void setClear(redisReply * _reply);
  84. private :
  85. redisReply * reply = nullptr;
  86. };
  87. void Reply::setClear(redisReply * _reply)
  88. {
  89. if (reply == _reply)
  90. return;
  91. if (reply)
  92. freeReplyObject(reply);
  93. reply = _reply;
  94. }
  95. typedef Owned<RedisPlugin::Reply> OwnedReply;
  96. class TimeoutHandler
  97. {
  98. public :
  99. TimeoutHandler(unsigned _timeout) : timeout(_timeout), t0(msTick()) { }
  100. inline void reset(unsigned _timeout) { timeout = _timeout; t0 = msTick(); }
  101. unsigned timeLeft() const;
  102. inline unsigned getTimeout() const { return timeout; }
  103. private :
  104. unsigned timeout;
  105. unsigned t0;
  106. };
  107. unsigned TimeoutHandler::timeLeft() const
  108. {
  109. //This function is ambiguous and the caller must disambiguate timeout == 0 from timeLeft == 0
  110. if (timeout)
  111. {
  112. unsigned dt = msTick() - t0;
  113. if (dt < timeout)
  114. return timeout - dt;
  115. }
  116. return 0;
  117. }
  118. class Connection : public CInterface
  119. {
  120. friend class ConnectionContainer;
  121. public :
  122. Connection(ICodeContext * ctx, const char * _options, const char * _ip, int _port, bool parseOptions, int _database, const char * password, unsigned _timeout, bool selectDB);
  123. ~Connection() { freeContext(); }
  124. static Connection * createConnection(ICodeContext * ctx, Connection * & _cachedConnection, const char * options, const char * _ip, int _port, bool parseOptions, int _database, const char * password, unsigned _timeout, bool cachedConnectionRequested, bool isSubscription = false);
  125. //set
  126. template <class type> void setKey(ICodeContext * ctx, const char * key, type value, unsigned expire);
  127. template <class type> void setKey(ICodeContext * ctx, const char * key, size32_t valueSize, const type * value, unsigned expire);
  128. void setIntKey(ICodeContext * ctx, const char * key, signed __int64 value, unsigned expire, bool _unsigned);
  129. void setRealKey(ICodeContext * ctx, const char * key, double value, unsigned expire);
  130. //get
  131. template <class type> void getKey(ICodeContext * ctx, const char * key, type & value);
  132. template <class type> void getKey(ICodeContext * ctx, const char * key, size_t & valueSize, type * & value);
  133. template <class type> void getNumericKey(ICodeContext * ctx, const char * key, type & value);
  134. signed __int64 returnInt(const char * key, const char * cmd, const redisReply * reply);
  135. //-------------------------------LOCKING------------------------------------------------
  136. void lockSet(ICodeContext * ctx, const char * key, size32_t valueSize, const char * value, unsigned expire);
  137. void lockGet(ICodeContext * ctx, const char * key, size_t & valueSize, char * & value, const char * password, unsigned expire);
  138. void unlock(ICodeContext * ctx, const char * key);
  139. //--------------------------------------------------------------------------------------
  140. //-------------------------------PUB/SUB------------------------------------------------
  141. unsigned __int64 publish(ICodeContext * ctx, const char * keyOrChannel, size32_t messageSize, const char * message, int _database, bool lockedKey);
  142. void subAndWaitForSinglePub(ICodeContext * ctx, const char * keyOrChannel, size_t & messageSize, char * & message, int _database, bool lockedKey);
  143. //--------------------------------------------------------------------------------------
  144. void persist(ICodeContext * ctx, const char * key);
  145. void expire(ICodeContext * ctx, const char * key, unsigned _expire);
  146. void del(ICodeContext * ctx, const char * key);
  147. void clear(ICodeContext * ctx);
  148. unsigned __int64 dbSize(ICodeContext * ctx);
  149. bool exists(ICodeContext * ctx, const char * key);
  150. signed __int64 incrBy(ICodeContext * ctx, const char * key, signed __int64 value);
  151. protected : //Specific to subscribed connections
  152. void subscribe(ICodeContext * ctx, const char * channel);
  153. void unsubscribe();
  154. bool isCorrectChannel(const redisReply * reply, const char * op) const;
  155. int redisSetUnsubscribeTimeout();
  156. static int getUnsubscribeTimeout();
  157. static unsigned getUnsubscribeReadAttempts();
  158. protected :
  159. void freeContext();
  160. int redisSetTimeout();
  161. int setTimeout(unsigned _timeout);
  162. inline unsigned timeLeft() const { return timeout.timeLeft(); }
  163. void assertTimeout(int state);
  164. void redisConnect();
  165. void doParseOptions(ICodeContext * ctx, const char * _options);
  166. void connect(ICodeContext * ctx, int _database, const char * password, bool selectDB);
  167. inline bool isCachedConnection() const { return (this == cachedConnection) || (this == cachedPubConnection) || (this == cachedSubscriptionConnection); }
  168. void selectDB(ICodeContext * ctx, int _database);
  169. void readReply(Reply * reply);
  170. void readReplyAndAssert(Reply * reply, const char * msg);
  171. void readReplyAndAssertWithCmdMsg(Reply * reply, const char * msg, const char * key = nullptr);
  172. void assertKey(const redisReply * reply, const char * key);
  173. void assertAuthorization(const redisReply * reply);
  174. void assertOnError(const redisReply * reply, const char * _msg);
  175. void assertOnErrorWithCmdMsg(const redisReply * reply, const char * cmd, const char * key = nullptr);
  176. void assertConnection(const char * _msg);
  177. void assertConnectionWithCmdMsg(const char * cmd, const char * key = nullptr);
  178. __declspec(noreturn) void fail(const char * cmd, const char * errmsg, const char * key = nullptr) __attribute__((noreturn));
  179. void * redisCommand(const char * format, ...);
  180. void fromStr(const char * str, const char * key, double & ret);
  181. void fromStr(const char * str, const char * key, signed __int64 & ret);
  182. void fromStr(const char * str, const char * key, unsigned __int64 & ret);
  183. static unsigned hashServerIpPortPassword(ICodeContext * ctx, const char * _options, const char * password);
  184. static bool canCacheConnections(bool cachedConnectionRequested, bool isSubscription);
  185. static int getConnectionCachingLevel();
  186. static bool getCacheSubConnections();
  187. int writeBufferToSocket();
  188. bool isSameConnection(ICodeContext * ctx, const char * _options, const char * password) const;
  189. void reset(ICodeContext * ctx, unsigned _database, const char * password, unsigned _timeout, bool selectDB);
  190. //-------------------------------LOCKING------------------------------------------------
  191. void handleLockOnSet(ICodeContext * ctx, const char * key, const char * value, size_t size, unsigned expire);
  192. void handleLockOnGet(ICodeContext * ctx, const char * key, MemoryAttr * retVal, const char * password, unsigned expire);
  193. const char * encodeChannel(StringBuffer & buffer, const char * keyOrChannel, int _database, bool lockedKey) const;
  194. bool noScript(const redisReply * reply) const;
  195. bool lock(ICodeContext * ctx, const char * key, const char * channel, unsigned expire);
  196. //--------------------------------------------------------------------------------------
  197. protected :
  198. redisContext * context = nullptr;
  199. StringAttr options;
  200. StringAttr ip; //The default is set in parseOptions as "localhost"
  201. unsigned serverIpPortPasswordHash = 0;
  202. int port = 6379; //Default redis-server port
  203. TimeoutHandler timeout;
  204. int database = 0; //NOTE: redis stores the maximum number of dbs as an 'int'.
  205. StringAttr channel;
  206. bool subscribed = false;
  207. };
  208. class ConnectionContainer : public CInterface
  209. {
  210. public :
  211. ConnectionContainer() { }
  212. ConnectionContainer(Connection * _connection)
  213. {
  214. connection.setown(_connection);
  215. }
  216. ~ConnectionContainer()
  217. {
  218. if (connection)
  219. connection->unsubscribe();
  220. }
  221. inline Connection * operator -> () const { return connection.get(); }
  222. inline void setown(Connection * _connection) { connection.setown(_connection); }
  223. __declspec(noreturn) void handleException(IException * error) __attribute__((noreturn))
  224. {
  225. if (connection)
  226. connection->freeContext();
  227. throw error;
  228. }
  229. Owned<Connection> connection;
  230. };
  231. static void releaseAllCachedContexts()
  232. {
  233. if (cachedConnection)
  234. {
  235. cachedConnection->Release();
  236. cachedConnection = nullptr;
  237. }
  238. if (cachedPubConnection)
  239. {
  240. cachedPubConnection->Release();
  241. cachedPubConnection = nullptr;
  242. }
  243. if (cachedSubscriptionConnection)
  244. {
  245. cachedSubscriptionConnection->Release();
  246. cachedSubscriptionConnection = nullptr;
  247. }
  248. if (threadHookChain)
  249. {
  250. (*threadHookChain)();
  251. threadHookChain = nullptr;
  252. }
  253. threadHooked = false;
  254. }
  255. //The following class is here to ensure destruction of the cachedConnection within the main thread
  256. //as this is not handled by the thread hook mechanism.
  257. static class MainThreadCachedConnection
  258. {
  259. public :
  260. MainThreadCachedConnection() { }
  261. ~MainThreadCachedConnection() { releaseAllCachedContexts(); }
  262. } mainThread;
  263. Connection::Connection(ICodeContext * ctx, const char * _options, const char * _ip, int _port, bool parseOptions, int _database, const char * password, unsigned _timeout, bool selectDB)
  264. : timeout(_timeout)
  265. {
  266. serverIpPortPasswordHash = hashServerIpPortPassword(ctx, _options, password);
  267. options.set(_options, strlen(_options));
  268. if (parseOptions || !_ip || !_port)//parseOptions(true) is intended to be used when passing a valid ip & port but check just in case.
  269. doParseOptions(ctx, _options);
  270. else
  271. {
  272. port = _port;
  273. ip.set(_ip, strlen(_ip));
  274. }
  275. connect(ctx, _database, password, selectDB);
  276. }
  277. void Connection::redisConnect()
  278. {
  279. freeContext();
  280. if (timeout.getTimeout() == 0)
  281. context = ::redisConnect(ip.str(), port);
  282. else
  283. {
  284. unsigned timeStillLeft = timeLeft();
  285. if (timeStillLeft == 0)
  286. rtlFail(0, "Redis Plugin: ERROR - function timed out internally.");
  287. struct timeval to = { (time_t) (timeStillLeft/1000), (suseconds_t) ((timeStillLeft%1000)*1000) };
  288. context = ::redisConnectWithTimeout(ip.str(), port, to);
  289. }
  290. assertConnection("connection");
  291. }
  292. void Connection::connect(ICodeContext * ctx, int _database, const char * password, bool selectDB)
  293. {
  294. redisConnect();
  295. //The following is the dissemination of the two methods authenticate(ctx, password) & selectDB(ctx, _database)
  296. //such that they may be pipelined to save an extra round trip to the server and back.
  297. if (password && *password)
  298. redisAppendCommand(context, "AUTH %b", password, strlen(password));
  299. if (selectDB && (database != _database))
  300. {
  301. VStringBuffer cmd("SELECT %d", _database);
  302. redisAppendCommand(context, cmd.str());
  303. }
  304. //Now read replies.
  305. OwnedReply reply = new Reply();
  306. if (password && *password)
  307. readReplyAndAssert(reply, "server authentication");
  308. if (selectDB && (database != _database))
  309. {
  310. VStringBuffer cmd("SELECT %d", _database);
  311. readReplyAndAssertWithCmdMsg(reply, cmd.str());
  312. database = _database;
  313. }
  314. }
  315. void * Connection::redisCommand(const char * format, ...)
  316. {
  317. //Copied from https://github.com/redis/hiredis/blob/master/hiredis.c ~line:1008 void * redisCommand(redisContext * context, const char * format, ...)
  318. //with redisSetTimeout(); added.
  319. va_list parameters;
  320. void * reply = nullptr;
  321. va_start(parameters, format);
  322. assertTimeout(redisSetTimeout());
  323. reply = ::redisvCommand(context, format, parameters);
  324. va_end(parameters);
  325. return reply;
  326. }
  327. int Connection::setTimeout(unsigned _timeout)
  328. {
  329. struct timeval to = { (time_t) (_timeout/1000), (suseconds_t) ((_timeout%1000)*1000) };
  330. if (!context)
  331. return REDIS_ERR;
  332. return ::redisSetTimeout(context, to);//NOTE: ::redisSetTimeout sets the socket timeout and therefore 0 => forever
  333. }
  334. int Connection::redisSetTimeout()
  335. {
  336. unsigned timeStillLeft = timeLeft();
  337. if (timeStillLeft == 0 && timeout.getTimeout() != 0)
  338. return INTERNAL_TIMEOUT;
  339. return setTimeout(timeStillLeft);
  340. }
  341. int Connection::redisSetUnsubscribeTimeout()
  342. {
  343. unsigned timeout = getUnsubscribeTimeout();
  344. if (timeout == 0)//0 => no timeout => use normal timeout
  345. return redisSetTimeout();
  346. unsigned timeStillLeft = timeLeft();
  347. if (timeStillLeft == 0)
  348. return INTERNAL_TIMEOUT;
  349. unsigned tmp = unsubscribeTimeout < timeStillLeft ? unsubscribeTimeout : timeStillLeft;
  350. return setTimeout(tmp);
  351. }
  352. bool Connection::isSameConnection(ICodeContext * ctx, const char * _options, const char * password) const
  353. {
  354. return (hashServerIpPortPassword(ctx, _options, password) == serverIpPortPasswordHash);
  355. }
  356. unsigned Connection::hashServerIpPortPassword(ICodeContext * ctx, const char * _options, const char * password)
  357. {
  358. return hashc((const unsigned char*)_options, strlen(_options), hashc((const unsigned char*)password, strlen(password), 0));
  359. }
  360. void Connection::reset(ICodeContext * ctx, unsigned _database, const char * password, unsigned _timeout, bool selectDB)
  361. {
  362. timeout.reset(_timeout);
  363. if (!context || context->err != REDIS_OK)
  364. {
  365. database = 0;
  366. connect(ctx, _database, password, selectDB);
  367. }
  368. }
  369. void Connection::doParseOptions(ICodeContext * ctx, const char * _options)
  370. {
  371. StringArray optionStrings;
  372. optionStrings.appendList(_options, " ");
  373. ForEachItemIn(idx, optionStrings)
  374. {
  375. const char *opt = optionStrings.item(idx);
  376. if (strncmp(opt, "--SERVER=", 9) == 0)
  377. {
  378. opt += 9;
  379. StringArray splitPort;
  380. splitPort.appendList(opt, ":");
  381. if (splitPort.ordinality()==2)
  382. {
  383. ip.set(splitPort.item(0));
  384. port = atoi(splitPort.item(1));
  385. }
  386. }
  387. else
  388. {
  389. VStringBuffer err("Redis Plugin: ERROR - unsupported option string '%s'", opt);
  390. rtlFail(0, err.str());
  391. }
  392. }
  393. if (ip.isEmpty())
  394. {
  395. ip.set("localhost");
  396. if (ctx)
  397. {
  398. VStringBuffer msg("Redis Plugin: WARNING - using default cache (%s:%d)", ip.str(), port);
  399. ctx->logString(msg.str());
  400. }
  401. }
  402. }
  403. void Connection::freeContext()
  404. {
  405. subscribed = false;
  406. channel.clear();
  407. if(context)
  408. {
  409. redisFree(context);
  410. context = nullptr;
  411. database = 0;
  412. }
  413. }
  414. const char * Connection::encodeChannel(StringBuffer & buffer, const char * keyOrChannel, int _database, bool lockedKey) const
  415. {
  416. if (lockedKey)
  417. buffer.append(REDIS_LOCK_PREFIX).append("_").append(keyOrChannel).append("_").append(_database);
  418. else
  419. buffer.set(keyOrChannel);
  420. return buffer.str();
  421. }
  422. bool Connection::isCorrectChannel(const redisReply * reply, const char * op) const
  423. {
  424. if (!reply || channel.isEmpty())
  425. return false;
  426. return (reply->type == REDIS_REPLY_ARRAY)
  427. && (reply->elements > 1)
  428. && (strcmp(op, reply->element[0]->str) == 0)
  429. && (strcmp(channel.str(), reply->element[1]->str) == 0);
  430. }
  431. void Connection::subscribe(ICodeContext * ctx, const char * _channel)
  432. {
  433. assert(!subscribed || channel.isEmpty());//If this is a reused subscriptionConnection then this implies that it was not correctly unsubscribed/reset.
  434. channel.set(_channel);
  435. OwnedReply reply = Reply::createReply(redisCommand("SUBSCRIBE %b", channel.str(), (size_t)channel.length()));
  436. /* It is possible for the subscription to succeed in being registered by the server but fails in receiving the associated reply.
  437. * Set early to prevent not unsubscribing when failing.
  438. */
  439. subscribed = true;
  440. assertOnErrorWithCmdMsg(reply->query(), "SUBSCRIBE", channel.str());
  441. if (!isCorrectChannel(reply->query(), "subscribe"))
  442. fail("SUBSCRIBE", "failed to register SUB", channel.str());
  443. }
  444. void Connection::subAndWaitForSinglePub(ICodeContext * ctx, const char * keyOrChannel, size_t & messageSize, char * & message, int _database, bool lockedKey)
  445. {
  446. StringBuffer channelBuffer;
  447. encodeChannel(channelBuffer, keyOrChannel, _database, lockedKey);
  448. subscribe(ctx, channelBuffer.str());
  449. //Now wait for published message
  450. OwnedReply reply = new Reply();
  451. readReply(reply);
  452. assertOnErrorWithCmdMsg(reply->query(), "SUBSCRIBE", channel.str());
  453. if (isCorrectChannel(reply->query(), "message"))
  454. {
  455. if (reply->query()->element[2]->len > 0)
  456. {
  457. messageSize = (size_t)reply->query()->element[2]->len;
  458. message = reinterpret_cast<char*>(allocateAndCopy(reply->query()->element[2]->str, messageSize));
  459. }
  460. else
  461. {
  462. messageSize = 0;
  463. message = nullptr;
  464. }
  465. unsubscribe();
  466. return;
  467. }
  468. throwUnexpected();
  469. }
  470. int Connection::writeBufferToSocket()
  471. {
  472. int done = 0;
  473. if (context->flags & REDIS_BLOCK)
  474. {
  475. /* Write until done */
  476. while (!done)
  477. {
  478. if (redisBufferWrite(context, &done) == REDIS_ERR)
  479. return REDIS_ERR;
  480. }
  481. }
  482. return REDIS_OK;
  483. }
  484. unsigned Connection::getUnsubscribeReadAttempts()
  485. {
  486. if (!unsubscribeReadAttemptsChecked)//unsubscribeReadAttemptsChecked is std:atomic<bool>. Test to guard against unnecessary critical section
  487. {
  488. CriticalBlock block(critsec);
  489. if (!unsubscribeReadAttemptsChecked)
  490. {
  491. const char * tmp = getenv("HPCC_REDIS_PLUGIN_UNSUBSCRIBE_READ_ATTEMPTS");//ms
  492. if (tmp && *tmp)
  493. unsubscribeReadAttempts = atoi(tmp);
  494. unsubscribeReadAttemptsChecked = true;
  495. }
  496. }
  497. return unsubscribeReadAttempts;
  498. }
  499. void Connection::unsubscribe()
  500. {
  501. /* redisContext has both an output buffer (context->obuf) and an input buffer (context->reader).
  502. * redisCommand writes the command to the output buffer and then calls redisGetReply. This will first try to read unconsumed replies from the input buffer.
  503. * If there are none then it will flush the output buffer to the socket and wait for a (or multiples of) redisReply from the socket which writes this to the input buffer.
  504. * This is undesired behaviour here as it will not send the UNSUBSCRIBE command until all replies are consumed on the input buffer. Furthermore, there could be
  505. * spurious commands still in the output buffer preceding the UNSIBSCRIBE, though in the current plugin implementation there shouldn't be, unless in a failing state.
  506. * To solve these two (client) issues both buffers are cleared before unsubscribing. However, the same applies for the server side output buffer and more importantly the
  507. * client socket file descriptor as the redis server pushes published messages to clients. In order to reuse the connection for subsequent subscriptions this unsubscribe
  508. * must be confirmed and in order to do this all (now) spurious preceding replies must first be consumed. Because a single socket read will read more than a single
  509. * redis reply (if >1 exists waiting on the server), we can switch subsequent reads to just the input buffer. The point here is that we want to limit the number of
  510. * possible socket reads and thus possible waits. We then only make a maximum of HPCC_REDIS_PLUGIN_UNSUBSCRIBE_READ_ATTEMPTS socket reads.
  511. */
  512. if (!subscribed)
  513. return;
  514. //return early
  515. if (!context || (context->err != REDIS_OK) || channel.isEmpty())
  516. {
  517. freeContext();
  518. return;
  519. }
  520. /* hiredis v0.12.0 is broken (hiredis.h includes read.h but read.h is not installed), and <=v0.11.0 sds.h is neither installed nor included in hiredis.h.
  521. *
  522. * SubConnections are only used to sub and unsub. They only sub to a single channel at a time (currently) so only an un-flushed UNSUBSCRIBE may still be
  523. * still be present in the output buffer. If so it will either be for the same channel or another and thus is benign in nature as long as the channel is
  524. * is also confirmed in the reply. This implies that it should be ok to not clear the output buffer. Further more, connection caching is only used for
  525. * hiredis >= v0.13.0 which is where this is preferably needed.
  526. */
  527. #if HIREDIS_MAJOR >= 0 && 12 >= MIN_HIREDIS_MINOR && HIREDIS_PATCH >= 1
  528. //Empty output buffer as it may contain previous and now unwanted commands. Since the subscription connections only sub and unsub, this should already be empty.
  529. if (*context->obuf != '\0')//obuf is a redis sds string (chr*) containing a header with the actual pointer pointing directly to string buffer post header.
  530. {
  531. sdsfree(context->obuf);//free/clear current buffer
  532. context->obuf = sdsempty();//setup new one ready for writing
  533. }
  534. #endif
  535. //Empty input buffer as it may contain previous and now unwanted replies
  536. if (context->reader->len > 0)
  537. {
  538. redisReaderFree(context->reader);
  539. context->reader = redisReaderCreate();
  540. }
  541. //Write command to buffer, set timeout, and write to socket.
  542. bool cmdAppendOK = redisAppendCommand(context, "UNSUBSCRIBE %b", channel.str(), channel.length());
  543. if ((cmdAppendOK != REDIS_OK) || (redisSetUnsubscribeTimeout() != REDIS_OK) || (writeBufferToSocket() != REDIS_OK))
  544. {
  545. freeContext();
  546. return;
  547. }
  548. OwnedReply reply = new Reply();
  549. for (unsigned i = 0; i < getUnsubscribeReadAttempts(); i++)
  550. {
  551. if (redisSetUnsubscribeTimeout() != REDIS_OK)
  552. {
  553. freeContext();
  554. return;
  555. }
  556. redisReply * nakedReply = nullptr;
  557. redisGetReply(context, (void**)&nakedReply);
  558. reply->setClear(nakedReply);
  559. if (!reply->query())
  560. {
  561. freeContext();
  562. return;
  563. }
  564. if (isCorrectChannel(reply->query(), "unsubscribe"))
  565. {
  566. channel.clear();
  567. subscribed = false;
  568. return;
  569. }
  570. /* Whilst the input buffer was cleared the same may not be true for that server side.
  571. * We can read as many replies from the reader as we like but only 'unsubscribeReadAttempts'
  572. * from the socket.
  573. */
  574. bool replyErrorFound = (reply->query()->type == REDIS_REPLY_ERROR);
  575. for(;;)
  576. {
  577. redisReply * nakedReply = nullptr;
  578. if (redisReaderGetReply(context->reader, (void**)&nakedReply) != REDIS_OK)
  579. {
  580. freeContext();
  581. return;
  582. }
  583. if (!nakedReply)
  584. break;
  585. reply->setClear(nakedReply);
  586. if (nakedReply->type == REDIS_REPLY_ERROR)
  587. {
  588. replyErrorFound = true;
  589. continue;
  590. }
  591. if (isCorrectChannel(reply->query(), "unsubscribe"))
  592. {
  593. channel.clear();
  594. subscribed = false;
  595. return;
  596. }
  597. }
  598. /* If a reply error was encountered there is no way to know if it was
  599. * associated with the unsubscribe attempt of from a previous and unwanted
  600. * reply, at this point. Either it was, in which case we need to clear up or read
  601. * over from the socket again. The latter is not acceptable in case it *was* associated
  602. * and thus there are no more replies and therefore not wasting time for the read to time out.
  603. */
  604. if (replyErrorFound)
  605. {
  606. freeContext();
  607. return;
  608. }
  609. }
  610. freeContext();
  611. }
  612. void Connection::assertTimeout(int state)
  613. {
  614. switch(state)
  615. {
  616. case REDIS_OK :
  617. return;
  618. case REDIS_ERR :
  619. assertConnection("request to set timeout");
  620. break;
  621. case INTERNAL_TIMEOUT :
  622. rtlFail(0, "Redis Plugin: ERROR - function timed out internally.");
  623. }
  624. }
  625. void Connection::readReply(Reply * reply)
  626. {
  627. redisReply * nakedReply = nullptr;
  628. assertTimeout(redisSetTimeout());
  629. redisGetReply(context, (void**)&nakedReply);
  630. reply->setClear(nakedReply);
  631. }
  632. void Connection::readReplyAndAssert(Reply * reply, const char * msg)
  633. {
  634. readReply(reply);
  635. assertOnError(reply->query(), msg);
  636. }
  637. void Connection::readReplyAndAssertWithCmdMsg(Reply * reply, const char * msg, const char * key)
  638. {
  639. readReply(reply);
  640. assertOnErrorWithCmdMsg(reply->query(), msg, key);
  641. }
  642. int Connection::getConnectionCachingLevel()
  643. {
  644. //Fetch connection caching level
  645. if (!connectionCachingLevelChecked)//connectionCachingLevelChecked is std:atomic<bool>. Test to guard against unnecessary critical section
  646. {
  647. CriticalBlock block(critsec);
  648. if (!connectionCachingLevelChecked)
  649. {
  650. const char * tmp = getenv("HPCC_REDIS_PLUGIN_CONNECTION_CACHING_LEVEL"); // 0 = NO_CONNECTION_CACHING, 1 = ALLOW_CONNECTION_CACHING, 2 = CACHE_ALL_CONNECTIONS
  651. //connectionCachingLevel is already defaulted to ALLOW_CONNECTION_CACHING
  652. if (tmp && *tmp)
  653. connectionCachingLevel = atoi(tmp); //don't bother range checking
  654. connectionCachingLevelChecked = true;
  655. }
  656. }
  657. return connectionCachingLevel;
  658. }
  659. bool Connection::getCacheSubConnections()
  660. {
  661. if (!cacheSubConnectionsOptChecked)//cacheSubConnectionsOptChecked is std:atomic<bool>. Test to guard against unnecessary critical section
  662. {
  663. CriticalBlock block(critsec);
  664. if (!cacheSubConnectionsOptChecked)
  665. {
  666. const char * tmp = getenv("HPCC_REDIS_PLUGIN_CACHE_SUB_CONNECTIONS");
  667. //cacheSubConnections is already defaulted to true;
  668. if (tmp && *tmp)
  669. {
  670. //less ops to check on & true however, making cacheSubConnections(false) if not met would do also for misspelled versions.
  671. //Since the default is ON, misspelling on or true means/does nothing.
  672. if (*tmp == '0' || (stricmp("off", tmp) == 0) || (stricmp("false", tmp) == 0))
  673. cacheSubConnections = false;
  674. }
  675. cacheSubConnectionsOptChecked= true;
  676. }
  677. }
  678. return cacheSubConnections;
  679. }
  680. int Connection::getUnsubscribeTimeout()
  681. {
  682. if (!unsubscribeTimeoutChecked)//unsubscribeTimeoutChecked is std:atomic<bool>. Test to guard against unnecessary critical section
  683. {
  684. CriticalBlock block(critsec);
  685. if (!unsubscribeTimeoutChecked)
  686. {
  687. const char * tmp = getenv("HPCC_REDIS_PLUGIN_UNSUBSCRIBE_TIMEOUT");//ms
  688. if (tmp && *tmp)
  689. unsubscribeTimeout = atoi(tmp);
  690. unsubscribeTimeoutChecked = true;
  691. }
  692. }
  693. return unsubscribeTimeout;
  694. }
  695. bool Connection::canCacheConnections(bool cachedConnectionRequested, bool isSubscription)
  696. {
  697. #if HIREDIS_VERSION_OK_FOR_CACHING
  698. switch (getConnectionCachingLevel())
  699. {
  700. case CACHE_ALL_CONNECTIONS :
  701. return true;
  702. case NO_CONNECTION_CACHING :
  703. return false;
  704. }
  705. if (isSubscription)
  706. return cachedConnectionRequested && getCacheSubConnections();
  707. return cachedConnectionRequested;
  708. #endif
  709. return false;
  710. }
  711. static void addThreadHook()
  712. {
  713. if (!threadHooked)
  714. {
  715. threadHookChain = addThreadTermFunc(releaseAllCachedContexts);
  716. threadHooked = true;
  717. }
  718. }
  719. Connection * Connection::createConnection(ICodeContext * ctx, Connection * & _cachedConnection, const char * _options, const char * _ip, int _port, bool parseOptions, int _database, const char * password, unsigned _timeout, bool cachedConnectionRequested, bool isSubscription)
  720. {
  721. if (canCacheConnections(cachedConnectionRequested, isSubscription))
  722. {
  723. if (!_cachedConnection)
  724. {
  725. _cachedConnection = new Connection(ctx, _options, _ip, _port, parseOptions, _database, password, _timeout, !isSubscription);
  726. addThreadHook();
  727. return LINK(_cachedConnection);
  728. }
  729. if (_cachedConnection->isSameConnection(ctx, _options, password))
  730. {
  731. //MORE: should perhaps check that the connection has not expired (think hiredis REDIS_KEEPALIVE_INTERVAL is defaulted to 15s).
  732. _cachedConnection->reset(ctx, _database, password, _timeout, !isSubscription);//If the context had been previously freed, this will reconnect and selectDB in connect().
  733. _cachedConnection->selectDB(ctx, _database);//If the context is still present selectDB here.
  734. return LINK(_cachedConnection);
  735. }
  736. _cachedConnection->Release();
  737. _cachedConnection = nullptr;
  738. _cachedConnection = new Connection(ctx, _options, _ip, _port, parseOptions, _database, password, _timeout, !isSubscription);
  739. return LINK(_cachedConnection);
  740. }
  741. else
  742. return new Connection(ctx, _options, _ip, _port, parseOptions, _database, password, _timeout, !isSubscription);
  743. }
  744. void Connection::selectDB(ICodeContext * ctx, int _database)
  745. {
  746. if (database == _database || subscribed)
  747. return;
  748. database = _database;
  749. VStringBuffer cmd("SELECT %d", database);
  750. OwnedReply reply = Reply::createReply(redisCommand(cmd.str()));
  751. assertOnErrorWithCmdMsg(reply->query(), cmd.str());
  752. }
  753. void Connection::fail(const char * cmd, const char * errmsg, const char * key)
  754. {
  755. if (key)
  756. {
  757. VStringBuffer msg("Redis Plugin: ERROR - %s '%s' on database %d for %s:%d failed : %s", cmd, key, database, ip.str(), port, errmsg);
  758. rtlFail(0, msg.str());
  759. }
  760. VStringBuffer msg("Redis Plugin: ERROR - %s on database %d for %s:%d failed : %s", cmd, database, ip.str(), port, errmsg);
  761. rtlFail(0, msg.str());
  762. }
  763. void Connection::assertOnError(const redisReply * reply, const char * _msg)
  764. {
  765. if (!reply)
  766. {
  767. assertConnection(_msg);
  768. throwUnexpected();
  769. }
  770. else if (reply->type == REDIS_REPLY_ERROR)
  771. {
  772. assertAuthorization(reply);
  773. VStringBuffer msg("Redis Plugin: %s - %s", _msg, reply->str);
  774. rtlFail(0, msg.str());
  775. }
  776. }
  777. void Connection::assertOnErrorWithCmdMsg(const redisReply * reply, const char * cmd, const char * key)
  778. {
  779. if (!reply)
  780. {
  781. assertConnectionWithCmdMsg(cmd, key);
  782. throwUnexpected();
  783. }
  784. else if (reply->type == REDIS_REPLY_ERROR)
  785. {
  786. assertAuthorization(reply);
  787. fail(cmd, reply->str, key);
  788. }
  789. }
  790. void Connection::assertAuthorization(const redisReply * reply)
  791. {
  792. if (reply && reply->str && ( strncmp(reply->str, "NOAUTH", 6) == 0 || strncmp(reply->str, "ERR operation not permitted", 27) == 0 ))
  793. {
  794. VStringBuffer msg("Redis Plugin: ERROR - authentication for %s:%d failed : %s", ip.str(), port, reply->str);
  795. rtlFail(0, msg.str());
  796. }
  797. }
  798. void Connection::assertKey(const redisReply * reply, const char * key)
  799. {
  800. if (reply && reply->type == REDIS_REPLY_NIL)
  801. {
  802. VStringBuffer msg("Redis Plugin: ERROR - the requested key '%s' does not exist on database %d on %s:%d", key, database, ip.str(), port);
  803. rtlFail(0, msg.str());
  804. }
  805. }
  806. void Connection::assertConnectionWithCmdMsg(const char * cmd, const char * key)
  807. {
  808. if (!context)
  809. fail(cmd, "neither 'reply' nor connection error available", key);
  810. else if (context->err)
  811. fail(cmd, context->errstr, key);
  812. }
  813. void Connection::assertConnection(const char * _msg)
  814. {
  815. if (!context)
  816. {
  817. VStringBuffer msg("Redis Plugin: ERROR - %s for %s:%d failed : neither 'reply' nor connection error available", _msg, ip.str(), port);
  818. rtlFail(0, msg.str());
  819. }
  820. else if (context->err)
  821. {
  822. VStringBuffer msg("Redis Plugin: ERROR - %s for %s:%d failed : %s", _msg, ip.str(), port, context->errstr);
  823. rtlFail(0, msg.str());
  824. }
  825. }
  826. void Connection::clear(ICodeContext * ctx)
  827. {
  828. //NOTE: flush is the actual cache flush/clear/delete and not an io buffer flush.
  829. OwnedReply reply = Reply::createReply(redisCommand("FLUSHDB"));//NOTE: FLUSHDB deletes current database where as FLUSHALL deletes all dbs.
  830. //NOTE: documented as never failing, but in case
  831. assertOnErrorWithCmdMsg(reply->query(), "FlushDB");
  832. }
  833. void Connection::del(ICodeContext * ctx, const char * key)
  834. {
  835. OwnedReply reply = Reply::createReply(redisCommand("DEL %b", key, strlen(key)));
  836. assertOnErrorWithCmdMsg(reply->query(), "Del", key);
  837. }
  838. void Connection::persist(ICodeContext * ctx, const char * key)
  839. {
  840. OwnedReply reply = Reply::createReply(redisCommand("PERSIST %b", key, strlen(key)));
  841. assertOnErrorWithCmdMsg(reply->query(), "Persist", key);
  842. }
  843. void Connection::expire(ICodeContext * ctx, const char * key, unsigned _expire)
  844. {
  845. OwnedReply reply = Reply::createReply(redisCommand("PEXPIRE %b %u", key, strlen(key), _expire));
  846. assertOnErrorWithCmdMsg(reply->query(), "Expire", key);
  847. }
  848. bool Connection::exists(ICodeContext * ctx, const char * key)
  849. {
  850. OwnedReply reply = Reply::createReply(redisCommand("EXISTS %b", key, strlen(key)));
  851. assertOnErrorWithCmdMsg(reply->query(), "Exists", key);
  852. return (reply->query()->integer != 0);
  853. }
  854. unsigned __int64 Connection::dbSize(ICodeContext * ctx)
  855. {
  856. OwnedReply reply = Reply::createReply(redisCommand("DBSIZE"));
  857. assertOnErrorWithCmdMsg(reply->query(), "DBSIZE");
  858. return reply->query()->integer;
  859. }
  860. signed __int64 Connection::incrBy(ICodeContext * ctx, const char * key, signed __int64 value)
  861. {
  862. OwnedReply reply = Reply::createReply(redisCommand("INCRBY %b %" I64F "d", key, strlen(key), value));
  863. return returnInt(key, "INCRBY", reply->query());
  864. }
  865. //-------------------------------------------SET-----------------------------------------
  866. void Connection::setIntKey(ICodeContext * ctx, const char * key, signed __int64 value, unsigned expire, bool _unsigned)
  867. {
  868. StringBuffer cmd("SET %b %" I64F);
  869. if (_unsigned)
  870. cmd.append("u");
  871. else
  872. cmd.append("d");
  873. appendExpire(cmd, expire);
  874. OwnedReply reply = Reply::createReply(redisCommand(cmd.str(), key, strlen(key), value));
  875. assertOnErrorWithCmdMsg(reply->query(), "SET", key);
  876. }
  877. void Connection::setRealKey(ICodeContext * ctx, const char * key, double value, unsigned expire)
  878. {
  879. StringBuffer cmd("SET %b %.16g");
  880. appendExpire(cmd, expire);
  881. OwnedReply reply = Reply::createReply(redisCommand(cmd.str(), key, strlen(key), value));
  882. assertOnErrorWithCmdMsg(reply->query(), "SET", key);
  883. }
  884. //--OUTER--
  885. template<class type> void SyncRSet(ICodeContext * ctx, const char * _options, const char * key, type value, int database, unsigned expire, const char * password, unsigned _timeout, bool cachedConnectionRequested)
  886. {
  887. ConnectionContainer master;
  888. try
  889. {
  890. master.setown(Connection::createConnection(ctx, cachedConnection, _options, DUMMY_IP, DUMMY_PORT, true, database, password, _timeout, cachedConnectionRequested));
  891. master->setKey(ctx, key, value, expire);
  892. }
  893. catch (IException * error)
  894. {
  895. master.handleException(error);
  896. }
  897. }
  898. //Set pointer types
  899. template<class type> void SyncRSet(ICodeContext * ctx, const char * _options, const char * key, size32_t valueSize, const type * value, int database, unsigned expire, const char * password, unsigned _timeout, bool cachedConnectionRequested)
  900. {
  901. ConnectionContainer master;
  902. try
  903. {
  904. master.setown(Connection::createConnection(ctx, cachedConnection, _options, DUMMY_IP, DUMMY_PORT, true, database, password, _timeout, cachedConnectionRequested));
  905. master->setKey(ctx, key, valueSize, value, expire);
  906. }
  907. catch (IException * error)
  908. {
  909. master.handleException(error);
  910. }
  911. }
  912. //--INNER--
  913. template<class type> void Connection::setKey(ICodeContext * ctx, const char * key, type value, unsigned expire)
  914. {
  915. const char * _value = reinterpret_cast<const char *>(&value);//Do this even for char * to prevent compiler complaining
  916. StringBuffer cmd("SET %b %b");
  917. appendExpire(cmd, expire);
  918. OwnedReply reply = Reply::createReply(redisCommand(cmd.str(), key, strlen(key), _value, sizeof(type)));
  919. assertOnErrorWithCmdMsg(reply->query(), "SET", key);
  920. }
  921. template<class type> void Connection::setKey(ICodeContext * ctx, const char * key, size32_t valueSize, const type * value, unsigned expire)
  922. {
  923. const char * _value = reinterpret_cast<const char *>(value);//Do this even for char * to prevent compiler complaining
  924. StringBuffer cmd("SET %b %b");
  925. appendExpire(cmd, expire);
  926. OwnedReply reply = Reply::createReply(redisCommand(cmd.str(), key, strlen(key), _value, (size_t)valueSize));
  927. assertOnErrorWithCmdMsg(reply->query(), "SET", key);
  928. }
  929. //-------------------------------------------GET-----------------------------------------
  930. signed __int64 Connection::returnInt(const char * key, const char * cmd, const redisReply * reply)
  931. {
  932. assertOnErrorWithCmdMsg(reply, cmd, key);
  933. assertKey(reply, key);
  934. if (reply->type == REDIS_REPLY_INTEGER)
  935. return reply->integer;
  936. fail(cmd, "expected RESP integer from redis", key);
  937. throwUnexpected(); //stop compiler complaining
  938. }
  939. //--OUTER--
  940. template<class type> void SyncRGetNumeric(ICodeContext * ctx, const char * options, const char * key, type & returnValue, int database, const char * password, unsigned _timeout, bool cachedConnectionRequested)
  941. {
  942. ConnectionContainer master;
  943. try
  944. {
  945. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, _timeout, cachedConnectionRequested));
  946. master->getNumericKey(ctx, key, returnValue);
  947. }
  948. catch (IException * error)
  949. {
  950. master.handleException(error);
  951. }
  952. }
  953. template<class type> void SyncRGet(ICodeContext * ctx, const char * options, const char * key, type & returnValue, int database, const char * password, unsigned _timeout, bool cachedConnectionRequested)
  954. {
  955. ConnectionContainer master;
  956. try
  957. {
  958. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, _timeout, cachedConnectionRequested));
  959. master->getKey(ctx, key, returnValue);
  960. }
  961. catch (IException * error)
  962. {
  963. master.handleException(error);
  964. }
  965. }
  966. template<class type> void SyncRGet(ICodeContext * ctx, const char * options, const char * key, size_t & returnSize, type * & returnValue, int database, const char * password, unsigned _timeout, bool cachedConnectionRequested)
  967. {
  968. ConnectionContainer master;
  969. try
  970. {
  971. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, _timeout, cachedConnectionRequested));
  972. master->getKey(ctx, key, returnSize, returnValue);
  973. }
  974. catch (IException * error)
  975. {
  976. master.handleException(error);
  977. }
  978. }
  979. void Connection::fromStr(const char * str, const char * key, double & ret)
  980. {
  981. char * end = nullptr;
  982. ret = strtod(str, &end);
  983. if (errno == ERANGE)
  984. fail("GetReal", "value returned out of range", key);
  985. }
  986. void Connection::fromStr(const char * str, const char * key, signed __int64 & ret)
  987. {
  988. char* end = nullptr;
  989. ret = strtoll(str, &end, 10);
  990. if (errno == ERANGE)
  991. fail("GetInteger", "value returned out of range", key);
  992. }
  993. void Connection::fromStr(const char * str, const char * key, unsigned __int64 & ret)
  994. {
  995. char* end = nullptr;
  996. ret = strtoull(str, &end, 10);
  997. if (errno == ERANGE)
  998. fail("GetUnsigned", "value returned out of range", key);
  999. }
  1000. //--INNER--
  1001. template<class type> void Connection::getNumericKey(ICodeContext * ctx, const char * key, type & returnValue)
  1002. {
  1003. OwnedReply reply = Reply::createReply(redisCommand("GET %b", key, strlen(key)));
  1004. assertOnErrorWithCmdMsg(reply->query(), "GET", key);
  1005. assertKey(reply->query(), key);
  1006. fromStr(reply->query()->str, key, returnValue);
  1007. }
  1008. template<class type> void Connection::getKey(ICodeContext * ctx, const char * key, type & returnValue)
  1009. {
  1010. OwnedReply reply = Reply::createReply(redisCommand("GET %b", key, strlen(key)));
  1011. assertOnErrorWithCmdMsg(reply->query(), "GET", key);
  1012. assertKey(reply->query(), key);
  1013. size_t returnSize = reply->query()->len;
  1014. if (sizeof(type)!=returnSize)
  1015. {
  1016. VStringBuffer msg("requested type of different size (%uB) from that stored (%uB)", (unsigned)sizeof(type), (unsigned)returnSize);
  1017. fail("GET", msg.str(), key);
  1018. }
  1019. memcpy(&returnValue, reply->query()->str, returnSize);
  1020. }
  1021. template<class type> void Connection::getKey(ICodeContext * ctx, const char * key, size_t & returnSize, type * & returnValue)
  1022. {
  1023. OwnedReply reply = Reply::createReply(redisCommand("GET %b", key, strlen(key)));
  1024. assertOnErrorWithCmdMsg(reply->query(), "GET", key);
  1025. assertKey(reply->query(), key);
  1026. returnSize = reply->query()->len;
  1027. returnValue = reinterpret_cast<type*>(allocateAndCopy(reply->query()->str, returnSize));
  1028. }
  1029. unsigned __int64 Connection::publish(ICodeContext * ctx, const char * keyOrChannel, size32_t messageSize, const char * message, int _database, bool lockedKey)
  1030. {
  1031. StringBuffer channel;
  1032. encodeChannel(channel, keyOrChannel, _database, lockedKey);
  1033. OwnedReply reply = Reply::createReply(redisCommand("PUBLISH %b %b", channel.str(), (size_t)channel.length(), message, (size_t)messageSize));
  1034. assertOnErrorWithCmdMsg(reply->query(), "PUBLISH", channel.str());
  1035. if (reply->query()->type == REDIS_REPLY_INTEGER)
  1036. {
  1037. if (reply->query()->integer >= 0)
  1038. return (unsigned __int64)reply->query()->integer;
  1039. else
  1040. throwUnexpected();
  1041. }
  1042. throwUnexpected();
  1043. }
  1044. //--------------------------------------------------------------------------------
  1045. // ECL SERVICE ENTRYPOINTS
  1046. //--------------------------------------------------------------------------------
  1047. ECL_REDIS_API unsigned __int64 ECL_REDIS_CALL SyncRPub(ICodeContext * ctx, const char * keyOrChannel, size32_t messageSize, const char * message, const char * options, int database, const char * password, unsigned timeout, bool lockedKey, bool cachedConnectionRequested)
  1048. {
  1049. ConnectionContainer master;
  1050. try
  1051. {
  1052. master.setown(Connection::createConnection(ctx, cachedPubConnection, options, DUMMY_IP, DUMMY_PORT, true, 0, password, timeout, cachedConnectionRequested));
  1053. return master->publish(ctx, keyOrChannel, messageSize, message, database, lockedKey);
  1054. }
  1055. catch (IException * error)
  1056. {
  1057. master.handleException(error);
  1058. }
  1059. }
  1060. ECL_REDIS_API void ECL_REDIS_CALL SyncRSub(ICodeContext * ctx, size32_t & messageSize, char * & message, const char * keyOrChannel, const char * options, int database, const char * password, unsigned timeout, bool lockedKey, bool cachedConnectionRequested)
  1061. {
  1062. size_t _messageSize = 0;
  1063. ConnectionContainer master;
  1064. try
  1065. {
  1066. master.setown(Connection::createConnection(ctx, cachedSubscriptionConnection, options, DUMMY_IP, DUMMY_PORT, true, 0, password, timeout, cachedConnectionRequested, true));
  1067. master->subAndWaitForSinglePub(ctx, keyOrChannel, _messageSize, message, database, lockedKey);
  1068. messageSize = static_cast<size32_t>(_messageSize);
  1069. }
  1070. catch (IException * error)
  1071. {
  1072. master.handleException(error);
  1073. }
  1074. }
  1075. ECL_REDIS_API void ECL_REDIS_CALL RClear(ICodeContext * ctx, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1076. {
  1077. ConnectionContainer master;
  1078. try
  1079. {
  1080. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1081. master->clear(ctx);
  1082. }
  1083. catch (IException * error)
  1084. {
  1085. master.handleException(error);
  1086. }
  1087. }
  1088. ECL_REDIS_API bool ECL_REDIS_CALL RExist(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1089. {
  1090. ConnectionContainer master;
  1091. try
  1092. {
  1093. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1094. return master->exists(ctx, key);
  1095. }
  1096. catch (IException * error)
  1097. {
  1098. master.handleException(error);
  1099. }
  1100. }
  1101. ECL_REDIS_API void ECL_REDIS_CALL RDel(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1102. {
  1103. ConnectionContainer master;
  1104. try
  1105. {
  1106. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1107. master->del(ctx, key);
  1108. }
  1109. catch (IException * error)
  1110. {
  1111. master.handleException(error);
  1112. }
  1113. }
  1114. ECL_REDIS_API void ECL_REDIS_CALL RPersist(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1115. {
  1116. ConnectionContainer master;
  1117. try
  1118. {
  1119. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1120. master->persist(ctx, key);
  1121. }
  1122. catch (IException * error)
  1123. {
  1124. master.handleException(error);
  1125. }
  1126. }
  1127. ECL_REDIS_API void ECL_REDIS_CALL RExpire(ICodeContext * ctx, const char * key, const char * options, int database, unsigned _expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1128. {
  1129. ConnectionContainer master;
  1130. try
  1131. {
  1132. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1133. master->expire(ctx, key, _expire);
  1134. }
  1135. catch (IException * error)
  1136. {
  1137. master.handleException(error);
  1138. }
  1139. }
  1140. ECL_REDIS_API unsigned __int64 ECL_REDIS_CALL RDBSize(ICodeContext * ctx, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1141. {
  1142. ConnectionContainer master;
  1143. try
  1144. {
  1145. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1146. return master->dbSize(ctx);
  1147. }
  1148. catch (IException * error)
  1149. {
  1150. master.handleException(error);
  1151. }
  1152. }
  1153. ECL_REDIS_API signed __int64 ECL_REDIS_CALL SyncRINCRBY(ICodeContext * ctx, const char * key, signed __int64 value, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1154. {
  1155. ConnectionContainer master;
  1156. try
  1157. {
  1158. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1159. return master->incrBy(ctx, key, value);
  1160. }
  1161. catch (IException * error)
  1162. {
  1163. master.handleException(error);
  1164. }
  1165. }
  1166. //-----------------------------------SET------------------------------------------
  1167. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetStr(ICodeContext * ctx, const char * key, size32_t valueSize, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1168. {
  1169. SyncRSet(ctx, options, key, valueSize, value, database, expire, password, timeout, cachedConnectionRequested);
  1170. }
  1171. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetUChar(ICodeContext * ctx, const char * key, size32_t valueLength, const UChar * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1172. {
  1173. SyncRSet(ctx, options, key, (valueLength)*sizeof(UChar), value, database, expire, password, timeout, cachedConnectionRequested);
  1174. }
  1175. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetInt(ICodeContext * ctx, const char * key, signed __int64 value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1176. {
  1177. ConnectionContainer master;
  1178. try
  1179. {
  1180. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1181. master->setIntKey(ctx, key, value, expire, false);
  1182. }
  1183. catch (IException * error)
  1184. {
  1185. master.handleException(error);
  1186. }
  1187. }
  1188. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetUInt(ICodeContext * ctx, const char * key, unsigned __int64 value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1189. {
  1190. ConnectionContainer master;
  1191. try
  1192. {
  1193. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1194. master->setIntKey(ctx, key, value, expire, true);
  1195. }
  1196. catch (IException * error)
  1197. {
  1198. master.handleException(error);
  1199. }
  1200. }
  1201. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetReal(ICodeContext * ctx, const char * key, double value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1202. {
  1203. ConnectionContainer master;
  1204. try
  1205. {
  1206. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1207. master->setRealKey(ctx, key, value, expire);
  1208. }
  1209. catch (IException * error)
  1210. {
  1211. master.handleException(error);
  1212. }
  1213. }
  1214. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetBool(ICodeContext * ctx, const char * key, bool value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1215. {
  1216. SyncRSet(ctx, options, key, value, database, expire, password, timeout, cachedConnectionRequested);
  1217. }
  1218. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetData(ICodeContext * ctx, const char * key, size32_t valueSize, const void * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1219. {
  1220. SyncRSet(ctx, options, key, valueSize, value, database, expire, password, timeout, cachedConnectionRequested);
  1221. }
  1222. ECL_REDIS_API void ECL_REDIS_CALL SyncRSetUtf8(ICodeContext * ctx, const char * key, size32_t valueLength, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1223. {
  1224. SyncRSet(ctx, options, key, rtlUtf8Size(valueLength, value), value, database, expire, password, timeout, cachedConnectionRequested);
  1225. }
  1226. //-------------------------------------GET----------------------------------------
  1227. ECL_REDIS_API bool ECL_REDIS_CALL SyncRGetBool(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1228. {
  1229. bool value;
  1230. SyncRGet(ctx, options, key, value, database, password, timeout, cachedConnectionRequested);
  1231. return value;
  1232. }
  1233. ECL_REDIS_API double ECL_REDIS_CALL SyncRGetDouble(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1234. {
  1235. double value;
  1236. SyncRGetNumeric(ctx, options, key, value, database, password, timeout, cachedConnectionRequested);
  1237. return value;
  1238. }
  1239. ECL_REDIS_API signed __int64 ECL_REDIS_CALL SyncRGetInt8(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1240. {
  1241. signed __int64 value;
  1242. SyncRGetNumeric(ctx, options, key, value, database, password, timeout, cachedConnectionRequested);
  1243. return value;
  1244. }
  1245. ECL_REDIS_API unsigned __int64 ECL_REDIS_CALL SyncRGetUint8(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1246. {
  1247. unsigned __int64 value;
  1248. SyncRGetNumeric(ctx, options, key, value, database, password, timeout, cachedConnectionRequested);
  1249. return value;
  1250. }
  1251. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetStr(ICodeContext * ctx, size32_t & returnSize, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1252. {
  1253. size_t _returnSize;
  1254. SyncRGet(ctx, options, key, _returnSize, returnValue, database, password, timeout, cachedConnectionRequested);
  1255. returnSize = static_cast<size32_t>(_returnSize);
  1256. }
  1257. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetUChar(ICodeContext * ctx, size32_t & returnLength, UChar * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1258. {
  1259. size_t returnSize;
  1260. SyncRGet(ctx, options, key, returnSize, returnValue, database, password, timeout, cachedConnectionRequested);
  1261. returnLength = static_cast<size32_t>(returnSize/sizeof(UChar));
  1262. }
  1263. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetUtf8(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1264. {
  1265. size_t returnSize;
  1266. SyncRGet(ctx, options, key, returnSize, returnValue, database, password, timeout, cachedConnectionRequested);
  1267. returnLength = static_cast<size32_t>(rtlUtf8Length(returnSize, returnValue));
  1268. }
  1269. ECL_REDIS_API void ECL_REDIS_CALL SyncRGetData(ICodeContext * ctx, size32_t & returnSize, void * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1270. {
  1271. size_t _returnSize;
  1272. SyncRGet(ctx, options, key, _returnSize, returnValue, database, password, timeout, cachedConnectionRequested);
  1273. returnSize = static_cast<size32_t>(_returnSize);
  1274. }
  1275. //----------------------------------LOCK------------------------------------------
  1276. //-----------------------------------SET-----------------------------------------
  1277. //Set pointer types
  1278. void SyncLockRSet(ICodeContext * ctx, const char * _options, const char * key, size32_t valueSize, const char * value, int database, unsigned expire, const char * password, unsigned _timeout, bool cachedConnectionRequested)
  1279. {
  1280. ConnectionContainer master;
  1281. try
  1282. {
  1283. master.setown(Connection::createConnection(ctx, cachedConnection, _options, DUMMY_IP, DUMMY_PORT, true, database, password, _timeout, cachedConnectionRequested));
  1284. master->lockSet(ctx, key, valueSize, value, expire);
  1285. }
  1286. catch (IException * error)
  1287. {
  1288. master.handleException(error);
  1289. }
  1290. }
  1291. //--INNER--
  1292. void Connection::lockSet(ICodeContext * ctx, const char * key, size32_t valueSize, const char * value, unsigned expire)
  1293. {
  1294. const char * _value = reinterpret_cast<const char *>(value);//Do this even for char * to prevent compiler complaining
  1295. handleLockOnSet(ctx, key, _value, (size_t)valueSize, expire);
  1296. }
  1297. //-------------------------------------------GET-----------------------------------------
  1298. //--OUTER--
  1299. void SyncLockRGet(ICodeContext * ctx, const char * options, const char * key, size_t & returnSize, char * & returnValue, int database, unsigned expire, const char * password, unsigned _timeout, bool cachedConnectionRequested)
  1300. {
  1301. ConnectionContainer master;
  1302. try
  1303. {
  1304. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, _timeout, cachedConnectionRequested));
  1305. master->lockGet(ctx, key, returnSize, returnValue, password, expire);
  1306. }
  1307. catch (IException * error)
  1308. {
  1309. master.handleException(error);
  1310. }
  1311. }
  1312. //--INNER--
  1313. void Connection::lockGet(ICodeContext * ctx, const char * key, size_t & returnSize, char * & returnValue, const char * password, unsigned expire)
  1314. {
  1315. MemoryAttr retVal;
  1316. handleLockOnGet(ctx, key, &retVal, password, expire);
  1317. returnSize = retVal.length();
  1318. returnValue = reinterpret_cast<char*>(retVal.detach());
  1319. }
  1320. //---------------------------------------------------------------------------------------
  1321. bool Connection::lock(ICodeContext * ctx, const char * key, const char * channel, unsigned expire)
  1322. {
  1323. if (expire == 0)
  1324. fail("GetOrLock<type>", "invalid value for 'expire', persistent locks not allowed.", key);
  1325. StringBuffer cmd("SET %b %b NX PX ");
  1326. cmd.append(expire);
  1327. OwnedReply reply = Reply::createReply(redisCommand(cmd.str(), key, strlen(key), channel, strlen(channel)));
  1328. assertOnErrorWithCmdMsg(reply->query(), cmd.str(), key);
  1329. return (reply->query()->type == REDIS_REPLY_STATUS && strcmp(reply->query()->str, "OK") == 0);
  1330. }
  1331. void Connection::unlock(ICodeContext * ctx, const char * key)
  1332. {
  1333. //WATCH key, if altered between WATCH and EXEC abort all commands inbetween
  1334. redisAppendCommand(context, "WATCH %b", key, strlen(key));
  1335. redisAppendCommand(context, "GET %b", key, strlen(key));
  1336. //Read replies
  1337. OwnedReply reply = new Reply();
  1338. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//WATCH reply
  1339. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//GET reply
  1340. //check if locked
  1341. if (strncmp(reply->query()->str, REDIS_LOCK_PREFIX, strlen(REDIS_LOCK_PREFIX)) == 0)
  1342. {
  1343. //MULTI - all commands between MULTI and EXEC are considered an atomic transaction on the server
  1344. redisAppendCommand(context, "MULTI");//MULTI
  1345. redisAppendCommand(context, "DEL %b", key, strlen(key));//DEL
  1346. redisAppendCommand(context, "EXEC");//EXEC
  1347. #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.
  1348. sleep(10);
  1349. #endif
  1350. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//MULTI reply
  1351. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//DEL reply
  1352. readReplyAndAssertWithCmdMsg(reply.get(), "manual unlock", key);//EXEC reply
  1353. }
  1354. //If the above is aborted, let the lock expire.
  1355. }
  1356. void Connection::handleLockOnGet(ICodeContext * ctx, const char * key, MemoryAttr * retVal, const char * password, unsigned expire)
  1357. {
  1358. //NOTE: This routine can only return an empty string under one condition, that which indicates to the caller that the key was successfully locked.
  1359. StringBuffer channel;
  1360. encodeChannel(channel, key, database, true);
  1361. //Query key and set lock if non existent
  1362. if (lock(ctx, key, channel.str(), expire))
  1363. return;
  1364. #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.
  1365. {
  1366. OwnedReply pubReply = Reply::createReply(redisCommand("DEL %b", key, strlen(key)));
  1367. assertOnError(pubReply->query(), "del fail");
  1368. }
  1369. #endif
  1370. //SUB before GET
  1371. //Requires separate connection from GET so that the replies are not mangled. This could be averted but is not worth it.
  1372. int _timeLeft = (int) timeLeft();//createConnection requires a timeout value, so create it here.
  1373. if (_timeLeft == 0 && timeout.getTimeout() != 0)//Disambiguate between zero time left and timeout = 0 => infinity.
  1374. rtlFail(0, "Redis Plugin: ERROR - function timed out internally.");
  1375. ConnectionContainer subscriptionConnection;
  1376. try
  1377. {
  1378. subscriptionConnection.setown(createConnection(ctx, cachedSubscriptionConnection, options.str(), ip.str(), port, false, 0, password, _timeLeft, canCacheConnections(isCachedConnection(), true), true));
  1379. subscriptionConnection->subscribe(ctx, channel.str());
  1380. #if(0)//Test publish before GET.
  1381. {
  1382. OwnedReply pubReply = Reply::createReply(redisCommand("PUBLISH %b %b", channel.str(), (size_t)channel.length(), "foo", (size_t)3));
  1383. assertOnError(pubReply->query(), "pub fail");
  1384. }
  1385. #endif
  1386. //Now GET
  1387. OwnedReply getReply = Reply::createReply((redisReply*)redisCommand("GET %b", key, strlen(key)));
  1388. assertOnErrorWithCmdMsg(getReply->query(), "GetOrLock<type>", key);
  1389. #if(0)//Test publish after GET.
  1390. {
  1391. OwnedReply pubReply = Reply::createReply(redisCommand("PUBLISH %b %b", channel.str(), (size_t)channel.length(), "foo", (size_t)3));
  1392. assertOnError(pubReply->query(), "pub fail");
  1393. }
  1394. #endif
  1395. //Only return an actual value, i.e. neither the lock value nor an empty string. The latter is unlikely since we know that lock()
  1396. //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.
  1397. if (getReply->query()->type != REDIS_REPLY_NIL && getReply->query()->str && strncmp(getReply->query()->str, REDIS_LOCK_PREFIX, strlen(REDIS_LOCK_PREFIX)) != 0)
  1398. {
  1399. retVal->set(getReply->query()->len, getReply->query()->str);
  1400. return;
  1401. }
  1402. else
  1403. {
  1404. //Check that the lock was set by this plugin and thus that we subscribed to the expected channel.
  1405. if (getReply->query()->str && strcmp(getReply->query()->str, channel.str()) !=0 )
  1406. {
  1407. VStringBuffer msg("key locked with a channel ('%s') different to that subscribed to (%s).", getReply->query()->str, channel.str());
  1408. fail("GetOrLock<type>", msg.str(), key);
  1409. //MORE: In theory, it is possible to recover at this stage by subscribing to the channel that the key was actually locked with.
  1410. //However, we may have missed the massage publication already or by then, but could SUB again in case we haven't.
  1411. //More importantly and furthermore, the publication (in SetAndPublish<type>) will only publish to the channel encoded by
  1412. //this plugin, rather than the string retrieved as the lock value (the value of the locked key).
  1413. }
  1414. getReply.clear();
  1415. #if(0)//Added to allow for manual pub testing via redis-cli
  1416. struct timeval to = { 10, 0 };//10secs
  1417. ::redisSetTimeout(subscriptionConnection->context, to);
  1418. #endif
  1419. OwnedReply subReply = new Reply();
  1420. subscriptionConnection->readReply(subReply);
  1421. subscriptionConnection->assertOnErrorWithCmdMsg(subReply->query(), "GetOrLock<type>", key);
  1422. if (subscriptionConnection->isCorrectChannel(subReply->query(), "message"))
  1423. {
  1424. //We are about to return a value, to conform with other Get<type> functions, fail if the key did not exist.
  1425. //Since the value is sent via a published message, there is no direct reply struct so assume that an empty
  1426. //string is equivalent to a non-existent key.
  1427. //More importantly, it is paramount that this routine only return an empty string under one condition, that
  1428. //which indicates to the caller that the key was successfully locked.
  1429. //NOTE: it is possible for an empty message to have been PUBLISHed.
  1430. if (subReply->query()->element[2]->len > 0)
  1431. {
  1432. retVal->set(subReply->query()->element[2]->len, subReply->query()->element[2]->str);//return the published value rather than another (WATCHed) GET.
  1433. return;
  1434. }
  1435. //fail that key does not exist
  1436. redisReply fakeReply;
  1437. fakeReply.type = REDIS_REPLY_NIL;
  1438. assertKey(&fakeReply, key);
  1439. }
  1440. }
  1441. throwUnexpected();
  1442. }
  1443. catch (IException * error)
  1444. {
  1445. subscriptionConnection.handleException(error);
  1446. }
  1447. }
  1448. void Connection::handleLockOnSet(ICodeContext * ctx, const char * key, const char * value, size_t size, unsigned expire)
  1449. {
  1450. //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.
  1451. StringBuffer channel;
  1452. encodeChannel(channel, key, database, true);
  1453. if (size > 29)//c.f. 1st note below.
  1454. {
  1455. OwnedReply replyContainer = new Reply();
  1456. if (expire == 0)
  1457. {
  1458. const char * luaScriptSHA1 = "2a4a976d9bbd806756b2c7fc1e2bc2cb905e68c3"; //NOTE: update this if luaScript is updated!
  1459. replyContainer->setClear(redisCommand("EVALSHA %b %d %b %b %b", luaScriptSHA1, (size_t)40, 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size));
  1460. if (noScript(replyContainer->query()))
  1461. {
  1462. 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!
  1463. replyContainer->setClear(redisCommand("EVAL %b %d %b %b %b", luaScript, strlen(luaScript), 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size));
  1464. }
  1465. }
  1466. else
  1467. {
  1468. const char * luaScriptWithExpireSHA1 = "6f6bc88ccea7c6853ccc395eaa7abd8cb91fb2d8"; //NOTE: update this if luaScriptWithExpire is updated!
  1469. replyContainer->setClear(redisCommand("EVALSHA %b %d %b %b %b %d", luaScriptWithExpireSHA1, (size_t)40, 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size, expire));
  1470. if (noScript(replyContainer->query()))
  1471. {
  1472. 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!
  1473. replyContainer->setClear(redisCommand("EVAL %b %d %b %b %b %d", luaScriptWithExpire, strlen(luaScriptWithExpire), 1, key, strlen(key), channel.str(), (size_t)channel.length(), value, size, expire));
  1474. }
  1475. }
  1476. assertOnErrorWithCmdMsg(replyContainer->query(), "SET", key);
  1477. }
  1478. else
  1479. {
  1480. StringBuffer cmd("SET %b %b");
  1481. RedisPlugin::appendExpire(cmd, expire);
  1482. redisAppendCommand(context, "MULTI");
  1483. redisAppendCommand(context, cmd.str(), key, strlen(key), value, size);//SET
  1484. redisAppendCommand(context, "PUBLISH %b %b", channel.str(), (size_t)channel.length(), value, size);//PUB
  1485. redisAppendCommand(context, "EXEC");
  1486. //Now read and assert replies
  1487. OwnedReply reply = new Reply();
  1488. readReplyAndAssertWithCmdMsg(reply, "SET", key);//MULTI reply
  1489. readReplyAndAssertWithCmdMsg(reply, "SET", key);//SET reply
  1490. readReplyAndAssertWithCmdMsg(reply, "PUB for the key", key);//PUB reply
  1491. readReplyAndAssertWithCmdMsg(reply, "SET", key);//EXEC reply
  1492. }
  1493. //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.
  1494. //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.
  1495. //However, there is a transmission overhead for this method that may still be larger than sending the data twice if it is small enough.
  1496. //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
  1497. //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
  1498. //Therefore, they have same length when: 19 + value = 48 => value = 29.
  1499. //NOTE: Pipelining the above commands may not be the expected behaviour, instead only PUBLISH upon a successful SET. Doing both regardless, does however ensure
  1500. //(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
  1501. //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.
  1502. //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.
  1503. //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
  1504. //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(),
  1505. //otherwise PUB on the value retrieved from GETSET or possibly only if it at least has the prefix "redis_key_lock".
  1506. //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.
  1507. }
  1508. bool Connection::noScript(const redisReply * reply) const
  1509. {
  1510. return (reply && reply->type == REDIS_REPLY_ERROR && strncmp(reply->str, "NOSCRIPT", 8) == 0);
  1511. }
  1512. //--------------------------------------------------------------------------------
  1513. // ECL SERVICE ENTRYPOINTS
  1514. //--------------------------------------------------------------------------------
  1515. //-----------------------------------SET------------------------------------------
  1516. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRSetStr(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, size32_t valueLength, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1517. {
  1518. SyncLockRSet(ctx, options, key, valueLength, value, database, expire, password, timeout, cachedConnectionRequested);
  1519. returnLength = valueLength;
  1520. returnValue = (char*)allocateAndCopy(value, valueLength);
  1521. }
  1522. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRSetUChar(ICodeContext * ctx, size32_t & returnLength, UChar * & returnValue, const char * key, size32_t valueLength, const UChar * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1523. {
  1524. unsigned valueSize = (valueLength)*sizeof(UChar);
  1525. SyncLockRSet(ctx, options, key, valueSize, (char*)value, database, expire, password, timeout, cachedConnectionRequested);
  1526. returnLength= valueLength;
  1527. returnValue = (UChar*)allocateAndCopy(value, valueSize);
  1528. }
  1529. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRSetUtf8(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, size32_t valueLength, const char * value, const char * options, int database, unsigned expire, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1530. {
  1531. unsigned valueSize = rtlUtf8Size(valueLength, value);
  1532. SyncLockRSet(ctx, options, key, valueSize, value, database, expire, password, timeout, cachedConnectionRequested);
  1533. returnLength = valueLength;
  1534. returnValue = (char*)allocateAndCopy(value, valueSize);
  1535. }
  1536. //-------------------------------------GET----------------------------------------
  1537. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRGetStr(ICodeContext * ctx, size32_t & returnSize, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, unsigned expire, bool cachedConnectionRequested)
  1538. {
  1539. size_t _returnSize;
  1540. SyncLockRGet(ctx, options, key, _returnSize, returnValue, database, expire, password, timeout, cachedConnectionRequested);
  1541. returnSize = static_cast<size32_t>(_returnSize);
  1542. }
  1543. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRGetUChar(ICodeContext * ctx, size32_t & returnLength, UChar * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, unsigned expire, bool cachedConnectionRequested)
  1544. {
  1545. size_t returnSize;
  1546. char * _returnValue;
  1547. SyncLockRGet(ctx, options, key, returnSize, _returnValue, database, expire, password, timeout, cachedConnectionRequested);
  1548. returnValue = (UChar*)_returnValue;
  1549. returnLength = static_cast<size32_t>(returnSize/sizeof(UChar));
  1550. }
  1551. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRGetUtf8(ICodeContext * ctx, size32_t & returnLength, char * & returnValue, const char * key, const char * options, int database, const char * password, unsigned timeout, unsigned expire, bool cachedConnectionRequested)
  1552. {
  1553. size_t returnSize;
  1554. SyncLockRGet(ctx, options, key, returnSize, returnValue, database, expire, password, timeout, cachedConnectionRequested);
  1555. returnLength = static_cast<size32_t>(rtlUtf8Length(returnSize, returnValue));
  1556. }
  1557. ECL_REDIS_API void ECL_REDIS_CALL SyncLockRUnlock(ICodeContext * ctx, const char * key, const char * options, int database, const char * password, unsigned timeout, bool cachedConnectionRequested)
  1558. {
  1559. ConnectionContainer master;
  1560. try
  1561. {
  1562. master.setown(Connection::createConnection(ctx, cachedConnection, options, DUMMY_IP, DUMMY_PORT, true, database, password, timeout, cachedConnectionRequested));
  1563. master->unlock(ctx, key);
  1564. }
  1565. catch (IException * error)
  1566. {
  1567. master.handleException(error);
  1568. }
  1569. }
  1570. }//close namespace