2 * Copyright 2001-2008 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
39 #include <iostream>
\r
40 #include <libmemcached/memcached.h>
\r
41 #include <xercesc/util/XMLUniDefs.hpp>
\r
43 #include <xmltooling/logging.h>
\r
44 #include <xmltooling/XMLToolingConfig.h>
\r
45 #include <xmltooling/util/NDC.h>
\r
46 #include <xmltooling/util/StorageService.h>
\r
47 #include <xmltooling/util/XMLHelper.h>
\r
49 using namespace xmltooling::logging;
\r
50 using namespace xmltooling;
\r
51 using namespace xercesc;
\r
52 using namespace std;
\r
54 namespace xmltooling {
\r
55 static const XMLCh Hosts[] = UNICODE_LITERAL_5(H,o,s,t,s);
\r
56 static const XMLCh prefix[] = UNICODE_LITERAL_6(p,r,e,f,i,x);
\r
57 static const XMLCh buildMap[] = UNICODE_LITERAL_8(b,u,i,l,d,M,a,p);
\r
64 mc_record(string _v, time_t _e) :
\r
65 value(_v), expiration(_e)
\r
69 class MemcacheBase {
\r
71 MemcacheBase(const DOMElement* e);
\r
74 bool addMemcache(const char *key,
\r
78 bool use_prefix = true);
\r
79 bool setMemcache(const char *key,
\r
83 bool use_prefix = true);
\r
84 bool replaceMemcache(const char *key,
\r
88 bool use_prefix = true);
\r
89 bool getMemcache(const char *key,
\r
92 bool use_prefix = true);
\r
93 bool deleteMemcache(const char *key,
\r
95 bool use_prefix = true);
\r
97 void serialize(mc_record &source, string &dest);
\r
98 void serialize(list<string> &source, string &dest);
\r
99 void deserialize(string &source, mc_record &dest);
\r
100 void deserialize(string &source, list<string> &dest);
\r
102 bool addSessionToUser(string &key, string &user);
\r
103 bool addLock(string what, bool use_prefix = true);
\r
104 void deleteLock(string what, bool use_prefix = true);
\r
107 const DOMElement* m_root; // can only use this during initialization
\r
109 memcached_st *memc;
\r
110 string m_memcacheHosts;
\r
115 class MemcacheStorageService : public StorageService, public MemcacheBase {
\r
118 MemcacheStorageService(const DOMElement* e);
\r
119 ~MemcacheStorageService();
\r
121 bool createString(const char* context, const char* key, const char* value, time_t expiration);
\r
122 int readString(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0);
\r
123 int updateString(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0);
\r
124 bool deleteString(const char* context, const char* key);
\r
126 bool createText(const char* context, const char* key, const char* value, time_t expiration) {
\r
127 return createString(context, key, value, expiration);
\r
129 int readText(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0) {
\r
130 return readString(context, key, pvalue, pexpiration, version);
\r
132 int updateText(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0) {
\r
133 return updateString(context, key, value, expiration, version);
\r
135 bool deleteText(const char* context, const char* key) {
\r
136 return deleteString(context, key);
\r
139 void reap(const char* context) {}
\r
141 void updateContext(const char* context, time_t expiration);
\r
142 void deleteContext(const char* context);
\r
152 StorageService* MemcacheStorageServiceFactory(const DOMElement* const & e) {
\r
153 return new MemcacheStorageService(e);
\r
158 bool MemcacheBase::addLock(string what, bool use_prefix) {
\r
159 string lock_name = what + ":LOCK";
\r
160 string set_val = "1";
\r
161 unsigned tries = 5;
\r
162 while (!addMemcache(lock_name.c_str(), set_val, 5, 0, use_prefix)) {
\r
163 if (tries-- == 0) {
\r
164 log.debug("Unable to get lock %s... FAILED.", lock_name.c_str());
\r
167 log.debug("Unable to get lock %s... Retrying.", lock_name.c_str());
\r
173 struct timeval tv = { 0, 100000 };
\r
174 select(0, 0, 0, 0, &tv);
\r
180 void MemcacheBase::deleteLock(string what, bool use_prefix) {
\r
182 string lock_name = what + ":LOCK";
\r
183 deleteMemcache(lock_name.c_str(), 0, use_prefix);
\r
188 void MemcacheBase::deserialize(string &source, mc_record &dest) {
\r
189 istringstream is(source, stringstream::in | stringstream::out);
\r
190 is >> dest.expiration;
\r
191 is.ignore(1); // ignore delimiter
\r
192 dest.value = is.str().c_str() + is.tellg();
\r
195 void MemcacheBase::deserialize(string &source, list<string> &dest) {
\r
196 istringstream is(source, stringstream::in | stringstream::out);
\r
197 while (!is.eof()) {
\r
204 void MemcacheBase::serialize(mc_record &source, string &dest) {
\r
205 ostringstream os(stringstream::in | stringstream::out);
\r
206 os << source.expiration;
\r
207 os << "-"; // delimiter
\r
208 os << source.value;
\r
212 void MemcacheBase::serialize(list<string> &source, string &dest) {
\r
213 ostringstream os(stringstream::in | stringstream::out);
\r
214 for(list<string>::iterator iter = source.begin(); iter != source.end(); iter++) {
\r
215 if (iter != source.begin()) {
\r
223 bool MemcacheBase::addSessionToUser(string &key, string &user) {
\r
225 if (! addLock(user, false)) {
\r
231 string sessid = m_prefix + key; // add specific prefix to session
\r
232 string delimiter = ";";
\r
233 string user_key = "UDATA:";
\r
237 bool result = getMemcache(user_key.c_str(), user_val, &flags, false);
\r
240 bool already_there = false;
\r
241 // skip delimiters at beginning.
\r
242 string::size_type lastPos = user_val.find_first_not_of(delimiter, 0);
\r
244 // find first "non-delimiter".
\r
245 string::size_type pos = user_val.find_first_of(delimiter, lastPos);
\r
247 while (string::npos != pos || string::npos != lastPos) {
\r
248 // found a token, add it to the vector.
\r
249 string session = user_val.substr(lastPos, pos - lastPos);
\r
250 if (strcmp(session.c_str(), sessid.c_str()) == 0) {
\r
251 already_there = true;
\r
255 // skip delimiters. Note the "not_of"
\r
256 lastPos = user_val.find_first_not_of(delimiter, pos);
\r
258 // find next "non-delimiter"
\r
259 pos = user_val.find_first_of(delimiter, lastPos);
\r
262 if (!already_there) {
\r
263 user_val += delimiter + sessid;
\r
264 replaceMemcache(user_key.c_str(), user_val, 0, 0, false);
\r
267 addMemcache(user_key.c_str(), sessid, 0, 0, false);
\r
270 deleteLock(user, false);
\r
275 bool MemcacheBase::deleteMemcache(const char *key,
\r
278 memcached_return rv;
\r
283 final_key = m_prefix + key;
\r
289 rv = memcached_delete(memc, (char *)final_key.c_str(), final_key.length(), timeout);
\r
292 if (rv == MEMCACHED_SUCCESS) {
\r
294 } else if (rv == MEMCACHED_NOTFOUND) {
\r
295 // Key wasn't there... No biggie.
\r
297 } else if (rv == MEMCACHED_ERRNO) {
\r
299 log.error(string("Memcache::deleteMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
302 log.error(string("Memcache::deleteMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
303 // shouldn't be here
\r
310 bool MemcacheBase::getMemcache(const char *key,
\r
314 memcached_return rv;
\r
321 final_key = m_prefix + key;
\r
327 result = memcached_get(memc, (char *)final_key.c_str(), final_key.length(), &len, flags, &rv);
\r
330 if (rv == MEMCACHED_SUCCESS) {
\r
334 } else if (rv == MEMCACHED_NOTFOUND) {
\r
335 log.debug("Key %s not found in memcache...", key);
\r
337 } else if (rv == MEMCACHED_ERRNO) {
\r
339 log.error(string("Memcache::getMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
342 log.error(string("Memcache::getMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
349 bool MemcacheBase::addMemcache(const char *key,
\r
355 memcached_return rv;
\r
360 final_key = m_prefix + key;
\r
366 rv = memcached_add(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
369 if (rv == MEMCACHED_SUCCESS) {
\r
371 } else if (rv == MEMCACHED_NOTSTORED) {
\r
374 } else if (rv == MEMCACHED_ERRNO) {
\r
376 log.error(string("Memcache::addMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
379 // shouldn't be here
\r
380 log.error(string("Memcache::addMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
387 bool MemcacheBase::setMemcache(const char *key,
\r
393 memcached_return rv;
\r
398 final_key = m_prefix + key;
\r
404 rv = memcached_set(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
407 if (rv == MEMCACHED_SUCCESS) {
\r
409 } else if (rv == MEMCACHED_ERRNO) {
\r
411 log.error(string("Memcache::setMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
414 // shouldn't be here
\r
415 log.error(string("Memcache::setMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
422 bool MemcacheBase::replaceMemcache(const char *key,
\r
428 memcached_return rv;
\r
433 final_key = m_prefix + key;
\r
439 rv = memcached_replace(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
442 if (rv == MEMCACHED_SUCCESS) {
\r
444 } else if (rv == MEMCACHED_NOTSTORED) {
\r
447 } else if (rv == MEMCACHED_ERRNO) {
\r
449 log.error(string("Memcache::replaceMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
452 // shouldn't be here
\r
453 log.error(string("Memcache::replaceMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
460 MemcacheBase::MemcacheBase(const DOMElement* e) : m_root(e), log(Category::getInstance("XMLTooling.MemcacheBase")), m_memcacheHosts(""), m_prefix("") {
\r
462 auto_ptr_char p(e ? e->getAttributeNS(NULL,prefix) : NULL);
\r
463 if (p.get() && *p.get()) {
\r
464 log.debug("INIT: GOT key prefix: %s", p.get());
\r
465 m_prefix = p.get();
\r
468 // Grab hosts from the configuration.
\r
469 e = e ? XMLHelper::getFirstChildElement(e,Hosts) : NULL;
\r
470 if (!e || !e->hasChildNodes()) {
\r
471 throw XMLToolingException("Memcache StorageService requires Hosts element in configuration.");
\r
473 auto_ptr_char h(e->getFirstChild()->getNodeValue());
\r
474 log.debug("INIT: GOT Hosts: %s", h.get());
\r
475 m_memcacheHosts = h.get();
\r
477 m_lock = Mutex::create();
\r
478 log.debug("Lock created");
\r
480 memc = memcached_create(NULL);
\r
481 if (memc == NULL) {
\r
482 throw XMLToolingException("MemcacheBase::Memcache(): memcached_create() failed");
\r
485 log.debug("Memcache created");
\r
487 unsigned int hash = MEMCACHED_HASH_CRC;
\r
488 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_HASH, hash);
\r
489 log.debug("CRC hash set");
\r
491 int32_t timeout = 1000000;
\r
492 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SND_TIMEOUT, timeout);
\r
493 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, timeout);
\r
495 int32_t poll_timeout = 1000;
\r
496 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_POLL_TIMEOUT, poll_timeout);
\r
498 int32_t fail_limit = 5;
\r
499 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, fail_limit);
\r
501 int32_t retry_timeout = 30;
\r
502 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, retry_timeout);
\r
504 memcached_server_st *servers;
\r
505 servers = memcached_servers_parse((char *)m_memcacheHosts.c_str());
\r
506 log.debug("Got %u hosts.", memcached_server_list_count(servers));
\r
507 if (memcached_server_push(memc, servers) != MEMCACHED_SUCCESS) {
\r
508 throw IOException("MemcacheBase::Memcache(): memcached_server_push() failed");
\r
510 memcached_server_list_free(servers);
\r
512 log.debug("Memcache object initialized");
\r
515 MemcacheBase::~MemcacheBase() {
\r
516 memcached_free(memc);
\r
518 log.debug("Base object destroyed");
\r
521 MemcacheStorageService::MemcacheStorageService(const DOMElement* e)
\r
522 : MemcacheBase(e), m_log(Category::getInstance("XMLTooling.MemcacheStorageService")), m_buildMap(false) {
\r
524 const XMLCh* tag=e ? e->getAttributeNS(NULL,buildMap) : NULL;
\r
525 if (tag && *tag && XMLString::parseInt(tag) != 0) {
\r
527 m_log.debug("Cache built with buildMap ON");
\r
532 MemcacheStorageService::~MemcacheStorageService() {
\r
537 bool MemcacheStorageService::createString(const char* context, const char* key, const char* value, time_t expiration) {
\r
539 log.debug("createString ctx: %s - key: %s", context, key);
\r
541 string final_key = string(context) + ":" + string(key);
\r
543 mc_record rec(value, expiration);
\r
544 string final_value;
\r
545 serialize(rec, final_value);
\r
547 bool result = addMemcache(final_key.c_str(), final_value, expiration, 1); // the flag will be the version
\r
549 if (result && m_buildMap) {
\r
550 log.debug("Got result, updating map");
\r
552 string map_name = context;
\r
553 // we need to update the context map
\r
554 if (! addLock(map_name)) {
\r
555 log.error("Unable to get lock for context %s!", context);
\r
556 deleteMemcache(final_key.c_str(), 0);
\r
562 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
564 list<string> contents;
\r
566 log.debug("Match found. Parsing...");
\r
568 deserialize(ser_arr, contents);
\r
570 log.debug("Iterating retrieved session map...");
\r
571 list<string>::iterator iter;
\r
572 for(iter = contents.begin();
\r
573 iter != contents.end();
\r
575 log.debug("value = " + *iter);
\r
579 log.debug("New context: %s", map_name.c_str());
\r
583 contents.push_back(key);
\r
584 serialize(contents, ser_arr);
\r
585 setMemcache(map_name.c_str(), ser_arr, expiration, 0);
\r
587 deleteLock(map_name);
\r
594 int MemcacheStorageService::readString(const char* context, const char* key, string* pvalue, time_t* pexpiration, int version) {
\r
596 log.debug("readString ctx: %s - key: %s", context, key);
\r
598 string final_key = string(context) + ":" + string(key);
\r
599 uint32_t rec_version;
\r
603 log.debug("Checking context");
\r
605 string map_name = context;
\r
608 bool ctx_found = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
615 bool found = getMemcache(final_key.c_str(), value, &rec_version);
\r
620 if (version && rec_version <= (uint32_t)version) {
\r
624 if (pexpiration || pvalue) {
\r
626 deserialize(value, rec);
\r
629 *pexpiration = rec.expiration;
\r
633 *pvalue = rec.value;
\r
637 return rec_version;
\r
641 int MemcacheStorageService::updateString(const char* context, const char* key, const char* value, time_t expiration, int version) {
\r
643 log.debug("updateString ctx: %s - key: %s", context, key);
\r
645 time_t final_exp = expiration;
\r
646 time_t *want_expiration = NULL;
\r
648 want_expiration = &final_exp;
\r
651 int read_res = readString(context, key, NULL, want_expiration, version);
\r
658 if (version && version != read_res) {
\r
659 // version incorrect
\r
663 // Proceding with update
\r
664 string final_key = string(context) + ":" + string(key);
\r
665 mc_record rec(value, final_exp);
\r
666 string final_value;
\r
667 serialize(rec, final_value);
\r
669 replaceMemcache(final_key.c_str(), final_value, final_exp, ++version);
\r
674 bool MemcacheStorageService::deleteString(const char* context, const char* key) {
\r
676 log.debug("deleteString ctx: %s - key: %s", context, key);
\r
678 string final_key = string(context) + ":" + string(key);
\r
680 // Not updating context map, if there is one. There is no need.
\r
682 return deleteMemcache(final_key.c_str(), 0);
\r
686 void MemcacheStorageService::updateContext(const char* context, time_t expiration) {
\r
688 log.debug("updateContext ctx: %s", context);
\r
691 log.error("updateContext invoked on a Storage with no context map built!");
\r
695 string map_name = context;
\r
698 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
700 list<string> contents;
\r
702 log.debug("Match found. Parsing...");
\r
704 deserialize(ser_arr, contents);
\r
706 log.debug("Iterating retrieved session map...");
\r
707 list<string>::iterator iter;
\r
708 for(iter = contents.begin();
\r
709 iter != contents.end();
\r
712 // Update expiration times
\r
714 int read_res = readString(context, iter->c_str(), &value, NULL, 0);
\r
721 updateString(context, iter->c_str(), value.c_str(), expiration, read_res);
\r
723 replaceMemcache(map_name.c_str(), ser_arr, expiration, flags);
\r
728 void MemcacheStorageService::deleteContext(const char* context) {
\r
730 log.debug("deleteContext ctx: %s", context);
\r
733 log.error("deleteContext invoked on a Storage with no context map built!");
\r
737 string map_name = context;
\r
740 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
742 list<string> contents;
\r
744 log.debug("Match found. Parsing...");
\r
746 deserialize(ser_arr, contents);
\r
748 log.debug("Iterating retrieved session map...");
\r
749 list<string>::iterator iter;
\r
750 for(iter = contents.begin();
\r
751 iter != contents.end();
\r
753 string final_key = map_name + *iter;
\r
754 deleteMemcache(final_key.c_str(), 0);
\r
757 deleteMemcache(map_name.c_str(), 0);
\r
762 extern "C" int MCEXT_EXPORTS xmltooling_extension_init(void*) {
\r
763 // Register this SS type
\r
764 XMLToolingConfig::getConfig().StorageServiceManager.registerFactory("MEMCACHE", MemcacheStorageServiceFactory);
\r
768 extern "C" void MCEXT_EXPORTS xmltooling_extension_term() {
\r
769 XMLToolingConfig::getConfig().StorageServiceManager.deregisterFactory("MEMCACHE");
\r