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/XMLHelper.h>
\r
50 using namespace xmltooling::logging;
\r
51 using namespace xmltooling;
\r
52 using namespace xercesc;
\r
53 using namespace std;
\r
55 namespace xmltooling {
\r
56 static const XMLCh Hosts[] = UNICODE_LITERAL_5(H,o,s,t,s);
\r
57 static const XMLCh prefix[] = UNICODE_LITERAL_6(p,r,e,f,i,x);
\r
58 static const XMLCh buildMap[] = UNICODE_LITERAL_8(b,u,i,l,d,M,a,p);
\r
65 mc_record(string _v, time_t _e) :
\r
66 value(_v), expiration(_e)
\r
70 class MemcacheBase {
\r
72 MemcacheBase(const DOMElement* e);
\r
75 bool addMemcache(const char *key,
\r
79 bool use_prefix = true);
\r
80 bool setMemcache(const char *key,
\r
84 bool use_prefix = true);
\r
85 bool replaceMemcache(const char *key,
\r
89 bool use_prefix = true);
\r
90 bool getMemcache(const char *key,
\r
93 bool use_prefix = true);
\r
94 bool deleteMemcache(const char *key,
\r
96 bool use_prefix = true);
\r
98 void serialize(mc_record &source, string &dest);
\r
99 void serialize(list<string> &source, string &dest);
\r
100 void deserialize(string &source, mc_record &dest);
\r
101 void deserialize(string &source, list<string> &dest);
\r
103 bool addSessionToUser(string &key, string &user);
\r
104 bool addLock(string what, bool use_prefix = true);
\r
105 void deleteLock(string what, bool use_prefix = true);
\r
108 const DOMElement* m_root; // can only use this during initialization
\r
110 memcached_st *memc;
\r
111 string m_memcacheHosts;
\r
116 class MemcacheStorageService : public StorageService, public MemcacheBase {
\r
119 MemcacheStorageService(const DOMElement* e);
\r
120 ~MemcacheStorageService();
\r
122 bool createString(const char* context, const char* key, const char* value, time_t expiration);
\r
123 int readString(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0);
\r
124 int updateString(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0);
\r
125 bool deleteString(const char* context, const char* key);
\r
127 bool createText(const char* context, const char* key, const char* value, time_t expiration) {
\r
128 return createString(context, key, value, expiration);
\r
130 int readText(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0) {
\r
131 return readString(context, key, pvalue, pexpiration, version);
\r
133 int updateText(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0) {
\r
134 return updateString(context, key, value, expiration, version);
\r
136 bool deleteText(const char* context, const char* key) {
\r
137 return deleteString(context, key);
\r
140 void reap(const char* context) {}
\r
142 void updateContext(const char* context, time_t expiration);
\r
143 void deleteContext(const char* context);
\r
153 StorageService* MemcacheStorageServiceFactory(const DOMElement* const & e) {
\r
154 return new MemcacheStorageService(e);
\r
159 bool MemcacheBase::addLock(string what, bool use_prefix) {
\r
160 string lock_name = what + ":LOCK";
\r
161 string set_val = "1";
\r
162 unsigned tries = 5;
\r
163 while (!addMemcache(lock_name.c_str(), set_val, 5, 0, use_prefix)) {
\r
164 if (tries-- == 0) {
\r
165 log.debug("Unable to get lock %s... FAILED.", lock_name.c_str());
\r
168 log.debug("Unable to get lock %s... Retrying.", lock_name.c_str());
\r
174 struct timeval tv = { 0, 100000 };
\r
175 select(0, 0, 0, 0, &tv);
\r
181 void MemcacheBase::deleteLock(string what, bool use_prefix) {
\r
183 string lock_name = what + ":LOCK";
\r
184 deleteMemcache(lock_name.c_str(), 0, use_prefix);
\r
189 void MemcacheBase::deserialize(string &source, mc_record &dest) {
\r
190 istringstream is(source, stringstream::in | stringstream::out);
\r
191 is >> dest.expiration;
\r
192 is.ignore(1); // ignore delimiter
\r
193 dest.value = is.str().c_str() + is.tellg();
\r
196 void MemcacheBase::deserialize(string &source, list<string> &dest) {
\r
197 istringstream is(source, stringstream::in | stringstream::out);
\r
198 while (!is.eof()) {
\r
205 void MemcacheBase::serialize(mc_record &source, string &dest) {
\r
206 ostringstream os(stringstream::in | stringstream::out);
\r
207 os << source.expiration;
\r
208 os << "-"; // delimiter
\r
209 os << source.value;
\r
213 void MemcacheBase::serialize(list<string> &source, string &dest) {
\r
214 ostringstream os(stringstream::in | stringstream::out);
\r
215 for(list<string>::iterator iter = source.begin(); iter != source.end(); iter++) {
\r
216 if (iter != source.begin()) {
\r
224 bool MemcacheBase::addSessionToUser(string &key, string &user) {
\r
226 if (! addLock(user, false)) {
\r
232 string sessid = m_prefix + key; // add specific prefix to session
\r
233 string delimiter = ";";
\r
234 string user_key = "UDATA:";
\r
238 bool result = getMemcache(user_key.c_str(), user_val, &flags, false);
\r
241 bool already_there = false;
\r
242 // skip delimiters at beginning.
\r
243 string::size_type lastPos = user_val.find_first_not_of(delimiter, 0);
\r
245 // find first "non-delimiter".
\r
246 string::size_type pos = user_val.find_first_of(delimiter, lastPos);
\r
248 while (string::npos != pos || string::npos != lastPos) {
\r
249 // found a token, add it to the vector.
\r
250 string session = user_val.substr(lastPos, pos - lastPos);
\r
251 if (strcmp(session.c_str(), sessid.c_str()) == 0) {
\r
252 already_there = true;
\r
256 // skip delimiters. Note the "not_of"
\r
257 lastPos = user_val.find_first_not_of(delimiter, pos);
\r
259 // find next "non-delimiter"
\r
260 pos = user_val.find_first_of(delimiter, lastPos);
\r
263 if (!already_there) {
\r
264 user_val += delimiter + sessid;
\r
265 replaceMemcache(user_key.c_str(), user_val, 0, 0, false);
\r
268 addMemcache(user_key.c_str(), sessid, 0, 0, false);
\r
271 deleteLock(user, false);
\r
276 bool MemcacheBase::deleteMemcache(const char *key,
\r
279 memcached_return rv;
\r
284 final_key = m_prefix + key;
\r
290 rv = memcached_delete(memc, (char *)final_key.c_str(), final_key.length(), timeout);
\r
293 if (rv == MEMCACHED_SUCCESS) {
\r
295 } else if (rv == MEMCACHED_NOTFOUND) {
\r
296 // Key wasn't there... No biggie.
\r
298 } else if (rv == MEMCACHED_ERRNO) {
\r
300 log.error(string("Memcache::deleteMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
303 log.error(string("Memcache::deleteMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
304 // shouldn't be here
\r
311 bool MemcacheBase::getMemcache(const char *key,
\r
315 memcached_return rv;
\r
322 final_key = m_prefix + key;
\r
328 result = memcached_get(memc, (char *)final_key.c_str(), final_key.length(), &len, flags, &rv);
\r
331 if (rv == MEMCACHED_SUCCESS) {
\r
335 } else if (rv == MEMCACHED_NOTFOUND) {
\r
336 log.debug("Key %s not found in memcache...", key);
\r
338 } else if (rv == MEMCACHED_ERRNO) {
\r
340 log.error(string("Memcache::getMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
343 log.error(string("Memcache::getMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
350 bool MemcacheBase::addMemcache(const char *key,
\r
356 memcached_return rv;
\r
361 final_key = m_prefix + key;
\r
367 rv = memcached_add(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
370 if (rv == MEMCACHED_SUCCESS) {
\r
372 } else if (rv == MEMCACHED_NOTSTORED) {
\r
375 } else if (rv == MEMCACHED_ERRNO) {
\r
377 log.error(string("Memcache::addMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
380 // shouldn't be here
\r
381 log.error(string("Memcache::addMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
388 bool MemcacheBase::setMemcache(const char *key,
\r
394 memcached_return rv;
\r
399 final_key = m_prefix + key;
\r
405 rv = memcached_set(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
408 if (rv == MEMCACHED_SUCCESS) {
\r
410 } else if (rv == MEMCACHED_ERRNO) {
\r
412 log.error(string("Memcache::setMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
415 // shouldn't be here
\r
416 log.error(string("Memcache::setMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
423 bool MemcacheBase::replaceMemcache(const char *key,
\r
429 memcached_return rv;
\r
434 final_key = m_prefix + key;
\r
440 rv = memcached_replace(memc, (char *)final_key.c_str(), final_key.length(), (char *)value.c_str(), value.length(), timeout, flags);
\r
443 if (rv == MEMCACHED_SUCCESS) {
\r
445 } else if (rv == MEMCACHED_NOTSTORED) {
\r
448 } else if (rv == MEMCACHED_ERRNO) {
\r
450 log.error(string("Memcache::replaceMemcache() SYSTEM ERROR: ") + string(strerror(memc->cached_errno)));
\r
453 // shouldn't be here
\r
454 log.error(string("Memcache::replaceMemcache() Problems: ") + memcached_strerror(memc, rv));
\r
461 MemcacheBase::MemcacheBase(const DOMElement* e) : m_root(e), log(Category::getInstance("XMLTooling.MemcacheBase")), m_memcacheHosts(""), m_prefix("") {
\r
463 auto_ptr_char p(e ? e->getAttributeNS(NULL,prefix) : NULL);
\r
464 if (p.get() && *p.get()) {
\r
465 log.debug("INIT: GOT key prefix: %s", p.get());
\r
466 m_prefix = p.get();
\r
469 // Grab hosts from the configuration.
\r
470 e = e ? XMLHelper::getFirstChildElement(e,Hosts) : NULL;
\r
471 if (!e || !e->hasChildNodes()) {
\r
472 throw XMLToolingException("Memcache StorageService requires Hosts element in configuration.");
\r
474 auto_ptr_char h(e->getFirstChild()->getNodeValue());
\r
475 log.debug("INIT: GOT Hosts: %s", h.get());
\r
476 m_memcacheHosts = h.get();
\r
478 m_lock = Mutex::create();
\r
479 log.debug("Lock created");
\r
481 memc = memcached_create(NULL);
\r
482 if (memc == NULL) {
\r
483 throw XMLToolingException("MemcacheBase::Memcache(): memcached_create() failed");
\r
486 log.debug("Memcache created");
\r
488 unsigned int hash = MEMCACHED_HASH_CRC;
\r
489 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_HASH, hash);
\r
490 log.debug("CRC hash set");
\r
492 int32_t timeout = 1000000;
\r
493 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SND_TIMEOUT, timeout);
\r
494 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, timeout);
\r
496 int32_t poll_timeout = 1000;
\r
497 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_POLL_TIMEOUT, poll_timeout);
\r
499 int32_t fail_limit = 5;
\r
500 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, fail_limit);
\r
502 int32_t retry_timeout = 30;
\r
503 memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, retry_timeout);
\r
505 memcached_server_st *servers;
\r
506 servers = memcached_servers_parse((char *)m_memcacheHosts.c_str());
\r
507 log.debug("Got %u hosts.", memcached_server_list_count(servers));
\r
508 if (memcached_server_push(memc, servers) != MEMCACHED_SUCCESS) {
\r
509 throw IOException("MemcacheBase::Memcache(): memcached_server_push() failed");
\r
511 memcached_server_list_free(servers);
\r
513 log.debug("Memcache object initialized");
\r
516 MemcacheBase::~MemcacheBase() {
\r
517 memcached_free(memc);
\r
519 log.debug("Base object destroyed");
\r
522 MemcacheStorageService::MemcacheStorageService(const DOMElement* e)
\r
523 : MemcacheBase(e), m_log(Category::getInstance("XMLTooling.MemcacheStorageService")), m_buildMap(false) {
\r
525 const XMLCh* tag=e ? e->getAttributeNS(NULL,buildMap) : NULL;
\r
526 if (tag && *tag && XMLString::parseInt(tag) != 0) {
\r
528 m_log.debug("Cache built with buildMap ON");
\r
533 MemcacheStorageService::~MemcacheStorageService() {
\r
538 bool MemcacheStorageService::createString(const char* context, const char* key, const char* value, time_t expiration) {
\r
540 log.debug("createString ctx: %s - key: %s", context, key);
\r
542 string final_key = string(context) + ":" + string(key);
\r
544 mc_record rec(value, expiration);
\r
545 string final_value;
\r
546 serialize(rec, final_value);
\r
548 bool result = addMemcache(final_key.c_str(), final_value, expiration, 1); // the flag will be the version
\r
550 if (result && m_buildMap) {
\r
551 log.debug("Got result, updating map");
\r
553 string map_name = context;
\r
554 // we need to update the context map
\r
555 if (! addLock(map_name)) {
\r
556 log.error("Unable to get lock for context %s!", context);
\r
557 deleteMemcache(final_key.c_str(), 0);
\r
563 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
565 list<string> contents;
\r
567 log.debug("Match found. Parsing...");
\r
569 deserialize(ser_arr, contents);
\r
571 log.debug("Iterating retrieved session map...");
\r
572 list<string>::iterator iter;
\r
573 for(iter = contents.begin();
\r
574 iter != contents.end();
\r
576 log.debug("value = " + *iter);
\r
580 log.debug("New context: %s", map_name.c_str());
\r
584 contents.push_back(key);
\r
585 serialize(contents, ser_arr);
\r
586 setMemcache(map_name.c_str(), ser_arr, expiration, 0);
\r
588 deleteLock(map_name);
\r
595 int MemcacheStorageService::readString(const char* context, const char* key, string* pvalue, time_t* pexpiration, int version) {
\r
597 log.debug("readString ctx: %s - key: %s", context, key);
\r
599 string final_key = string(context) + ":" + string(key);
\r
600 uint32_t rec_version;
\r
604 log.debug("Checking context");
\r
606 string map_name = context;
\r
609 bool ctx_found = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
616 bool found = getMemcache(final_key.c_str(), value, &rec_version);
\r
621 if (version && rec_version <= (uint32_t)version) {
\r
625 if (pexpiration || pvalue) {
\r
627 deserialize(value, rec);
\r
630 *pexpiration = rec.expiration;
\r
634 *pvalue = rec.value;
\r
638 return rec_version;
\r
642 int MemcacheStorageService::updateString(const char* context, const char* key, const char* value, time_t expiration, int version) {
\r
644 log.debug("updateString ctx: %s - key: %s", context, key);
\r
646 time_t final_exp = expiration;
\r
647 time_t *want_expiration = NULL;
\r
649 want_expiration = &final_exp;
\r
652 int read_res = readString(context, key, NULL, want_expiration, version);
\r
659 if (version && version != read_res) {
\r
660 // version incorrect
\r
664 // Proceding with update
\r
665 string final_key = string(context) + ":" + string(key);
\r
666 mc_record rec(value, final_exp);
\r
667 string final_value;
\r
668 serialize(rec, final_value);
\r
670 replaceMemcache(final_key.c_str(), final_value, final_exp, ++version);
\r
675 bool MemcacheStorageService::deleteString(const char* context, const char* key) {
\r
677 log.debug("deleteString ctx: %s - key: %s", context, key);
\r
679 string final_key = string(context) + ":" + string(key);
\r
681 // Not updating context map, if there is one. There is no need.
\r
683 return deleteMemcache(final_key.c_str(), 0);
\r
687 void MemcacheStorageService::updateContext(const char* context, time_t expiration) {
\r
689 log.debug("updateContext ctx: %s", context);
\r
692 log.error("updateContext invoked on a Storage with no context map built!");
\r
696 string map_name = context;
\r
699 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
701 list<string> contents;
\r
703 log.debug("Match found. Parsing...");
\r
705 deserialize(ser_arr, contents);
\r
707 log.debug("Iterating retrieved session map...");
\r
708 list<string>::iterator iter;
\r
709 for(iter = contents.begin();
\r
710 iter != contents.end();
\r
713 // Update expiration times
\r
715 int read_res = readString(context, iter->c_str(), &value, NULL, 0);
\r
722 updateString(context, iter->c_str(), value.c_str(), expiration, read_res);
\r
724 replaceMemcache(map_name.c_str(), ser_arr, expiration, flags);
\r
729 void MemcacheStorageService::deleteContext(const char* context) {
\r
731 log.debug("deleteContext ctx: %s", context);
\r
734 log.error("deleteContext invoked on a Storage with no context map built!");
\r
738 string map_name = context;
\r
741 bool result = getMemcache(map_name.c_str(), ser_arr, &flags);
\r
743 list<string> contents;
\r
745 log.debug("Match found. Parsing...");
\r
747 deserialize(ser_arr, contents);
\r
749 log.debug("Iterating retrieved session map...");
\r
750 list<string>::iterator iter;
\r
751 for(iter = contents.begin();
\r
752 iter != contents.end();
\r
754 string final_key = map_name + *iter;
\r
755 deleteMemcache(final_key.c_str(), 0);
\r
758 deleteMemcache(map_name.c_str(), 0);
\r
763 extern "C" int MCEXT_EXPORTS xmltooling_extension_init(void*) {
\r
764 // Register this SS type
\r
765 XMLToolingConfig::getConfig().StorageServiceManager.registerFactory("MEMCACHE", MemcacheStorageServiceFactory);
\r
769 extern "C" void MCEXT_EXPORTS xmltooling_extension_term() {
\r
770 XMLToolingConfig::getConfig().StorageServiceManager.deregisterFactory("MEMCACHE");
\r