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.data(), 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,
488 std::map<const std::string, std::vector<char> >::const_iterator it= key_value_map.begin();
490 while (it != key_value_map.end())
492 if (!set(it->first, it->second, expiration, flags))
494 // We should tell the user what the key that failed was
504 * Increment the value of the object associated with the specified
505 * key by the offset given. The resulting value is saved in the value
508 * @param[in] key key of object in server whose value to increment
509 * @param[in] offset amount to increment object's value by
510 * @param[out] value store the result of the increment here
511 * @return true on success; false otherwise
513 bool increment(const std::string& key, uint32_t offset, uint64_t *value)
515 return memcached_success(memcached_increment(memc_, key.c_str(), key.length(), offset, value));
519 * Decrement the value of the object associated with the specified
520 * key by the offset given. The resulting value is saved in the value
523 * @param[in] key key of object in server whose value to decrement
524 * @param[in] offset amount to increment object's value by
525 * @param[out] value store the result of the decrement here
526 * @return true on success; false otherwise
528 bool decrement(const std::string& key, uint32_t offset, uint64_t *value)
530 return memcached_success(memcached_decrement(memc_, key.c_str(),
537 * Add an object with the specified key and value to the server. This
538 * function returns false if the object already exists on the server.
540 * @param[in] key key of object to add
541 * @param[in] value of object to add
542 * @return true on success; false otherwise
544 bool add(const std::string& key, const std::vector<char>& value)
546 return memcached_success(memcached_add(memc_, key.c_str(), key.length(),
547 &value[0], value.size(), 0, 0));
551 * Add an object with the specified key and value to the server. This
552 * function returns false if the object already exists on the server. The
553 * server to add the object to is specified by the master_key parameter.
555 * @param[in[ master_key key of server to add object to
556 * @param[in] key key of object to add
557 * @param[in] value of object to add
558 * @return true on success; false otherwise
560 bool addByKey(const std::string& master_key,
561 const std::string& key,
562 const std::vector<char>& value)
564 return memcached_success(memcached_add_by_key(memc_,
575 * Replaces an object on the server. This method only succeeds
576 * if the object is already present on the server.
578 * @param[in] key key of object to replace
579 * @param[in[ value value to replace object with
580 * @return true on success; false otherwise
582 bool replace(const std::string& key, const std::vector<char>& value)
584 return memcached_success(memcached_replace(memc_, key.c_str(), key.length(),
585 &value[0], value.size(),
590 * Replaces an object on the server. This method only succeeds
591 * if the object is already present on the server. The server
592 * to replace the object on is specified by the master_key param.
594 * @param[in] master_key key of server to replace object on
595 * @param[in] key key of object to replace
596 * @param[in[ value value to replace object with
597 * @return true on success; false otherwise
599 bool replaceByKey(const std::string& master_key,
600 const std::string& key,
601 const std::vector<char>& value)
603 return memcached_success(memcached_replace_by_key(memc_,
614 * Places a segment of data before the last piece of data stored.
616 * @param[in] key key of object whose value we will prepend data to
617 * @param[in] value data to prepend to object's value
618 * @return true on success; false otherwise
620 bool prepend(const std::string& key, const std::vector<char>& value)
622 return memcached_success(memcached_prepend(memc_, key.c_str(), key.length(),
623 &value[0], value.size(), 0, 0));
627 * Places a segment of data before the last piece of data stored. The
628 * server on which the object where we will be prepending data is stored
629 * on is specified by the master_key parameter.
631 * @param[in] master_key key of server where object is stored
632 * @param[in] key key of object whose value we will prepend data to
633 * @param[in] value data to prepend to object's value
634 * @return true on success; false otherwise
636 bool prependByKey(const std::string& master_key,
637 const std::string& key,
638 const std::vector<char>& value)
640 return memcached_success(memcached_prepend_by_key(memc_,
652 * Places a segment of data at the end of the last piece of data stored.
654 * @param[in] key key of object whose value we will append data to
655 * @param[in] value data to append to object's value
656 * @return true on success; false otherwise
658 bool append(const std::string& key, const std::vector<char>& value)
660 return memcached_success(memcached_append(memc_,
669 * Places a segment of data at the end of the last piece of data stored. The
670 * server on which the object where we will be appending data is stored
671 * on is specified by the master_key parameter.
673 * @param[in] master_key key of server where object is stored
674 * @param[in] key key of object whose value we will append data to
675 * @param[in] value data to append to object's value
676 * @return true on success; false otherwise
678 bool appendByKey(const std::string& master_key,
679 const std::string& key,
680 const std::vector<char> &value)
682 return memcached_success(memcached_append_by_key(memc_,
693 * Overwrite data in the server as long as the cas_arg value
694 * is still the same in the server.
696 * @param[in] key key of object in server
697 * @param[in] value value to store for object in server
698 * @param[in] cas_arg "cas" value
700 bool cas(const std::string& key,
701 const std::vector<char>& value,
704 return memcached_success(memcached_cas(memc_, key.c_str(), key.length(),
705 &value[0], value.size(),
710 * Overwrite data in the server as long as the cas_arg value
711 * is still the same in the server. The server to use is
712 * specified by the master_key parameter.
714 * @param[in] master_key specifies server to operate on
715 * @param[in] key key of object in server
716 * @param[in] value value to store for object in server
717 * @param[in] cas_arg "cas" value
719 bool casByKey(const std::string& master_key,
720 const std::string& key,
721 const std::vector<char> &value,
724 return memcached_success(memcached_cas_by_key(memc_,
735 * Delete an object from the server specified by the key given.
737 * @param[in] key key of object to delete
738 * @return true on success; false otherwise
740 bool remove(const std::string& key)
742 return memcached_success(memcached_delete(memc_, key.c_str(), key.length(), 0));
746 * Delete an object from the server specified by the key given.
748 * @param[in] key key of object to delete
749 * @param[in] expiration time to delete the object after
750 * @return true on success; false otherwise
752 bool remove(const std::string& key, time_t expiration)
754 return memcached_success(memcached_delete(memc_,
761 * Delete an object from the server specified by the key given.
763 * @param[in] master_key specifies server to remove object from
764 * @param[in] key key of object to delete
765 * @return true on success; false otherwise
767 bool removeByKey(const std::string& master_key,
768 const std::string& key)
770 return memcached_success(memcached_delete_by_key(memc_,
779 * Delete an object from the server specified by the key given.
781 * @param[in] master_key specifies server to remove object from
782 * @param[in] key key of object to delete
783 * @param[in] expiration time to delete the object after
784 * @return true on success; false otherwise
786 bool removeByKey(const std::string& master_key,
787 const std::string& key,
790 return memcached_success(memcached_delete_by_key(memc_,
799 * Wipe the contents of memcached servers.
801 * @param[in] expiration time to wait until wiping contents of
803 * @return true on success; false otherwise
805 bool flush(time_t expiration= 0)
807 return memcached_success(memcached_flush(memc_, expiration));
811 * Get the library version string.
812 * @return std::string containing a copy of the library version string.
814 const std::string libVersion() const
816 const char *ver= memcached_lib_version();
817 const std::string version(ver);
822 * Retrieve memcached statistics. Populate a std::map with the retrieved
823 * stats. Each server will map to another std::map of the key:value stats.
825 * @param[out] stats_map a std::map to be populated with the memcached
827 * @return true on success; false otherwise
829 bool getStats(std::map< std::string, std::map<std::string, std::string> >& stats_map)
831 memcached_return_t rc;
832 memcached_stat_st *stats= memcached_stat(memc_, NULL, &rc);
834 if (rc != MEMCACHED_SUCCESS &&
835 rc != MEMCACHED_SOME_ERRORS)
840 uint32_t server_count= memcached_server_count(memc_);
843 * For each memcached server, construct a std::map for its stats and add
844 * it to the std::map of overall stats.
846 for (uint32_t x= 0; x < server_count; x++)
848 const memcached_instance_st * instance= memcached_server_instance_by_position(memc_, x);
849 std::ostringstream strstm;
850 std::string server_name(memcached_server_name(instance));
851 server_name.append(":");
852 strstm << memcached_server_port(instance);
853 server_name.append(strstm.str());
855 std::map<std::string, std::string> server_stats;
856 char **list= memcached_stat_get_keys(memc_, &stats[x], &rc);
857 for (char** ptr= list; *ptr; ptr++)
859 char *value= memcached_stat_get_value(memc_, &stats[x], *ptr, &rc);
860 server_stats[*ptr]= value;
864 stats_map[server_name]= server_stats;
868 memcached_stat_free(memc_, stats);