1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
5 * Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * * Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following disclaimer
16 * in the documentation and/or other materials provided with the
19 * * The names of its contributors may not be used to endorse or
20 * promote products derived from this software without specific prior
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * Summary: C++ interface for memcached server
40 * Copy: See Copyright for the status of this software.
42 * Authors: Padraig O'Sullivan <osullivan.padraig@gmail.com>
43 * Patrick Galbraith <patg@patg.net>
48 * @brief Libmemcached C++ interface
53 #include <libmemcached-1.0/memcached.h>
55 #include <libmemcached/exception.hpp>
69 * This is the core memcached library (if later, other objects
70 * are needed, they will be created from this class).
78 memc_= memcached(NULL, 0);
81 Memcache(const std::string &config)
83 memc_= memcached(config.c_str(), config.size());
86 Memcache(const std::string &hostname, in_port_t port)
88 memc_= memcached(NULL, 0);
91 memcached_server_add(memc_, hostname.c_str(), port);
95 Memcache(memcached_st *clone)
97 memc_= memcached_clone(NULL, clone);
100 Memcache(const Memcache &rhs)
102 memc_= memcached_clone(NULL, rhs.getImpl());
105 Memcache &operator=(const Memcache &rhs)
109 memcached_free(memc_);
110 memc_= memcached_clone(NULL, rhs.getImpl());
118 memcached_free(memc_);
122 * Get the internal memcached_st *
124 const memcached_st *getImpl() const
130 * Return an error string for the given return structure.
132 * @param[in] rc a memcached_return_t structure
133 * @return error string corresponding to given return code in the library.
135 const std::string getError(memcached_return_t rc) const
137 /* first parameter to strerror is unused */
138 return memcached_strerror(NULL, rc);
141 bool error(std::string& error_message) const
143 if (memcached_failed(memcached_last_error(memc_)))
145 error_message+= memcached_last_error_message(memc_);
154 if (memcached_failed(memcached_last_error(memc_)))
162 bool error(memcached_return_t& arg) const
164 arg= memcached_last_error(memc_);
165 return memcached_failed(arg);
168 bool setBehavior(memcached_behavior_t flag, uint64_t data)
170 return (memcached_success(memcached_behavior_set(memc_, flag, data)));
173 uint64_t getBehavior(memcached_behavior_t flag)
175 return memcached_behavior_get(memc_, flag);
179 * Configure the memcache object
181 * @param[in] in_config configuration
182 * @return true on success; false otherwise
184 bool configure(const std::string &configuration)
186 memcached_st *new_memc= memcached(configuration.c_str(), configuration.size());
190 memcached_free(memc_);
200 * Add a server to the list of memcached servers to use.
202 * @param[in] server_name name of the server to add
203 * @param[in] port port number of server to add
204 * @return true on success; false otherwise
206 bool addServer(const std::string &server_name, in_port_t port)
208 return memcached_success(memcached_server_add(memc_, server_name.c_str(), port));
212 * Remove a server from the list of memcached servers to use.
214 * @param[in] server_name name of the server to remove
215 * @param[in] port port number of server to remove
216 * @return true on success; false otherwise
218 bool removeServer(const std::string &server_name, in_port_t port)
221 std::ostringstream strstm;
223 tmp_str.append(server_name);
226 tmp_str.append(strstm.str());
228 //memcached_return_t rc= memcached_server_remove(server);
234 * Fetches an individual value from the server. mget() must always
235 * be called before using this method.
237 * @param[in] key key of object to fetch
238 * @param[out] ret_val store returned object in this vector
239 * @return a memcached return structure
241 memcached_return_t fetch(std::string &key,
242 std::vector<char> &ret_val,
246 memcached_return_t rc;
248 memcached_result_st *result;
249 if ((result= memcached_fetch_result(memc_, NULL, &rc)))
252 key.assign(memcached_result_key_value(result), memcached_result_key_length(result));
254 // Actual value, null terminated
255 ret_val.reserve(memcached_result_length(result) +1);
256 ret_val.assign(memcached_result_value(result),
257 memcached_result_value(result) +memcached_result_length(result) +1);
258 ret_val.resize(memcached_result_length(result));
261 flags= memcached_result_flags(result);
262 cas_value= memcached_result_cas(result);
264 memcached_result_free(result);
269 memcached_return_t fetch(std::string &key,
270 std::vector<char> &ret_val)
273 uint64_t cas_value= 0;
275 return fetch(key, ret_val, flags, cas_value);
279 * Fetches an individual value from the server.
281 * @param[in] key key of object whose value to get
282 * @param[out] ret_val object that is retrieved is stored in
284 * @return true on success; false otherwise
286 bool get(const std::string &key, std::vector<char> &ret_val)
289 memcached_return_t rc;
290 size_t value_length= 0;
292 char *value= memcached_get(memc_, key.c_str(), key.length(),
293 &value_length, &flags, &rc);
294 if (value != NULL && ret_val.empty())
296 ret_val.reserve(value_length +1); // Always provide null
297 ret_val.assign(value, value +value_length +1);
298 ret_val.resize(value_length);
308 * Fetches an individual from a server which is specified by
309 * the master_key parameter that is used for determining which
310 * server an object was stored in if key partitioning was
313 * @param[in] master_key key that specifies server object is stored on
314 * @param[in] key key of object whose value to get
315 * @param[out] ret_val object that is retrieved is stored in
317 * @return true on success; false otherwise
319 bool getByKey(const std::string &master_key,
320 const std::string &key,
321 std::vector<char> &ret_val)
324 memcached_return_t rc;
325 size_t value_length= 0;
327 char *value= memcached_get_by_key(memc_,
328 master_key.c_str(), master_key.length(),
329 key.c_str(), key.length(),
330 &value_length, &flags, &rc);
333 ret_val.reserve(value_length +1); // Always provide null
334 ret_val.assign(value, value +value_length +1);
335 ret_val.resize(value_length);
344 * Selects multiple keys at once. This method always
345 * works asynchronously.
347 * @param[in] keys vector of keys to select
348 * @return true if all keys are found
350 bool mget(const std::vector<std::string>& keys)
352 std::vector<const char *> real_keys;
353 std::vector<size_t> key_len;
355 * Construct an array which will contain the length
356 * of each of the strings in the input vector. Also, to
357 * interface with the memcached C API, we need to convert
358 * the vector of std::string's to a vector of char *.
360 real_keys.reserve(keys.size());
361 key_len.reserve(keys.size());
363 std::vector<std::string>::const_iterator it= keys.begin();
365 while (it != keys.end())
367 real_keys.push_back(const_cast<char *>((*it).c_str()));
368 key_len.push_back((*it).length());
373 * If the std::vector of keys is empty then we cannot
374 * call memcached_mget as we will get undefined behavior.
376 if (not real_keys.empty())
378 return memcached_success(memcached_mget(memc_, &real_keys[0], &key_len[0], real_keys.size()));
385 * Writes an object to the server. If the object already exists, it will
386 * overwrite the existing object. This method always returns true
387 * when using non-blocking mode unless a network error occurs.
389 * @param[in] key key of object to write to server
390 * @param[in] value value of object to write to server
391 * @param[in] expiration time to keep the object stored in the server for
392 * @param[in] flags flags to store with the object
393 * @return true on succcess; false otherwise
395 bool set(const std::string &key,
396 const std::vector<char> &value,
400 memcached_return_t rc= memcached_set(memc_,
401 key.c_str(), key.length(),
402 &value[0], value.size(),
404 return memcached_success(rc);
407 bool set(const std::string &key,
408 const char* value, const size_t value_length,
412 memcached_return_t rc= memcached_set(memc_,
413 key.c_str(), key.length(),
416 return memcached_success(rc);
420 * Writes an object to a server specified by the master_key parameter.
421 * If the object already exists, it will overwrite the existing object.
423 * @param[in] master_key key that specifies server to write to
424 * @param[in] key key of object to write to server
425 * @param[in] value value of object to write to server
426 * @param[in] expiration time to keep the object stored in the server for
427 * @param[in] flags flags to store with the object
428 * @return true on succcess; false otherwise
430 bool setByKey(const std::string& master_key,
431 const std::string& key,
432 const std::vector<char> &value,
436 return memcached_success(memcached_set_by_key(memc_, master_key.c_str(),
438 key.c_str(), key.length(),
439 &value[0], value.size(),
445 * Writes a list of objects to the server. Objects are specified by
446 * 2 vectors - 1 vector of keys and 1 vector of values.
448 * @param[in] keys vector of keys of objects to write to server
449 * @param[in] values vector of values of objects to write to server
450 * @param[in] expiration time to keep the objects stored in server for
451 * @param[in] flags flags to store with the objects
452 * @return true on success; false otherwise
454 bool setAll(const std::vector<std::string>& keys,
455 const std::vector< std::vector<char> *>& values,
460 std::vector<std::string>::const_iterator key_it= keys.begin();
461 std::vector< std::vector<char> *>::const_iterator val_it= values.begin();
462 while (key_it != keys.end())
464 retval= set((*key_it), *(*val_it), expiration, flags);
476 * Writes a list of objects to the server. Objects are specified by
477 * a map of keys to values.
479 * @param[in] key_value_map map of keys and values to store in server
480 * @param[in] expiration time to keep the objects stored in server for
481 * @param[in] flags flags to store with the objects
482 * @return true on success; false otherwise
484 bool setAll(const std::map<const std::string, std::vector<char> >& key_value_map,
489 std::map<const std::string, std::vector<char> >::const_iterator it= key_value_map.begin();
491 while (it != key_value_map.end())
493 retval= set(it->first, it->second, expiration, flags);
496 // We should tell the user what the key that failed was
506 * Increment the value of the object associated with the specified
507 * key by the offset given. The resulting value is saved in the value
510 * @param[in] key key of object in server whose value to increment
511 * @param[in] offset amount to increment object's value by
512 * @param[out] value store the result of the increment here
513 * @return true on success; false otherwise
515 bool increment(const std::string& key, uint32_t offset, uint64_t *value)
517 return memcached_success(memcached_increment(memc_, key.c_str(), key.length(), offset, value));
521 * Decrement the value of the object associated with the specified
522 * key by the offset given. The resulting value is saved in the value
525 * @param[in] key key of object in server whose value to decrement
526 * @param[in] offset amount to increment object's value by
527 * @param[out] value store the result of the decrement here
528 * @return true on success; false otherwise
530 bool decrement(const std::string& key, uint32_t offset, uint64_t *value)
532 return memcached_success(memcached_decrement(memc_, key.c_str(),
539 * Add an object with the specified key and value to the server. This
540 * function returns false if the object already exists on the server.
542 * @param[in] key key of object to add
543 * @param[in] value of object to add
544 * @return true on success; false otherwise
546 bool add(const std::string& key, const std::vector<char>& value)
548 return memcached_success(memcached_add(memc_, key.c_str(), key.length(),
549 &value[0], value.size(), 0, 0));
553 * Add an object with the specified key and value to the server. This
554 * function returns false if the object already exists on the server. The
555 * server to add the object to is specified by the master_key parameter.
557 * @param[in[ master_key key of server to add object to
558 * @param[in] key key of object to add
559 * @param[in] value of object to add
560 * @return true on success; false otherwise
562 bool addByKey(const std::string& master_key,
563 const std::string& key,
564 const std::vector<char>& value)
566 return memcached_success(memcached_add_by_key(memc_,
577 * Replaces an object on the server. This method only succeeds
578 * if the object is already present on the server.
580 * @param[in] key key of object to replace
581 * @param[in[ value value to replace object with
582 * @return true on success; false otherwise
584 bool replace(const std::string& key, const std::vector<char>& value)
586 return memcached_success(memcached_replace(memc_, key.c_str(), key.length(),
587 &value[0], value.size(),
592 * Replaces an object on the server. This method only succeeds
593 * if the object is already present on the server. The server
594 * to replace the object on is specified by the master_key param.
596 * @param[in] master_key key of server to replace object on
597 * @param[in] key key of object to replace
598 * @param[in[ value value to replace object with
599 * @return true on success; false otherwise
601 bool replaceByKey(const std::string& master_key,
602 const std::string& key,
603 const std::vector<char>& value)
605 return memcached_success(memcached_replace_by_key(memc_,
616 * Places a segment of data before the last piece of data stored.
618 * @param[in] key key of object whose value we will prepend data to
619 * @param[in] value data to prepend to object's value
620 * @return true on success; false otherwise
622 bool prepend(const std::string& key, const std::vector<char>& value)
624 return memcached_success(memcached_prepend(memc_, key.c_str(), key.length(),
625 &value[0], value.size(), 0, 0));
629 * Places a segment of data before the last piece of data stored. The
630 * server on which the object where we will be prepending data is stored
631 * on is specified by the master_key parameter.
633 * @param[in] master_key key of server where object is stored
634 * @param[in] key key of object whose value we will prepend data to
635 * @param[in] value data to prepend to object's value
636 * @return true on success; false otherwise
638 bool prependByKey(const std::string& master_key,
639 const std::string& key,
640 const std::vector<char>& value)
642 return memcached_success(memcached_prepend_by_key(memc_,
654 * Places a segment of data at the end of the last piece of data stored.
656 * @param[in] key key of object whose value we will append data to
657 * @param[in] value data to append to object's value
658 * @return true on success; false otherwise
660 bool append(const std::string& key, const std::vector<char>& value)
662 return memcached_success(memcached_append(memc_,
671 * Places a segment of data at the end of the last piece of data stored. The
672 * server on which the object where we will be appending data is stored
673 * on is specified by the master_key parameter.
675 * @param[in] master_key key of server where object is stored
676 * @param[in] key key of object whose value we will append data to
677 * @param[in] value data to append to object's value
678 * @return true on success; false otherwise
680 bool appendByKey(const std::string& master_key,
681 const std::string& key,
682 const std::vector<char> &value)
684 return memcached_success(memcached_append_by_key(memc_,
695 * Overwrite data in the server as long as the cas_arg value
696 * is still the same in the server.
698 * @param[in] key key of object in server
699 * @param[in] value value to store for object in server
700 * @param[in] cas_arg "cas" value
702 bool cas(const std::string& key,
703 const std::vector<char>& value,
706 return memcached_success(memcached_cas(memc_, key.c_str(), key.length(),
707 &value[0], value.size(),
712 * Overwrite data in the server as long as the cas_arg value
713 * is still the same in the server. The server to use is
714 * specified by the master_key parameter.
716 * @param[in] master_key specifies server to operate on
717 * @param[in] key key of object in server
718 * @param[in] value value to store for object in server
719 * @param[in] cas_arg "cas" value
721 bool casByKey(const std::string& master_key,
722 const std::string& key,
723 const std::vector<char> &value,
726 return memcached_success(memcached_cas_by_key(memc_,
737 * Delete an object from the server specified by the key given.
739 * @param[in] key key of object to delete
740 * @return true on success; false otherwise
742 bool remove(const std::string& key)
744 return memcached_success(memcached_delete(memc_, key.c_str(), key.length(), 0));
748 * Delete an object from the server specified by the key given.
750 * @param[in] key key of object to delete
751 * @param[in] expiration time to delete the object after
752 * @return true on success; false otherwise
754 bool remove(const std::string& key, time_t expiration)
756 return memcached_success(memcached_delete(memc_,
763 * Delete an object from the server specified by the key given.
765 * @param[in] master_key specifies server to remove object from
766 * @param[in] key key of object to delete
767 * @return true on success; false otherwise
769 bool removeByKey(const std::string& master_key,
770 const std::string& key)
772 return memcached_success(memcached_delete_by_key(memc_,
781 * Delete an object from the server specified by the key given.
783 * @param[in] master_key specifies server to remove object from
784 * @param[in] key key of object to delete
785 * @param[in] expiration time to delete the object after
786 * @return true on success; false otherwise
788 bool removeByKey(const std::string& master_key,
789 const std::string& key,
792 return memcached_success(memcached_delete_by_key(memc_,
801 * Wipe the contents of memcached servers.
803 * @param[in] expiration time to wait until wiping contents of
805 * @return true on success; false otherwise
807 bool flush(time_t expiration= 0)
809 return memcached_success(memcached_flush(memc_, expiration));
813 * Get the library version string.
814 * @return std::string containing a copy of the library version string.
816 const std::string libVersion() const
818 const char *ver= memcached_lib_version();
819 const std::string version(ver);
824 * Retrieve memcached statistics. Populate a std::map with the retrieved
825 * stats. Each server will map to another std::map of the key:value stats.
827 * @param[out] stats_map a std::map to be populated with the memcached
829 * @return true on success; false otherwise
831 bool getStats(std::map< std::string, std::map<std::string, std::string> >& stats_map)
833 memcached_return_t rc;
834 memcached_stat_st *stats= memcached_stat(memc_, NULL, &rc);
836 if (rc != MEMCACHED_SUCCESS &&
837 rc != MEMCACHED_SOME_ERRORS)
842 uint32_t server_count= memcached_server_count(memc_);
845 * For each memcached server, construct a std::map for its stats and add
846 * it to the std::map of overall stats.
848 for (uint32_t x= 0; x < server_count; x++)
850 memcached_server_instance_st instance= memcached_server_instance_by_position(memc_, x);
851 std::ostringstream strstm;
852 std::string server_name(memcached_server_name(instance));
853 server_name.append(":");
854 strstm << memcached_server_port(instance);
855 server_name.append(strstm.str());
857 std::map<std::string, std::string> server_stats;
858 char **list= memcached_stat_get_keys(memc_, &stats[x], &rc);
859 for (char** ptr= list; *ptr; ptr++)
861 char *value= memcached_stat_get_value(memc_, &stats[x], *ptr, &rc);
862 server_stats[*ptr]= value;
866 stats_map[server_name]= server_stats;
870 memcached_stat_free(memc_, stats);