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("", 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("", 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));
260 flags= memcached_result_flags(result);
261 cas_value= memcached_result_cas(result);
263 memcached_result_free(result);
268 memcached_return_t fetch(std::string &key,
269 std::vector<char> &ret_val)
272 uint64_t cas_value= 0;
274 return fetch(key, ret_val, flags, cas_value);
278 * Fetches an individual value from the server.
280 * @param[in] key key of object whose value to get
281 * @param[out] ret_val object that is retrieved is stored in
283 * @return true on success; false otherwise
285 bool get(const std::string &key, std::vector<char> &ret_val)
288 memcached_return_t rc;
289 size_t value_length= 0;
291 char *value= memcached_get(memc, key.c_str(), key.length(),
292 &value_length, &flags, &rc);
293 if (value != NULL && ret_val.empty())
295 ret_val.reserve(value_length);
296 ret_val.assign(value, value +value_length);
305 * Fetches an individual from a server which is specified by
306 * the master_key parameter that is used for determining which
307 * server an object was stored in if key partitioning was
310 * @param[in] master_key key that specifies server object is stored on
311 * @param[in] key key of object whose value to get
312 * @param[out] ret_val object that is retrieved is stored in
314 * @return true on success; false otherwise
316 bool getByKey(const std::string &master_key,
317 const std::string &key,
318 std::vector<char> &ret_val)
321 memcached_return_t rc;
322 size_t value_length= 0;
324 char *value= memcached_get_by_key(memc,
325 master_key.c_str(), master_key.length(),
326 key.c_str(), key.length(),
327 &value_length, &flags, &rc);
330 ret_val.reserve(value_length);
331 ret_val.assign(value, value +value_length);
339 * Selects multiple keys at once. This method always
340 * works asynchronously.
342 * @param[in] keys vector of keys to select
343 * @return true if all keys are found
345 bool mget(const std::vector<std::string>& keys)
347 std::vector<const char *> real_keys;
348 std::vector<size_t> key_len;
350 * Construct an array which will contain the length
351 * of each of the strings in the input vector. Also, to
352 * interface with the memcached C API, we need to convert
353 * the vector of std::string's to a vector of char *.
355 real_keys.reserve(keys.size());
356 key_len.reserve(keys.size());
358 std::vector<std::string>::const_iterator it= keys.begin();
360 while (it != keys.end())
362 real_keys.push_back(const_cast<char *>((*it).c_str()));
363 key_len.push_back((*it).length());
368 * If the std::vector of keys is empty then we cannot
369 * call memcached_mget as we will get undefined behavior.
371 if (not real_keys.empty())
373 return memcached_success(memcached_mget(memc, &real_keys[0], &key_len[0], real_keys.size()));
380 * Writes an object to the server. If the object already exists, it will
381 * overwrite the existing object. This method always returns true
382 * when using non-blocking mode unless a network error occurs.
384 * @param[in] key key of object to write to server
385 * @param[in] value value of object to write to server
386 * @param[in] expiration time to keep the object stored in the server for
387 * @param[in] flags flags to store with the object
388 * @return true on succcess; false otherwise
390 bool set(const std::string &key,
391 const std::vector<char> &value,
395 memcached_return_t rc= memcached_set(memc,
396 key.c_str(), key.length(),
397 &value[0], value.size(),
399 return memcached_success(rc);
403 * Writes an object to a server specified by the master_key parameter.
404 * If the object already exists, it will overwrite the existing object.
406 * @param[in] master_key key that specifies server to write to
407 * @param[in] key key of object to write to server
408 * @param[in] value value of object to write to server
409 * @param[in] expiration time to keep the object stored in the server for
410 * @param[in] flags flags to store with the object
411 * @return true on succcess; false otherwise
413 bool setByKey(const std::string& master_key,
414 const std::string& key,
415 const std::vector<char> &value,
419 return memcached_success(memcached_set_by_key(memc, master_key.c_str(),
421 key.c_str(), key.length(),
422 &value[0], value.size(),
428 * Writes a list of objects to the server. Objects are specified by
429 * 2 vectors - 1 vector of keys and 1 vector of values.
431 * @param[in] keys vector of keys of objects to write to server
432 * @param[in] values vector of values of objects to write to server
433 * @param[in] expiration time to keep the objects stored in server for
434 * @param[in] flags flags to store with the objects
435 * @return true on success; false otherwise
437 bool setAll(const std::vector<std::string>& keys,
438 const std::vector< std::vector<char> *>& values,
443 std::vector<std::string>::const_iterator key_it= keys.begin();
444 std::vector< std::vector<char> *>::const_iterator val_it= values.begin();
445 while (key_it != keys.end())
447 retval= set((*key_it), *(*val_it), expiration, flags);
459 * Writes a list of objects to the server. Objects are specified by
460 * a map of keys to values.
462 * @param[in] key_value_map map of keys and values to store in server
463 * @param[in] expiration time to keep the objects stored in server for
464 * @param[in] flags flags to store with the objects
465 * @return true on success; false otherwise
467 bool setAll(const std::map<const std::string, std::vector<char> >& key_value_map,
472 std::map<const std::string, std::vector<char> >::const_iterator it= key_value_map.begin();
474 while (it != key_value_map.end())
476 retval= set(it->first, it->second, expiration, flags);
479 // We should tell the user what the key that failed was
489 * Increment the value of the object associated with the specified
490 * key by the offset given. The resulting value is saved in the value
493 * @param[in] key key of object in server whose value to increment
494 * @param[in] offset amount to increment object's value by
495 * @param[out] value store the result of the increment here
496 * @return true on success; false otherwise
498 bool increment(const std::string& key, uint32_t offset, uint64_t *value)
500 return memcached_success(memcached_increment(memc, key.c_str(), key.length(), offset, value));
504 * Decrement 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 decrement
509 * @param[in] offset amount to increment object's value by
510 * @param[out] value store the result of the decrement here
511 * @return true on success; false otherwise
513 bool decrement(const std::string& key, uint32_t offset, uint64_t *value)
515 return memcached_success(memcached_decrement(memc, key.c_str(),
522 * Add an object with the specified key and value to the server. This
523 * function returns false if the object already exists on the server.
525 * @param[in] key key of object to add
526 * @param[in] value of object to add
527 * @return true on success; false otherwise
529 bool add(const std::string& key, const std::vector<char>& value)
531 return memcached_success(memcached_add(memc, key.c_str(), key.length(),
532 &value[0], value.size(), 0, 0));
536 * Add an object with the specified key and value to the server. This
537 * function returns false if the object already exists on the server. The
538 * server to add the object to is specified by the master_key parameter.
540 * @param[in[ master_key key of server to add object to
541 * @param[in] key key of object to add
542 * @param[in] value of object to add
543 * @return true on success; false otherwise
545 bool addByKey(const std::string& master_key,
546 const std::string& key,
547 const std::vector<char>& value)
549 return memcached_success(memcached_add_by_key(memc,
560 * Replaces an object on the server. This method only succeeds
561 * if the object is already present on the server.
563 * @param[in] key key of object to replace
564 * @param[in[ value value to replace object with
565 * @return true on success; false otherwise
567 bool replace(const std::string& key, const std::vector<char>& value)
569 return memcached_success(memcached_replace(memc, key.c_str(), key.length(),
570 &value[0], value.size(),
575 * Replaces an object on the server. This method only succeeds
576 * if the object is already present on the server. The server
577 * to replace the object on is specified by the master_key param.
579 * @param[in] master_key key of server to replace object on
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 replaceByKey(const std::string& master_key,
585 const std::string& key,
586 const std::vector<char>& value)
588 return memcached_success(memcached_replace_by_key(memc,
599 * Places a segment of data before the last piece of data stored.
601 * @param[in] key key of object whose value we will prepend data to
602 * @param[in] value data to prepend to object's value
603 * @return true on success; false otherwise
605 bool prepend(const std::string& key, const std::vector<char>& value)
607 return memcached_success(memcached_prepend(memc, key.c_str(), key.length(),
608 &value[0], value.size(), 0, 0));
612 * Places a segment of data before the last piece of data stored. The
613 * server on which the object where we will be prepending data is stored
614 * on is specified by the master_key parameter.
616 * @param[in] master_key key of server where object is stored
617 * @param[in] key key of object whose value we will prepend data to
618 * @param[in] value data to prepend to object's value
619 * @return true on success; false otherwise
621 bool prependByKey(const std::string& master_key,
622 const std::string& key,
623 const std::vector<char>& value)
625 return memcached_success(memcached_prepend_by_key(memc,
637 * Places a segment of data at the end of the last piece of data stored.
639 * @param[in] key key of object whose value we will append data to
640 * @param[in] value data to append to object's value
641 * @return true on success; false otherwise
643 bool append(const std::string& key, const std::vector<char>& value)
645 return memcached_success(memcached_append(memc,
654 * Places a segment of data at the end of the last piece of data stored. The
655 * server on which the object where we will be appending data is stored
656 * on is specified by the master_key parameter.
658 * @param[in] master_key key of server where object is stored
659 * @param[in] key key of object whose value we will append data to
660 * @param[in] value data to append to object's value
661 * @return true on success; false otherwise
663 bool appendByKey(const std::string& master_key,
664 const std::string& key,
665 const std::vector<char> &value)
667 return memcached_success(memcached_append_by_key(memc,
678 * Overwrite data in the server as long as the cas_arg value
679 * is still the same in the server.
681 * @param[in] key key of object in server
682 * @param[in] value value to store for object in server
683 * @param[in] cas_arg "cas" value
685 bool cas(const std::string& key,
686 const std::vector<char>& value,
689 return memcached_success(memcached_cas(memc, key.c_str(), key.length(),
690 &value[0], value.size(),
695 * Overwrite data in the server as long as the cas_arg value
696 * is still the same in the server. The server to use is
697 * specified by the master_key parameter.
699 * @param[in] master_key specifies server to operate on
700 * @param[in] key key of object in server
701 * @param[in] value value to store for object in server
702 * @param[in] cas_arg "cas" value
704 bool casByKey(const std::string& master_key,
705 const std::string& key,
706 const std::vector<char> &value,
709 return memcached_success(memcached_cas_by_key(memc,
720 * Delete an object from the server specified by the key given.
722 * @param[in] key key of object to delete
723 * @return true on success; false otherwise
725 bool remove(const std::string& key)
727 return memcached_success(memcached_delete(memc, key.c_str(), key.length(), 0));
731 * Delete an object from the server specified by the key given.
733 * @param[in] key key of object to delete
734 * @param[in] expiration time to delete the object after
735 * @return true on success; false otherwise
737 bool remove(const std::string& key, time_t expiration)
739 return memcached_success(memcached_delete(memc,
746 * Delete an object from the server specified by the key given.
748 * @param[in] master_key specifies server to remove object from
749 * @param[in] key key of object to delete
750 * @return true on success; false otherwise
752 bool removeByKey(const std::string& master_key,
753 const std::string& key)
755 return memcached_success(memcached_delete_by_key(memc,
764 * Delete an object from the server specified by the key given.
766 * @param[in] master_key specifies server to remove object from
767 * @param[in] key key of object to delete
768 * @param[in] expiration time to delete the object after
769 * @return true on success; false otherwise
771 bool removeByKey(const std::string& master_key,
772 const std::string& key,
775 return memcached_success(memcached_delete_by_key(memc,
784 * Wipe the contents of memcached servers.
786 * @param[in] expiration time to wait until wiping contents of
788 * @return true on success; false otherwise
790 bool flush(time_t expiration= 0)
792 return memcached_success(memcached_flush(memc, expiration));
796 * Get the library version string.
797 * @return std::string containing a copy of the library version string.
799 const std::string libVersion() const
801 const char *ver= memcached_lib_version();
802 const std::string version(ver);
807 * Retrieve memcached statistics. Populate a std::map with the retrieved
808 * stats. Each server will map to another std::map of the key:value stats.
810 * @param[out] stats_map a std::map to be populated with the memcached
812 * @return true on success; false otherwise
814 bool getStats(std::map< std::string, std::map<std::string, std::string> >& stats_map)
816 memcached_return_t rc;
817 memcached_stat_st *stats= memcached_stat(memc, NULL, &rc);
819 if (rc != MEMCACHED_SUCCESS &&
820 rc != MEMCACHED_SOME_ERRORS)
825 uint32_t server_count= memcached_server_count(memc);
828 * For each memcached server, construct a std::map for its stats and add
829 * it to the std::map of overall stats.
831 for (uint32_t x= 0; x < server_count; x++)
833 memcached_server_instance_st instance= memcached_server_instance_by_position(memc, x);
834 std::ostringstream strstm;
835 std::string server_name(memcached_server_name(instance));
836 server_name.append(":");
837 strstm << memcached_server_port(instance);
838 server_name.append(strstm.str());
840 std::map<std::string, std::string> server_stats;
841 char **list= memcached_stat_get_keys(memc, &stats[x], &rc);
842 for (char** ptr= list; *ptr; ptr++)
844 char *value= memcached_stat_get_value(memc, &stats[x], *ptr, &rc);
845 server_stats[*ptr]= value;
849 stats_map[server_name]= server_stats;
853 memcached_stat_free(memc, stats);