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
29 #include <xercesc/util/XMLUniDefs.hpp>
\r
31 #include <xmltooling/logging.h>
\r
33 #include <xmltooling/XMLToolingConfig.h>
\r
34 #include <xmltooling/util/NDC.h>
\r
35 #include <xmltooling/util/StorageService.h>
\r
36 #include <xmltooling/util/XMLHelper.h>
\r
38 #include <libmemcached/memcached.h>
\r
40 using namespace xmltooling::logging;
\r
41 using namespace xmltooling;
\r
42 using namespace xercesc;
\r
43 using namespace std;
\r
45 namespace xmltooling {
\r
46 static const XMLCh Hosts[] = UNICODE_LITERAL_5(H,o,s,t,s);
\r
47 static const XMLCh prefix[] = UNICODE_LITERAL_6(p,r,e,f,i,x);
\r
48 static const XMLCh buildMap[] = UNICODE_LITERAL_8(b,u,i,l,d,M,a,p);
\r
55 mc_record(string _v, time_t _e) :
\r
56 value(_v), expiration(_e)
\r
60 class MemcacheBase {
\r
62 MemcacheBase(const DOMElement* e);
\r
65 bool addMemcache(const char *key,
\r
69 bool use_prefix = true);
\r
70 bool setMemcache(const char *key,
\r
74 bool use_prefix = true);
\r
75 bool replaceMemcache(const char *key,
\r
79 bool use_prefix = true);
\r
80 bool getMemcache(const char *key,
\r
83 bool use_prefix = true);
\r
84 bool deleteMemcache(const char *key,
\r
86 bool use_prefix = true);
\r
88 void serialize(mc_record &source, string &dest);
\r
89 void serialize(list<string> &source, string &dest);
\r
90 void deserialize(string &source, mc_record &dest);
\r
91 void deserialize(string &source, list<string> &dest);
\r
93 bool addSessionToUser(string &key, string &user);
\r
94 bool addLock(string what, bool use_prefix = true);
\r
95 void deleteLock(string what, bool use_prefix = true);
\r
98 const DOMElement* m_root; // can only use this during initialization
\r
100 memcached_st *memc;
\r
101 string m_memcacheHosts;
\r
106 class MemcacheStorageService : public StorageService, public MemcacheBase {
\r
109 MemcacheStorageService(const DOMElement* e);
\r
110 ~MemcacheStorageService();
\r
112 bool createString(const char* context, const char* key, const char* value, time_t expiration);
\r
113 int readString(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0);
\r
114 int updateString(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0);
\r
115 bool deleteString(const char* context, const char* key);
\r
117 bool createText(const char* context, const char* key, const char* value, time_t expiration) {
\r
118 return createString(context, key, value, expiration);
\r
120 int readText(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0) {
\r
121 return readString(context, key, pvalue, pexpiration, version);
\r
123 int updateText(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0) {
\r
124 return updateString(context, key, value, expiration, version);
\r
126 bool deleteText(const char* context, const char* key) {
\r
127 return deleteString(context, key);
\r
130 void reap(const char* context) {}
\r
132 void updateContext(const char* context, time_t expiration);
\r
133 void deleteContext(const char* context);
\r
143 StorageService* MemcacheStorageServiceFactory(const DOMElement* const & e) {
\r
144 return new MemcacheStorageService(e);
\r
149 bool MemcacheBase::addLock(string what, bool use_prefix) {
\r
150 string lock_name = what + ":LOCK";
\r
151 string set_val = "1";
\r
152 unsigned tries = 5;
\r
153 while (!addMemcache(lock_name.c_str(), set_val, 5, 0, use_prefix)) {
\r
155 log.debug("Unable to get lock %s... FAILED.", lock_name.c_str());
\r
158 log.debug("Unable to get lock %s... Retrying.", lock_name.c_str());
\r
161 struct timeval tv = { 0, 100000 };
\r
162 select(0, 0, 0, 0, &tv);
\r
167 void MemcacheBase::deleteLock(string what, bool use_prefix) {
\r
169 string lock_name = what + ":LOCK";
\r
170 deleteMemcache(lock_name.c_str(), 0, use_prefix);
\r
175 void MemcacheBase::deserialize(string &source, mc_record &dest) {
\r
176 istringstream is(source, stringstream::in | stringstream::out);
\r
177 is >> dest.expiration;
\r
178 is.ignore(1); // ignore delimiter
\r
179 dest.value = is.str().c_str() + is.tellg();
\r
182 void MemcacheBase::deserialize(string &source, list<string> &dest) {
\r
183 istringstream is(source, stringstream::in | stringstream::out);
\r
184 while (!is.eof()) {
\r
191 void MemcacheBase::serialize(mc_record &source, string &dest) {
\r
192 ostringstream os(stringstream::in | stringstream::out);
\r
193 os << source.expiration;
\r
194 os << "-"; // delimiter
\r
195 os << source.value;
\r
199 void MemcacheBase::serialize(list<string> &source, string &dest) {
\r
200 ostringstream os(stringstream::in | stringstream::out);
\r
201 for(list<string>::iterator iter = source.begin(); iter != source.end(); iter++) {
\r
202 if (iter != source.begin()) {
\r
210 bool MemcacheBase::addSessionToUser(string &key, string &user) {
\r
212 if (! addLock(user, false)) {
\r
218 string sessid = m_prefix + key; // add specific prefix to session
\r
219 string delimiter = ";";
\r
220 string user_key = "UDATA:";
\r
224 bool result = getMemcache(user_key.c_str(), user_val, &flags, false);
\r
227 bool already_there = false;
\r
228 // skip delimiters at beginning.
\r
229 string::size_type lastPos = user_val.find_first_not_of(delimiter, 0);
\r
231 // find first "non-delimiter".
\r
232 string::size_type pos = user_val.find_first_of(delimiter, lastPos);
\r
234 while (string::npos != pos || string::npos != lastPos) {
\r
235 // found a token, add it to the vector.
\r
236 string session = user_val.substr(lastPos, pos - lastPos);
\r
237 if (strcmp(session.c_str(), sessid.c_str()) == 0) {
\r
238 already_there = true;
\r
242 // skip delimiters. Note the "not_of"
\r
243 lastPos = user_val.find_first_not_of(delimiter, pos);
\r
245 // find next "non-delimiter"
\r
246 pos = user_val.find_first_of(delimiter, lastPos);
\r
249 if (!already_there) {
\r
250 user_val += delimiter + sessid;
\r
251 replaceMemcache(user_key.c_str(), user_val, 0, 0, false);
\r
254 addMemcache(user_key.c_str(), sessid, 0, 0, false);
\r
257 deleteLock(user, false);
\r
262 bool MemcacheBase::deleteMemcache(const char *key,
\r
265 memcached_return rv;
\r
267 memcached_st clone;
\r
271 final_key = m_prefix + key;
\r
276 if (memcached_clone(&clone, memc) == NULL) {
\r
277 throw IOException("MemcacheBase::deleteMemcache(): memcached_clone() failed");
\r
280 rv = memcached_delete(&clone, (char *)final_key.c_str(), final_key.length(), timeout);
\r
281 if (rv == MEMCACHED_SUCCESS) {
\r
283 } else if (rv == MEMCACHED_NOTFOUND) {
\r
284 // Key wasn't there... No biggie.
\r
287 log.error(string("Memcache::deleteMemcache() Problems: ") + memcached_strerror(&clone, rv));
\r
288 // shouldn't be here
\r
292 memcached_free(&clone);
\r
296 bool MemcacheBase::getMemcache(const char *key,
\r
300 memcached_return rv;
\r
304 memcached_st clone;
\r
308 final_key = m_prefix + key;
\r
313 if (memcached_clone(&clone, memc) == NULL) {
\r
314 throw IOException("MemcacheBase::getMemcache(): memcached_clone() failed");
\r
317 result = memcached_get(&clone, (char *)final_key.c_str(), final_key.length(), &len, flags, &rv);
\r
318 if (rv == MEMCACHED_SUCCESS) {
\r
322 } else if (rv == MEMCACHED_NOTFOUND) {
\r
323 log.debug("Key %s not found in memcache...", key);
\r
326 log.error(string("Memcache::getMemcache() Problems: ") + memcached_strerror(&clone, rv));
\r
330 memcached_free(&clone);
\r
334 bool MemcacheBase::addMemcache(const char *key,
\r
340 memcached_return rv;
\r
342 memcached_st clone;
\r
346 final_key = m_prefix + key;
\r
351 if (memcached_clone(&clone, memc) == NULL) {
\r
352 throw IOException("MemcacheBase::addMemcache(): memcached_clone() failed");
\r
355 rv = memcached_add(&clone, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
356 if (rv == MEMCACHED_SUCCESS) {
\r
358 } else if (rv == MEMCACHED_NOTSTORED) {
\r
362 // shouldn't be here
\r
363 log.error(string("Memcache::addMemcache() Problems: ") + memcached_strerror(&clone, rv));
\r
367 memcached_free(&clone);
\r
371 bool MemcacheBase::setMemcache(const char *key,
\r
377 memcached_return rv;
\r
379 memcached_st clone;
\r
383 final_key = m_prefix + key;
\r
388 if (memcached_clone(&clone, memc) == NULL) {
\r
389 throw IOException("MemcacheBase::setMemcache(): memcached_clone() failed");
\r
392 rv = memcached_set(&clone, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
393 if (rv == MEMCACHED_SUCCESS) {
\r
396 // shouldn't be here
\r
397 log.error(string("Memcache::setMemcache() Problems: ") + memcached_strerror(&clone, rv));
\r
401 memcached_free(&clone);
\r
405 bool MemcacheBase::replaceMemcache(const char *key,
\r
411 memcached_return rv;
\r
413 memcached_st clone;
\r
417 final_key = m_prefix + key;
\r
422 if (memcached_clone(&clone, memc) == NULL) {
\r
423 throw IOException("MemcacheBase::replaceMemcache(): memcached_clone() failed");
\r
426 rv = memcached_replace(&clone, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
427 if (rv == MEMCACHED_SUCCESS) {
\r
429 } else if (rv == MEMCACHED_NOTSTORED) {
\r
433 // shouldn't be here
\r
434 log.error(string("Memcache::replaceMemcache() Problems: ") + memcached_strerror(&clone, rv));
\r
438 memcached_free(&clone);
\r
442 MemcacheBase::MemcacheBase(const DOMElement* e) : m_root(e), log(Category::getInstance("XMLTooling.MemcacheBase")), m_memcacheHosts(""), m_prefix("") {
\r
444 auto_ptr_char p(e ? e->getAttributeNS(NULL,prefix) : NULL);
\r
445 if (p.get() && *p.get()) {
\r
446 log.debug("INIT: GOT key prefix: %s", p.get());
\r
447 m_prefix = p.get();
\r
450 // Grab hosts from the configuration.
\r
451 e = e ? XMLHelper::getFirstChildElement(e,Hosts) : NULL;
\r
452 if (!e || !e->hasChildNodes()) {
\r
453 throw XMLToolingException("Memcache StorageService requires Hosts element in configuration.");
\r
455 auto_ptr_char h(e->getFirstChild()->getNodeValue());
\r
456 log.debug("INIT: GOT Hosts: %s", h.get());
\r
457 m_memcacheHosts = h.get();
\r
459 memc = memcached_create(NULL);
\r
460 if (memc == NULL) {
\r
461 throw XMLToolingException("MemcacheBase::Memcache(): memcached_create() failed");
\r
464 log.debug("Memcache created");
\r
466 unsigned int set = MEMCACHED_HASH_CRC;
\r
467 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_HASH, set);
\r
468 log.debug("CRC hash set");
\r
470 memcached_server_st *servers;
\r
471 servers = memcached_servers_parse((char *)m_memcacheHosts.c_str());
\r
472 log.debug("Got %u hosts.", memcached_server_list_count(servers));
\r
473 if (memcached_server_push(memc, servers) != MEMCACHED_SUCCESS) {
\r
474 throw IOException("MemcacheBase::Memcache(): memcached_server_push() failed");
\r
476 memcached_server_list_free(servers);
\r
478 log.debug("Memcache object initialized");
\r
481 MemcacheBase::~MemcacheBase() {
\r
482 memcached_free(memc);
\r
483 log.debug("Base object destroyed");
\r
486 MemcacheStorageService::MemcacheStorageService(const DOMElement* e)
\r
487 : MemcacheBase(e), m_log(Category::getInstance("XMLTooling.MemcacheStorageService")), m_buildMap(false) {
\r
489 const XMLCh* tag=e ? e->getAttributeNS(NULL,buildMap) : NULL;
\r
490 if (tag && *tag && XMLString::parseInt(tag) != 0) {
\r
492 m_log.debug("Cache built with buildMap ON");
\r
497 MemcacheStorageService::~MemcacheStorageService() {
\r
502 bool MemcacheStorageService::createString(const char* context, const char* key, const char* value, time_t expiration) {
\r
504 log.debug("createString ctx: %s - key: %s", context, key);
\r
506 string final_key = string(context) + ":" + string(key);
\r
508 mc_record rec(value, expiration);
\r
509 string final_value;
\r
510 serialize(rec, final_value);
\r
512 bool result = addMemcache(final_key.c_str(), final_value, expiration, 1); // the flag will be the version
\r
514 if (result && m_buildMap) {
\r
515 log.debug("Got result, updating map");
\r
517 string map_name = context;
\r
518 // we need to update the context map
\r
519 if (! addLock(map_name)) {
\r
520 log.error("Unable to get lock for context %s!", context);
\r
521 deleteMemcache(final_key.c_str(), 0);
\r
527 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
529 list<string> contents;
\r
531 log.debug("Match found. Parsing...");
\r
533 deserialize(ser_arr, contents);
\r
535 log.debug("Iterating retrieved session map...");
\r
536 list<string>::iterator iter;
\r
537 for(iter = contents.begin();
\r
538 iter != contents.end();
\r
540 log.debug("value = " + *iter);
\r
544 log.debug("New context: %s", map_name.c_str());
\r
548 contents.push_back(key);
\r
549 serialize(contents, ser_arr);
\r
550 setMemcache(map_name.c_str(), ser_arr, expiration, 0);
\r
552 deleteLock(map_name);
\r
559 int MemcacheStorageService::readString(const char* context, const char* key, string* pvalue, time_t* pexpiration, int version) {
\r
561 log.debug("readString ctx: %s - key: %s", context, key);
\r
563 string final_key = string(context) + ":" + string(key);
\r
564 uint32_t rec_version;
\r
567 bool found = getMemcache(final_key.c_str(), value, &rec_version);
\r
572 if (version && rec_version <= (uint32_t)version) {
\r
576 if (pexpiration || pvalue) {
\r
578 deserialize(value, rec);
\r
581 *pexpiration = rec.expiration;
\r
585 *pvalue = rec.value;
\r
589 return rec_version;
\r
593 int MemcacheStorageService::updateString(const char* context, const char* key, const char* value, time_t expiration, int version) {
\r
595 log.debug("updateString ctx: %s - key: %s", context, key);
\r
597 time_t final_exp = expiration;
\r
598 time_t *want_expiration = NULL;
\r
600 want_expiration = &final_exp;
\r
603 int read_res = readString(context, key, NULL, want_expiration, version);
\r
610 if (version && version != read_res) {
\r
611 // version incorrect
\r
615 // Proceding with update
\r
616 string final_key = string(context) + ":" + string(key);
\r
617 mc_record rec(value, final_exp);
\r
618 string final_value;
\r
619 serialize(rec, final_value);
\r
621 replaceMemcache(final_key.c_str(), final_value, final_exp, ++version);
\r
626 bool MemcacheStorageService::deleteString(const char* context, const char* key) {
\r
628 log.debug("deleteString ctx: %s - key: %s", context, key);
\r
630 string final_key = string(context) + ":" + string(key);
\r
632 // Not updating context map, if there is one. There is no need.
\r
634 return deleteMemcache(final_key.c_str(), 0);
\r
638 void MemcacheStorageService::updateContext(const char* context, time_t expiration) {
\r
640 log.debug("updateContext ctx: %s", context);
\r
643 log.error("updateContext invoked on a Storage with no context map built!");
\r
647 string map_name = context;
\r
649 if (! addLock(map_name)) {
\r
650 log.error("Unable to get lock for context %s!", context);
\r
656 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
658 list<string> contents;
\r
660 log.debug("Match found. Parsing...");
\r
662 deserialize(ser_arr, contents);
\r
664 log.debug("Iterating retrieved session map...");
\r
665 list<string>::iterator iter;
\r
666 for(iter = contents.begin();
\r
667 iter != contents.end();
\r
670 // Update expiration times
\r
672 int read_res = readString(context, iter->c_str(), &value, NULL, 0);
\r
679 updateString(context, iter->c_str(), value.c_str(), expiration, read_res);
\r
681 replaceMemcache(map_name.c_str(), ser_arr, expiration, flags);
\r
684 deleteLock(map_name);
\r
688 void MemcacheStorageService::deleteContext(const char* context) {
\r
690 log.debug("deleteContext ctx: %s", context);
\r
693 log.error("deleteContext invoked on a Storage with no context map built!");
\r
697 string map_name = context;
\r
699 if (! addLock(map_name)) {
\r
700 log.error("Unable to get lock for context %s!", context);
\r
706 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
708 list<string> contents;
\r
710 log.debug("Match found. Parsing...");
\r
712 deserialize(ser_arr, contents);
\r
714 log.debug("Iterating retrieved session map...");
\r
715 list<string>::iterator iter;
\r
716 for(iter = contents.begin();
\r
717 iter != contents.end();
\r
719 string final_key = map_name + *iter;
\r
720 deleteMemcache(final_key.c_str(), 0);
\r
723 deleteMemcache(map_name.c_str(), 0);
\r
726 deleteLock(map_name);
\r
730 extern "C" int xmltooling_extension_init(void*) {
\r
731 // Register this SS type
\r
732 XMLToolingConfig::getConfig().StorageServiceManager.registerFactory("MEMCACHE", MemcacheStorageServiceFactory);
\r
736 extern "C" void xmltooling_extension_term() {
\r
737 XMLToolingConfig::getConfig().StorageServiceManager.deregisterFactory("MEMCACHE");
\r