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/XMLToolingConfig.h>
\r
46 #include <xmltooling/util/NDC.h>
\r
47 #include <xmltooling/util/StorageService.h>
\r
48 #include <xmltooling/util/Threads.h>
\r
49 #include <xmltooling/util/XMLHelper.h>
\r
51 using namespace xmltooling::logging;
\r
52 using namespace xmltooling;
\r
53 using namespace xercesc;
\r
54 using namespace std;
\r
56 namespace xmltooling {
\r
57 static const XMLCh Hosts[] = UNICODE_LITERAL_5(H,o,s,t,s);
\r
58 static const XMLCh prefix[] = UNICODE_LITERAL_6(p,r,e,f,i,x);
\r
59 static const XMLCh buildMap[] = UNICODE_LITERAL_8(b,u,i,l,d,M,a,p);
\r
66 mc_record(string _v, time_t _e) :
\r
67 value(_v), expiration(_e)
\r
71 class MemcacheBase {
\r
73 MemcacheBase(const DOMElement* e);
\r
76 bool addMemcache(const char *key,
\r
80 bool use_prefix = true);
\r
81 bool setMemcache(const char *key,
\r
85 bool use_prefix = true);
\r
86 bool replaceMemcache(const char *key,
\r
90 bool use_prefix = true);
\r
91 bool getMemcache(const char *key,
\r
94 bool use_prefix = true);
\r
95 bool deleteMemcache(const char *key,
\r
97 bool use_prefix = true);
\r
99 void serialize(mc_record &source, string &dest);
\r
100 void serialize(list<string> &source, string &dest);
\r
101 void deserialize(string &source, mc_record &dest);
\r
102 void deserialize(string &source, list<string> &dest);
\r
104 bool addSessionToUser(string &key, string &user);
\r
105 bool addLock(string what, bool use_prefix = true);
\r
106 void deleteLock(string what, bool use_prefix = true);
\r
109 const DOMElement* m_root; // can only use this during initialization
\r
111 memcached_st *memc;
\r
112 string m_memcacheHosts;
\r
117 class MemcacheStorageService : public StorageService, public MemcacheBase {
\r
120 MemcacheStorageService(const DOMElement* e);
\r
121 ~MemcacheStorageService();
\r
123 bool createString(const char* context, const char* key, const char* value, time_t expiration);
\r
124 int readString(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0);
\r
125 int updateString(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0);
\r
126 bool deleteString(const char* context, const char* key);
\r
128 bool createText(const char* context, const char* key, const char* value, time_t expiration) {
\r
129 return createString(context, key, value, expiration);
\r
131 int readText(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0) {
\r
132 return readString(context, key, pvalue, pexpiration, version);
\r
134 int updateText(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0) {
\r
135 return updateString(context, key, value, expiration, version);
\r
137 bool deleteText(const char* context, const char* key) {
\r
138 return deleteString(context, key);
\r
141 void reap(const char* context) {}
\r
143 void updateContext(const char* context, time_t expiration);
\r
144 void deleteContext(const char* context);
\r
154 StorageService* MemcacheStorageServiceFactory(const DOMElement* const & e) {
\r
155 return new MemcacheStorageService(e);
\r
160 bool MemcacheBase::addLock(string what, bool use_prefix) {
\r
161 string lock_name = what + ":LOCK";
\r
162 string set_val = "1";
\r
163 unsigned tries = 5;
\r
164 while (!addMemcache(lock_name.c_str(), set_val, 5, 0, use_prefix)) {
\r
165 if (tries-- == 0) {
\r
166 log.debug("Unable to get lock %s... FAILED.", lock_name.c_str());
\r
169 log.debug("Unable to get lock %s... Retrying.", lock_name.c_str());
\r
175 struct timeval tv = { 0, 100000 };
\r
176 select(0, 0, 0, 0, &tv);
\r
182 void MemcacheBase::deleteLock(string what, bool use_prefix) {
\r
184 string lock_name = what + ":LOCK";
\r
185 deleteMemcache(lock_name.c_str(), 0, use_prefix);
\r
190 void MemcacheBase::deserialize(string &source, mc_record &dest) {
\r
191 istringstream is(source, stringstream::in | stringstream::out);
\r
192 is >> dest.expiration;
\r
193 is.ignore(1); // ignore delimiter
\r
194 dest.value = is.str().c_str() + is.tellg();
\r
197 void MemcacheBase::deserialize(string &source, list<string> &dest) {
\r
198 istringstream is(source, stringstream::in | stringstream::out);
\r
199 while (!is.eof()) {
\r
206 void MemcacheBase::serialize(mc_record &source, string &dest) {
\r
207 ostringstream os(stringstream::in | stringstream::out);
\r
208 os << source.expiration;
\r
209 os << "-"; // delimiter
\r
210 os << source.value;
\r
214 void MemcacheBase::serialize(list<string> &source, string &dest) {
\r
215 ostringstream os(stringstream::in | stringstream::out);
\r
216 for(list<string>::iterator iter = source.begin(); iter != source.end(); iter++) {
\r
217 if (iter != source.begin()) {
\r
225 bool MemcacheBase::addSessionToUser(string &key, string &user) {
\r
227 if (! addLock(user, false)) {
\r
233 string sessid = m_prefix + key; // add specific prefix to session
\r
234 string delimiter = ";";
\r
235 string user_key = "UDATA:";
\r
239 bool result = getMemcache(user_key.c_str(), user_val, &flags, false);
\r
242 bool already_there = false;
\r
243 // skip delimiters at beginning.
\r
244 string::size_type lastPos = user_val.find_first_not_of(delimiter, 0);
\r
246 // find first "non-delimiter".
\r
247 string::size_type pos = user_val.find_first_of(delimiter, lastPos);
\r
249 while (string::npos != pos || string::npos != lastPos) {
\r
250 // found a token, add it to the vector.
\r
251 string session = user_val.substr(lastPos, pos - lastPos);
\r
252 if (strcmp(session.c_str(), sessid.c_str()) == 0) {
\r
253 already_there = true;
\r
257 // skip delimiters. Note the "not_of"
\r
258 lastPos = user_val.find_first_not_of(delimiter, pos);
\r
260 // find next "non-delimiter"
\r
261 pos = user_val.find_first_of(delimiter, lastPos);
\r
264 if (!already_there) {
\r
265 user_val += delimiter + sessid;
\r
266 replaceMemcache(user_key.c_str(), user_val, 0, 0, false);
\r
269 addMemcache(user_key.c_str(), sessid, 0, 0, false);
\r
272 deleteLock(user, false);
\r
277 bool MemcacheBase::deleteMemcache(const char *key,
\r
280 memcached_return rv;
\r
285 final_key = m_prefix + key;
\r
291 rv = memcached_delete(memc, (char *)final_key.c_str(), final_key.length(), timeout);
\r
294 if (rv == MEMCACHED_SUCCESS) {
\r
296 } else if (rv == MEMCACHED_NOTFOUND) {
\r
297 // Key wasn't there... No biggie.
\r
299 } else if (rv == MEMCACHED_ERRNO) {
\r
301 log.error(string("Memcache::deleteMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
304 log.error(string("Memcache::deleteMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
305 // shouldn't be here
\r
312 bool MemcacheBase::getMemcache(const char *key,
\r
316 memcached_return rv;
\r
323 final_key = m_prefix + key;
\r
329 result = memcached_get(memc, (char *)final_key.c_str(), final_key.length(), &len, flags, &rv);
\r
332 if (rv == MEMCACHED_SUCCESS) {
\r
336 } else if (rv == MEMCACHED_NOTFOUND) {
\r
337 log.debug("Key %s not found in memcache...", key);
\r
339 } else if (rv == MEMCACHED_ERRNO) {
\r
341 log.error(string("Memcache::getMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
344 log.error(string("Memcache::getMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
351 bool MemcacheBase::addMemcache(const char *key,
\r
357 memcached_return rv;
\r
362 final_key = m_prefix + key;
\r
368 rv = memcached_add(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
371 if (rv == MEMCACHED_SUCCESS) {
\r
373 } else if (rv == MEMCACHED_NOTSTORED) {
\r
376 } else if (rv == MEMCACHED_ERRNO) {
\r
378 log.error(string("Memcache::addMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
381 // shouldn't be here
\r
382 log.error(string("Memcache::addMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
389 bool MemcacheBase::setMemcache(const char *key,
\r
395 memcached_return rv;
\r
400 final_key = m_prefix + key;
\r
406 rv = memcached_set(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
409 if (rv == MEMCACHED_SUCCESS) {
\r
411 } else if (rv == MEMCACHED_ERRNO) {
\r
413 log.error(string("Memcache::setMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
416 // shouldn't be here
\r
417 log.error(string("Memcache::setMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
424 bool MemcacheBase::replaceMemcache(const char *key,
\r
430 memcached_return rv;
\r
435 final_key = m_prefix + key;
\r
441 rv = memcached_replace(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
444 if (rv == MEMCACHED_SUCCESS) {
\r
446 } else if (rv == MEMCACHED_NOTSTORED) {
\r
449 } else if (rv == MEMCACHED_ERRNO) {
\r
451 log.error(string("Memcache::replaceMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
454 // shouldn't be here
\r
455 log.error(string("Memcache::replaceMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
462 MemcacheBase::MemcacheBase(const DOMElement* e) : m_root(e), log(Category::getInstance("XMLTooling.MemcacheBase")), m_memcacheHosts(""), m_prefix("") {
\r
464 auto_ptr_char p(e ? e->getAttributeNS(NULL,prefix) : NULL);
\r
465 if (p.get() && *p.get()) {
\r
466 log.debug("INIT: GOT key prefix: %s", p.get());
\r
467 m_prefix = p.get();
\r
470 // Grab hosts from the configuration.
\r
471 e = e ? XMLHelper::getFirstChildElement(e,Hosts) : NULL;
\r
472 if (!e || !e->hasChildNodes()) {
\r
473 throw XMLToolingException("Memcache StorageService requires Hosts element in configuration.");
\r
475 auto_ptr_char h(e->getFirstChild()->getNodeValue());
\r
476 log.debug("INIT: GOT Hosts: %s", h.get());
\r
477 m_memcacheHosts = h.get();
\r
479 m_lock = Mutex::create();
\r
480 log.debug("Lock created");
\r
482 memc = memcached_create(NULL);
\r
483 if (memc == NULL) {
\r
484 throw XMLToolingException("MemcacheBase::Memcache(): memcached_create() failed");
\r
487 log.debug("Memcache created");
\r
489 unsigned int hash = MEMCACHED_HASH_CRC;
\r
490 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_HASH, hash);
\r
491 log.debug("CRC hash set");
\r
493 int32_t timeout = 1000000;
\r
494 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SND_TIMEOUT, timeout);
\r
495 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, timeout);
\r
497 int32_t poll_timeout = 1000;
\r
498 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_POLL_TIMEOUT, poll_timeout);
\r
500 int32_t fail_limit = 5;
\r
501 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, fail_limit);
\r
503 int32_t retry_timeout = 30;
\r
504 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, retry_timeout);
\r
506 memcached_server_st *servers;
\r
507 servers = memcached_servers_parse((char *)m_memcacheHosts.c_str());
\r
508 log.debug("Got %u hosts.", memcached_server_list_count(servers));
\r
509 if (memcached_server_push(memc, servers) != MEMCACHED_SUCCESS) {
\r
510 throw IOException("MemcacheBase::Memcache(): memcached_server_push() failed");
\r
512 memcached_server_list_free(servers);
\r
514 log.debug("Memcache object initialized");
\r
517 MemcacheBase::~MemcacheBase() {
\r
518 memcached_free(memc);
\r
520 log.debug("Base object destroyed");
\r
523 MemcacheStorageService::MemcacheStorageService(const DOMElement* e)
\r
524 : MemcacheBase(e), m_log(Category::getInstance("XMLTooling.MemcacheStorageService")), m_buildMap(false) {
\r
526 const XMLCh* tag=e ? e->getAttributeNS(NULL,buildMap) : NULL;
\r
527 if (tag && *tag && XMLString::parseInt(tag) != 0) {
\r
529 m_log.debug("Cache built with buildMap ON");
\r
534 MemcacheStorageService::~MemcacheStorageService() {
\r
539 bool MemcacheStorageService::createString(const char* context, const char* key, const char* value, time_t expiration) {
\r
541 log.debug("createString ctx: %s - key: %s", context, key);
\r
543 string final_key = string(context) + ":" + string(key);
\r
545 mc_record rec(value, expiration);
\r
546 string final_value;
\r
547 serialize(rec, final_value);
\r
549 bool result = addMemcache(final_key.c_str(), final_value, expiration, 1); // the flag will be the version
\r
551 if (result && m_buildMap) {
\r
552 log.debug("Got result, updating map");
\r
554 string map_name = context;
\r
555 // we need to update the context map
\r
556 if (! addLock(map_name)) {
\r
557 log.error("Unable to get lock for context %s!", context);
\r
558 deleteMemcache(final_key.c_str(), 0);
\r
564 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
566 list<string> contents;
\r
568 log.debug("Match found. Parsing...");
\r
570 deserialize(ser_arr, contents);
\r
572 log.debug("Iterating retrieved session map...");
\r
573 list<string>::iterator iter;
\r
574 for(iter = contents.begin();
\r
575 iter != contents.end();
\r
577 log.debug("value = " + *iter);
\r
581 log.debug("New context: %s", map_name.c_str());
\r
585 contents.push_back(key);
\r
586 serialize(contents, ser_arr);
\r
587 setMemcache(map_name.c_str(), ser_arr, expiration, 0);
\r
589 deleteLock(map_name);
\r
596 int MemcacheStorageService::readString(const char* context, const char* key, string* pvalue, time_t* pexpiration, int version) {
\r
598 log.debug("readString ctx: %s - key: %s", context, key);
\r
600 string final_key = string(context) + ":" + string(key);
\r
601 uint32_t rec_version;
\r
605 log.debug("Checking context");
\r
607 string map_name = context;
\r
610 bool ctx_found = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
617 bool found = getMemcache(final_key.c_str(), value, &rec_version);
\r
622 if (version && rec_version <= (uint32_t)version) {
\r
626 if (pexpiration || pvalue) {
\r
628 deserialize(value, rec);
\r
631 *pexpiration = rec.expiration;
\r
635 *pvalue = rec.value;
\r
639 return rec_version;
\r
643 int MemcacheStorageService::updateString(const char* context, const char* key, const char* value, time_t expiration, int version) {
\r
645 log.debug("updateString ctx: %s - key: %s", context, key);
\r
647 time_t final_exp = expiration;
\r
648 time_t *want_expiration = NULL;
\r
650 want_expiration = &final_exp;
\r
653 int read_res = readString(context, key, NULL, want_expiration, version);
\r
660 if (version && version != read_res) {
\r
661 // version incorrect
\r
665 // Proceding with update
\r
666 string final_key = string(context) + ":" + string(key);
\r
667 mc_record rec(value, final_exp);
\r
668 string final_value;
\r
669 serialize(rec, final_value);
\r
671 replaceMemcache(final_key.c_str(), final_value, final_exp, ++version);
\r
676 bool MemcacheStorageService::deleteString(const char* context, const char* key) {
\r
678 log.debug("deleteString ctx: %s - key: %s", context, key);
\r
680 string final_key = string(context) + ":" + string(key);
\r
682 // Not updating context map, if there is one. There is no need.
\r
684 return deleteMemcache(final_key.c_str(), 0);
\r
688 void MemcacheStorageService::updateContext(const char* context, time_t expiration) {
\r
690 log.debug("updateContext ctx: %s", context);
\r
693 log.error("updateContext invoked on a Storage with no context map built!");
\r
697 string map_name = context;
\r
700 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
702 list<string> contents;
\r
704 log.debug("Match found. Parsing...");
\r
706 deserialize(ser_arr, contents);
\r
708 log.debug("Iterating retrieved session map...");
\r
709 list<string>::iterator iter;
\r
710 for(iter = contents.begin();
\r
711 iter != contents.end();
\r
714 // Update expiration times
\r
716 int read_res = readString(context, iter->c_str(), &value, NULL, 0);
\r
723 updateString(context, iter->c_str(), value.c_str(), expiration, read_res);
\r
725 replaceMemcache(map_name.c_str(), ser_arr, expiration, flags);
\r
730 void MemcacheStorageService::deleteContext(const char* context) {
\r
732 log.debug("deleteContext ctx: %s", context);
\r
735 log.error("deleteContext invoked on a Storage with no context map built!");
\r
739 string map_name = context;
\r
742 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
744 list<string> contents;
\r
746 log.debug("Match found. Parsing...");
\r
748 deserialize(ser_arr, contents);
\r
750 log.debug("Iterating retrieved session map...");
\r
751 list<string>::iterator iter;
\r
752 for(iter = contents.begin();
\r
753 iter != contents.end();
\r
755 string final_key = map_name + *iter;
\r
756 deleteMemcache(final_key.c_str(), 0);
\r
759 deleteMemcache(map_name.c_str(), 0);
\r
764 extern "C" int MCEXT_EXPORTS xmltooling_extension_init(void*) {
\r
765 // Register this SS type
\r
766 XMLToolingConfig::getConfig().StorageServiceManager.registerFactory("MEMCACHE", MemcacheStorageServiceFactory);
\r
770 extern "C" void MCEXT_EXPORTS xmltooling_extension_term() {
\r
771 XMLToolingConfig::getConfig().StorageServiceManager.deregisterFactory("MEMCACHE");
\r