kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/cxx/common/indexing/MemcachedHashCache.cc (about) 1 /* 2 * Copyright 2019 The Kythe Authors. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "kythe/cxx/common/indexing/MemcachedHashCache.h" 18 19 #include <libmemcached-1.0/memcached.h> 20 21 #include <iostream> 22 #include <string> 23 24 namespace kythe { 25 26 bool MemcachedHashCache::OpenMemcache(const std::string& spec) { 27 if (cache_) { 28 memcached_free(cache_); 29 cache_ = nullptr; 30 } 31 std::string spec_amend = spec; 32 spec_amend.append(" --BINARY-PROTOCOL"); 33 cache_ = memcached(spec_amend.c_str(), spec_amend.size()); 34 if (cache_ != nullptr) { 35 memcached_return_t remote_version = memcached_version(cache_); 36 return memcached_success(remote_version); 37 } 38 return false; 39 } 40 41 MemcachedHashCache::~MemcachedHashCache() { 42 if (cache_) { 43 memcached_free(cache_); 44 cache_ = nullptr; 45 } 46 } 47 48 void MemcachedHashCache::RegisterHash(const Hash& hash) { 49 if (!cache_) { 50 return; 51 } 52 char value = 1; 53 memcached_return_t add_result = 54 memcached_add(cache_, reinterpret_cast<const char*>(hash), kHashSize, 55 &value, sizeof(value), 0, 0); 56 if (!memcached_success(add_result) && add_result != MEMCACHED_DATA_EXISTS) { 57 std::cerr << "memcached add failed: " 58 << memcached_strerror(cache_, add_result) << "\n"; 59 } 60 } 61 62 bool MemcachedHashCache::SawHash(const Hash& hash) { 63 if (!cache_) { 64 return false; 65 } 66 memcached_return_t ex_result = 67 memcached_exist(cache_, reinterpret_cast<const char*>(hash), kHashSize); 68 if (ex_result == MEMCACHED_SUCCESS) { 69 return true; 70 } else if (ex_result != MEMCACHED_NOTFOUND) { 71 std::cerr << "memcached exist failed: " 72 << memcached_strerror(cache_, ex_result) << "\n"; 73 } 74 return false; 75 } 76 77 } // namespace kythe