2 * Copyright 2001-2009 Internet2
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
18 * memcache-store.cpp
\r
20 * Storage Service using memcache (pre memcache tags)
\r
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
\r
24 # include "config_win32.h"
\r
26 # include "config.h"
\r
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
\r
31 # define _CRT_SECURE_NO_DEPRECATE 1
\r
32 # define MCEXT_EXPORTS __declspec(dllexport)
\r
34 # define MCEXT_EXPORTS
\r
37 #include <xmltooling/base.h>
\r
40 #include <iostream>
\r
41 #include <libmemcached/memcached.h>
\r
42 #include <xercesc/util/XMLUniDefs.hpp>
\r
44 #include <xmltooling/logging.h>
\r
45 #include <xmltooling/unicode.h>
\r
46 #include <xmltooling/XMLToolingConfig.h>
\r
47 #include <xmltooling/util/NDC.h>
\r
48 #include <xmltooling/util/StorageService.h>
\r
49 #include <xmltooling/util/Threads.h>
\r
50 #include <xmltooling/util/XMLHelper.h>
\r
52 using namespace xmltooling::logging;
\r
53 using namespace xmltooling;
\r
54 using namespace xercesc;
\r
55 using namespace std;
\r
57 namespace xmltooling {
\r
58 static const XMLCh Hosts[] = UNICODE_LITERAL_5(H,o,s,t,s);
\r
59 static const XMLCh prefix[] = UNICODE_LITERAL_6(p,r,e,f,i,x);
\r
60 static const XMLCh buildMap[] = UNICODE_LITERAL_8(b,u,i,l,d,M,a,p);
\r
67 mc_record(string _v, time_t _e) :
\r
68 value(_v), expiration(_e)
\r
72 class MemcacheBase {
\r
74 MemcacheBase(const DOMElement* e);
\r
77 bool addMemcache(const char *key,
\r
81 bool use_prefix = true);
\r
82 bool setMemcache(const char *key,
\r
86 bool use_prefix = true);
\r
87 bool replaceMemcache(const char *key,
\r
91 bool use_prefix = true);
\r
92 bool getMemcache(const char *key,
\r
95 bool use_prefix = true);
\r
96 bool deleteMemcache(const char *key,
\r
98 bool use_prefix = true);
\r
100 void serialize(mc_record &source, string &dest);
\r
101 void serialize(list<string> &source, string &dest);
\r
102 void deserialize(string &source, mc_record &dest);
\r
103 void deserialize(string &source, list<string> &dest);
\r
105 bool addSessionToUser(string &key, string &user);
\r
106 bool addLock(string what, bool use_prefix = true);
\r
107 void deleteLock(string what, bool use_prefix = true);
\r
110 const DOMElement* m_root; // can only use this during initialization
\r
112 memcached_st *memc;
\r
113 string m_memcacheHosts;
\r
118 class MemcacheStorageService : public StorageService, public MemcacheBase {
\r
121 MemcacheStorageService(const DOMElement* e);
\r
122 ~MemcacheStorageService();
\r
124 bool createString(const char* context, const char* key, const char* value, time_t expiration);
\r
125 int readString(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0);
\r
126 int updateString(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0);
\r
127 bool deleteString(const char* context, const char* key);
\r
129 bool createText(const char* context, const char* key, const char* value, time_t expiration) {
\r
130 return createString(context, key, value, expiration);
\r
132 int readText(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0) {
\r
133 return readString(context, key, pvalue, pexpiration, version);
\r
135 int updateText(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0) {
\r
136 return updateString(context, key, value, expiration, version);
\r
138 bool deleteText(const char* context, const char* key) {
\r
139 return deleteString(context, key);
\r
142 void reap(const char* context) {}
\r
144 void updateContext(const char* context, time_t expiration);
\r
145 void deleteContext(const char* context);
\r
155 StorageService* MemcacheStorageServiceFactory(const DOMElement* const & e) {
\r
156 return new MemcacheStorageService(e);
\r
161 bool MemcacheBase::addLock(string what, bool use_prefix) {
\r
162 string lock_name = what + ":LOCK";
\r
163 string set_val = "1";
\r
164 unsigned tries = 5;
\r
165 while (!addMemcache(lock_name.c_str(), set_val, 5, 0, use_prefix)) {
\r
166 if (tries-- == 0) {
\r
167 log.debug("Unable to get lock %s... FAILED.", lock_name.c_str());
\r
170 log.debug("Unable to get lock %s... Retrying.", lock_name.c_str());
\r
176 struct timeval tv = { 0, 100000 };
\r
177 select(0, 0, 0, 0, &tv);
\r
183 void MemcacheBase::deleteLock(string what, bool use_prefix) {
\r
185 string lock_name = what + ":LOCK";
\r
186 deleteMemcache(lock_name.c_str(), 0, use_prefix);
\r
191 void MemcacheBase::deserialize(string &source, mc_record &dest) {
\r
192 istringstream is(source, stringstream::in | stringstream::out);
\r
193 is >> dest.expiration;
\r
194 is.ignore(1); // ignore delimiter
\r
195 dest.value = is.str().c_str() + is.tellg();
\r
198 void MemcacheBase::deserialize(string &source, list<string> &dest) {
\r
199 istringstream is(source, stringstream::in | stringstream::out);
\r
200 while (!is.eof()) {
\r
207 void MemcacheBase::serialize(mc_record &source, string &dest) {
\r
208 ostringstream os(stringstream::in | stringstream::out);
\r
209 os << source.expiration;
\r
210 os << "-"; // delimiter
\r
211 os << source.value;
\r
215 void MemcacheBase::serialize(list<string> &source, string &dest) {
\r
216 ostringstream os(stringstream::in | stringstream::out);
\r
217 for(list<string>::iterator iter = source.begin(); iter != source.end(); iter++) {
\r
218 if (iter != source.begin()) {
\r
226 bool MemcacheBase::addSessionToUser(string &key, string &user) {
\r
228 if (! addLock(user, false)) {
\r
234 string sessid = m_prefix + key; // add specific prefix to session
\r
235 string delimiter = ";";
\r
236 string user_key = "UDATA:";
\r
240 bool result = getMemcache(user_key.c_str(), user_val, &flags, false);
\r
243 bool already_there = false;
\r
244 // skip delimiters at beginning.
\r
245 string::size_type lastPos = user_val.find_first_not_of(delimiter, 0);
\r
247 // find first "non-delimiter".
\r
248 string::size_type pos = user_val.find_first_of(delimiter, lastPos);
\r
250 while (string::npos != pos || string::npos != lastPos) {
\r
251 // found a token, add it to the vector.
\r
252 string session = user_val.substr(lastPos, pos - lastPos);
\r
253 if (strcmp(session.c_str(), sessid.c_str()) == 0) {
\r
254 already_there = true;
\r
258 // skip delimiters. Note the "not_of"
\r
259 lastPos = user_val.find_first_not_of(delimiter, pos);
\r
261 // find next "non-delimiter"
\r
262 pos = user_val.find_first_of(delimiter, lastPos);
\r
265 if (!already_there) {
\r
266 user_val += delimiter + sessid;
\r
267 replaceMemcache(user_key.c_str(), user_val, 0, 0, false);
\r
270 addMemcache(user_key.c_str(), sessid, 0, 0, false);
\r
273 deleteLock(user, false);
\r
278 bool MemcacheBase::deleteMemcache(const char *key,
\r
281 memcached_return rv;
\r
286 final_key = m_prefix + key;
\r
292 rv = memcached_delete(memc, (char *)final_key.c_str(), final_key.length(), timeout);
\r
295 if (rv == MEMCACHED_SUCCESS) {
\r
297 } else if (rv == MEMCACHED_NOTFOUND) {
\r
298 // Key wasn't there... No biggie.
\r
300 } else if (rv == MEMCACHED_ERRNO) {
\r
302 log.error(string("Memcache::deleteMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
305 log.error(string("Memcache::deleteMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
306 // shouldn't be here
\r
313 bool MemcacheBase::getMemcache(const char *key,
\r
317 memcached_return rv;
\r
324 final_key = m_prefix + key;
\r
330 result = memcached_get(memc, (char *)final_key.c_str(), final_key.length(), &len, flags, &rv);
\r
333 if (rv == MEMCACHED_SUCCESS) {
\r
337 } else if (rv == MEMCACHED_NOTFOUND) {
\r
338 log.debug("Key %s not found in memcache...", key);
\r
340 } else if (rv == MEMCACHED_ERRNO) {
\r
342 log.error(string("Memcache::getMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
345 log.error(string("Memcache::getMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
352 bool MemcacheBase::addMemcache(const char *key,
\r
358 memcached_return rv;
\r
363 final_key = m_prefix + key;
\r
369 rv = memcached_add(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
372 if (rv == MEMCACHED_SUCCESS) {
\r
374 } else if (rv == MEMCACHED_NOTSTORED) {
\r
377 } else if (rv == MEMCACHED_ERRNO) {
\r
379 log.error(string("Memcache::addMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
382 // shouldn't be here
\r
383 log.error(string("Memcache::addMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
390 bool MemcacheBase::setMemcache(const char *key,
\r
396 memcached_return rv;
\r
401 final_key = m_prefix + key;
\r
407 rv = memcached_set(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
410 if (rv == MEMCACHED_SUCCESS) {
\r
412 } else if (rv == MEMCACHED_ERRNO) {
\r
414 log.error(string("Memcache::setMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
417 // shouldn't be here
\r
418 log.error(string("Memcache::setMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
425 bool MemcacheBase::replaceMemcache(const char *key,
\r
431 memcached_return rv;
\r
436 final_key = m_prefix + key;
\r
442 rv = memcached_replace(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
445 if (rv == MEMCACHED_SUCCESS) {
\r
447 } else if (rv == MEMCACHED_NOTSTORED) {
\r
450 } else if (rv == MEMCACHED_ERRNO) {
\r
452 log.error(string("Memcache::replaceMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
455 // shouldn't be here
\r
456 log.error(string("Memcache::replaceMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
463 MemcacheBase::MemcacheBase(const DOMElement* e) : m_root(e), log(Category::getInstance("XMLTooling.MemcacheBase")), m_memcacheHosts(""), m_prefix("") {
\r
465 auto_ptr_char p(e ? e->getAttributeNS(NULL,prefix) : NULL);
\r
466 if (p.get() && *p.get()) {
\r
467 log.debug("INIT: GOT key prefix: %s", p.get());
\r
468 m_prefix = p.get();
\r
471 // Grab hosts from the configuration.
\r
472 e = e ? XMLHelper::getFirstChildElement(e,Hosts) : NULL;
\r
473 if (!e || !e->hasChildNodes()) {
\r
474 throw XMLToolingException("Memcache StorageService requires Hosts element in configuration.");
\r
476 auto_ptr_char h(e->getFirstChild()->getNodeValue());
\r
477 log.debug("INIT: GOT Hosts: %s", h.get());
\r
478 m_memcacheHosts = h.get();
\r
480 m_lock = Mutex::create();
\r
481 log.debug("Lock created");
\r
483 memc = memcached_create(NULL);
\r
484 if (memc == NULL) {
\r
485 throw XMLToolingException("MemcacheBase::Memcache(): memcached_create() failed");
\r
488 log.debug("Memcache created");
\r
490 unsigned int hash = MEMCACHED_HASH_CRC;
\r
491 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_HASH, hash);
\r
492 log.debug("CRC hash set");
\r
494 int32_t timeout = 1000000;
\r
495 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SND_TIMEOUT, timeout);
\r
496 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, timeout);
\r
498 int32_t poll_timeout = 1000;
\r
499 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_POLL_TIMEOUT, poll_timeout);
\r
501 int32_t fail_limit = 5;
\r
502 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, fail_limit);
\r
504 int32_t retry_timeout = 30;
\r
505 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, retry_timeout);
\r
507 memcached_server_st *servers;
\r
508 servers = memcached_servers_parse((char *)m_memcacheHosts.c_str());
\r
509 log.debug("Got %u hosts.", memcached_server_list_count(servers));
\r
510 if (memcached_server_push(memc, servers) != MEMCACHED_SUCCESS) {
\r
511 throw IOException("MemcacheBase::Memcache(): memcached_server_push() failed");
\r
513 memcached_server_list_free(servers);
\r
515 log.debug("Memcache object initialized");
\r
518 MemcacheBase::~MemcacheBase() {
\r
519 memcached_free(memc);
\r
521 log.debug("Base object destroyed");
\r
524 MemcacheStorageService::MemcacheStorageService(const DOMElement* e)
\r
525 : MemcacheBase(e), m_log(Category::getInstance("XMLTooling.MemcacheStorageService")), m_buildMap(false) {
\r
527 const XMLCh* tag=e ? e->getAttributeNS(NULL,buildMap) : NULL;
\r
528 if (tag && *tag && XMLString::parseInt(tag) != 0) {
\r
530 m_log.debug("Cache built with buildMap ON");
\r
535 MemcacheStorageService::~MemcacheStorageService() {
\r
540 bool MemcacheStorageService::createString(const char* context, const char* key, const char* value, time_t expiration) {
\r
542 log.debug("createString ctx: %s - key: %s", context, key);
\r
544 string final_key = string(context) + ":" + string(key);
\r
546 mc_record rec(value, expiration);
\r
547 string final_value;
\r
548 serialize(rec, final_value);
\r
550 bool result = addMemcache(final_key.c_str(), final_value, expiration, 1); // the flag will be the version
\r
552 if (result && m_buildMap) {
\r
553 log.debug("Got result, updating map");
\r
555 string map_name = context;
\r
556 // we need to update the context map
\r
557 if (! addLock(map_name)) {
\r
558 log.error("Unable to get lock for context %s!", context);
\r
559 deleteMemcache(final_key.c_str(), 0);
\r
565 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
567 list<string> contents;
\r
569 log.debug("Match found. Parsing...");
\r
571 deserialize(ser_arr, contents);
\r
573 log.debug("Iterating retrieved session map...");
\r
574 list<string>::iterator iter;
\r
575 for(iter = contents.begin();
\r
576 iter != contents.end();
\r
578 log.debug("value = " + *iter);
\r
582 log.debug("New context: %s", map_name.c_str());
\r
586 contents.push_back(key);
\r
587 serialize(contents, ser_arr);
\r
588 setMemcache(map_name.c_str(), ser_arr, expiration, 0);
\r
590 deleteLock(map_name);
\r
597 int MemcacheStorageService::readString(const char* context, const char* key, string* pvalue, time_t* pexpiration, int version) {
\r
599 log.debug("readString ctx: %s - key: %s", context, key);
\r
601 string final_key = string(context) + ":" + string(key);
\r
602 uint32_t rec_version;
\r
606 log.debug("Checking context");
\r
608 string map_name = context;
\r
611 bool ctx_found = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
618 bool found = getMemcache(final_key.c_str(), value, &rec_version);
\r
623 if (version && rec_version <= (uint32_t)version) {
\r
627 if (pexpiration || pvalue) {
\r
629 deserialize(value, rec);
\r
632 *pexpiration = rec.expiration;
\r
636 *pvalue = rec.value;
\r
640 return rec_version;
\r
644 int MemcacheStorageService::updateString(const char* context, const char* key, const char* value, time_t expiration, int version) {
\r
646 log.debug("updateString ctx: %s - key: %s", context, key);
\r
648 time_t final_exp = expiration;
\r
649 time_t *want_expiration = NULL;
\r
651 want_expiration = &final_exp;
\r
654 int read_res = readString(context, key, NULL, want_expiration, version);
\r
661 if (version && version != read_res) {
\r
662 // version incorrect
\r
666 // Proceding with update
\r
667 string final_key = string(context) + ":" + string(key);
\r
668 mc_record rec(value, final_exp);
\r
669 string final_value;
\r
670 serialize(rec, final_value);
\r
672 replaceMemcache(final_key.c_str(), final_value, final_exp, ++version);
\r
677 bool MemcacheStorageService::deleteString(const char* context, const char* key) {
\r
679 log.debug("deleteString ctx: %s - key: %s", context, key);
\r
681 string final_key = string(context) + ":" + string(key);
\r
683 // Not updating context map, if there is one. There is no need.
\r
685 return deleteMemcache(final_key.c_str(), 0);
\r
689 void MemcacheStorageService::updateContext(const char* context, time_t expiration) {
\r
691 log.debug("updateContext ctx: %s", context);
\r
694 log.error("updateContext invoked on a Storage with no context map built!");
\r
698 string map_name = context;
\r
701 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
703 list<string> contents;
\r
705 log.debug("Match found. Parsing...");
\r
707 deserialize(ser_arr, contents);
\r
709 log.debug("Iterating retrieved session map...");
\r
710 list<string>::iterator iter;
\r
711 for(iter = contents.begin();
\r
712 iter != contents.end();
\r
715 // Update expiration times
\r
717 int read_res = readString(context, iter->c_str(), &value, NULL, 0);
\r
724 updateString(context, iter->c_str(), value.c_str(), expiration, read_res);
\r
726 replaceMemcache(map_name.c_str(), ser_arr, expiration, flags);
\r
731 void MemcacheStorageService::deleteContext(const char* context) {
\r
733 log.debug("deleteContext ctx: %s", context);
\r
736 log.error("deleteContext invoked on a Storage with no context map built!");
\r
740 string map_name = context;
\r
743 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
745 list<string> contents;
\r
747 log.debug("Match found. Parsing...");
\r
749 deserialize(ser_arr, contents);
\r
751 log.debug("Iterating retrieved session map...");
\r
752 list<string>::iterator iter;
\r
753 for(iter = contents.begin();
\r
754 iter != contents.end();
\r
756 string final_key = map_name + *iter;
\r
757 deleteMemcache(final_key.c_str(), 0);
\r
760 deleteMemcache(map_name.c_str(), 0);
\r
765 extern "C" int MCEXT_EXPORTS xmltooling_extension_init(void*) {
\r
766 // Register this SS type
\r
767 XMLToolingConfig::getConfig().StorageServiceManager.registerFactory("MEMCACHE", MemcacheStorageServiceFactory);
\r
771 extern "C" void MCEXT_EXPORTS xmltooling_extension_term() {
\r
772 XMLToolingConfig::getConfig().StorageServiceManager.deregisterFactory("MEMCACHE");
\r