repo
stringlengths
1
152
file
stringlengths
15
205
code
stringlengths
0
41.6M
file_length
int64
0
41.6M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
90 values
null
ceph-main/src/test/test_rgw_admin_log.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 eNovance SAS <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> #include <sys/wait.h> #include <unistd.h> #include <fstream> #include <map> #include <list> extern "C"{ #include <curl/curl.h> } #include "common/ceph_crypto.h" #include "include/str_list.h" #include "common/ceph_json.h" #include "common/code_environment.h" #include "common/ceph_argparse.h" #include "common/Finisher.h" #include "global/global_init.h" #include "rgw_common.h" #include "rgw_datalog.h" #include "rgw_mdlog.h" #include "rgw_bucket.h" #include "rgw_rados.h" #include "include/utime.h" #include "include/object.h" #include <gtest/gtest.h> using namespace std; #define CURL_VERBOSE 0 #define HTTP_RESPONSE_STR "RespCode" #define CEPH_CRYPTO_HMACSHA1_DIGESTSIZE 20 #define RGW_ADMIN_RESP_PATH "/tmp/.test_rgw_admin_resp" #define TEST_BUCKET_NAME "test_bucket" #define TEST_BUCKET_OBJECT "test_object" #define TEST_BUCKET_OBJECT_1 "test_object1" #define TEST_BUCKET_OBJECT_SIZE 1024 static string uid = "ceph"; static string display_name = "CEPH"; extern "C" int ceph_armor(char *dst, const char *dst_end, const char *src, const char *end); static void print_usage(char *exec){ cout << "Usage: " << exec << " <Options>\n"; cout << "Options:\n" "-g <gw-ip> - The ip address of the gateway\n" "-p <gw-port> - The port number of the gateway\n" "-c <ceph.conf> - Absolute path of ceph config file\n" "-rgw-admin <path/to/radosgw-admin> - radosgw-admin absolute path\n"; } namespace admin_log { class test_helper { private: string host; string port; string creds; string rgw_admin_path; string conf_path; CURL *curl_inst; map<string, string> response; list<string> extra_hdrs; string *resp_data; unsigned resp_code; public: test_helper() : resp_data(NULL){ curl_global_init(CURL_GLOBAL_ALL); } ~test_helper(){ curl_global_cleanup(); } int send_request(string method, string uri, size_t (*function)(void *,size_t,size_t,void *) = 0, void *ud = 0, size_t length = 0); int extract_input(int argc, char *argv[]); string& get_response(string hdr){ return response[hdr]; } void set_extra_header(string hdr){ extra_hdrs.push_back(hdr); } void set_response(char *val); void set_response_data(char *data, size_t len){ if(resp_data) delete resp_data; resp_data = new string(data, len); } string& get_rgw_admin_path() { return rgw_admin_path; } string& get_ceph_conf_path() { return conf_path; } void set_creds(string& c) { creds = c; } const string *get_response_data(){return resp_data;} unsigned get_resp_code(){return resp_code;} }; int test_helper::extract_input(int argc, char *argv[]){ #define ERR_CHECK_NEXT_PARAM(o) \ if(((int)loop + 1) >= argc)return -1; \ else o = argv[loop+1]; for(unsigned loop = 1;loop < (unsigned)argc; loop += 2){ if(strcmp(argv[loop], "-g") == 0){ ERR_CHECK_NEXT_PARAM(host); }else if(strcmp(argv[loop],"-p") == 0){ ERR_CHECK_NEXT_PARAM(port); }else if(strcmp(argv[loop], "-c") == 0){ ERR_CHECK_NEXT_PARAM(conf_path); }else if(strcmp(argv[loop], "-rgw-admin") == 0){ ERR_CHECK_NEXT_PARAM(rgw_admin_path); }else return -1; } if(!host.length() || !rgw_admin_path.length()) return -1; return 0; } void test_helper::set_response(char *r){ string sr(r), h, v; size_t off = sr.find(": "); if(off != string::npos){ h.assign(sr, 0, off); v.assign(sr, off + 2, sr.find("\r\n") - (off+2)); }else{ /*Could be the status code*/ if(sr.find("HTTP/") != string::npos){ h.assign(HTTP_RESPONSE_STR); off = sr.find(" "); v.assign(sr, off + 1, sr.find("\r\n") - (off + 1)); resp_code = atoi((v.substr(0, 3)).c_str()); } } response[h] = v; } size_t write_header(void *ptr, size_t size, size_t nmemb, void *ud){ test_helper *h = static_cast<test_helper *>(ud); h->set_response((char *)ptr); return size*nmemb; } size_t write_data(void *ptr, size_t size, size_t nmemb, void *ud){ test_helper *h = static_cast<test_helper *>(ud); h->set_response_data((char *)ptr, size*nmemb); return size*nmemb; } static inline void buf_to_hex(const unsigned char *buf, int len, char *str) { int i; str[0] = '\0'; for (i = 0; i < len; i++) { sprintf(&str[i*2], "%02x", (int)buf[i]); } } static void calc_hmac_sha1(const char *key, int key_len, const char *msg, int msg_len, char *dest) /* destination should be CEPH_CRYPTO_HMACSHA1_DIGESTSIZE bytes long */ { ceph::crypto::HMACSHA1 hmac((const unsigned char *)key, key_len); hmac.Update((const unsigned char *)msg, msg_len); hmac.Final((unsigned char *)dest); char hex_str[(CEPH_CRYPTO_HMACSHA1_DIGESTSIZE * 2) + 1]; admin_log::buf_to_hex((unsigned char *)dest, CEPH_CRYPTO_HMACSHA1_DIGESTSIZE, hex_str); } static int get_s3_auth(const string &method, string creds, const string &date, string res, string& out){ string aid, secret, auth_hdr; string tmp_res; size_t off = creds.find(":"); out = ""; if(off != string::npos){ aid.assign(creds, 0, off); secret.assign(creds, off + 1, string::npos); /*sprintf(auth_hdr, "%s\n\n\n%s\n%s", req_type, date, res);*/ char hmac_sha1[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE]; char b64[65]; /* 64 is really enough */ size_t off = res.find("?"); if(off == string::npos) tmp_res = res; else tmp_res.assign(res, 0, off); auth_hdr.append(method + string("\n\n\n") + date + string("\n") + tmp_res); admin_log::calc_hmac_sha1(secret.c_str(), secret.length(), auth_hdr.c_str(), auth_hdr.length(), hmac_sha1); int ret = ceph_armor(b64, b64 + 64, hmac_sha1, hmac_sha1 + CEPH_CRYPTO_HMACSHA1_DIGESTSIZE); if (ret < 0) { cout << "ceph_armor failed\n"; return -1; } b64[ret] = 0; out.append(aid + string(":") + b64); }else return -1; return 0; } void get_date(string& d){ struct timeval tv; char date[64]; struct tm tm; char *days[] = {(char *)"Sun", (char *)"Mon", (char *)"Tue", (char *)"Wed", (char *)"Thu", (char *)"Fri", (char *)"Sat"}; char *months[] = {(char *)"Jan", (char *)"Feb", (char *)"Mar", (char *)"Apr", (char *)"May", (char *)"Jun", (char *)"Jul",(char *) "Aug", (char *)"Sep", (char *)"Oct", (char *)"Nov", (char *)"Dec"}; gettimeofday(&tv, NULL); gmtime_r(&tv.tv_sec, &tm); sprintf(date, "%s, %d %s %d %d:%d:%d GMT", days[tm.tm_wday], tm.tm_mday, months[tm.tm_mon], tm.tm_year + 1900, tm.tm_hour, tm.tm_min, tm.tm_sec); d = date; } int test_helper::send_request(string method, string res, size_t (*read_function)( void *,size_t,size_t,void *), void *ud, size_t length){ string url; string auth, date; url.append(string("http://") + host); if(port.length() > 0)url.append(string(":") + port); url.append(res); curl_inst = curl_easy_init(); if(curl_inst){ curl_easy_setopt(curl_inst, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl_inst, CURLOPT_CUSTOMREQUEST, method.c_str()); curl_easy_setopt(curl_inst, CURLOPT_VERBOSE, CURL_VERBOSE); curl_easy_setopt(curl_inst, CURLOPT_HEADERFUNCTION, admin_log::write_header); curl_easy_setopt(curl_inst, CURLOPT_WRITEHEADER, (void *)this); curl_easy_setopt(curl_inst, CURLOPT_WRITEFUNCTION, admin_log::write_data); curl_easy_setopt(curl_inst, CURLOPT_WRITEDATA, (void *)this); if(read_function){ curl_easy_setopt(curl_inst, CURLOPT_READFUNCTION, read_function); curl_easy_setopt(curl_inst, CURLOPT_READDATA, (void *)ud); curl_easy_setopt(curl_inst, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl_inst, CURLOPT_INFILESIZE_LARGE, (curl_off_t)length); } get_date(date); string http_date; http_date.append(string("Date: ") + date); string s3auth; if (admin_log::get_s3_auth(method, creds, date, res, s3auth) < 0) return -1; auth.append(string("Authorization: AWS ") + s3auth); struct curl_slist *slist = NULL; slist = curl_slist_append(slist, auth.c_str()); slist = curl_slist_append(slist, http_date.c_str()); for(list<string>::iterator it = extra_hdrs.begin(); it != extra_hdrs.end(); ++it){ slist = curl_slist_append(slist, (*it).c_str()); } if(read_function) curl_slist_append(slist, "Expect:"); curl_easy_setopt(curl_inst, CURLOPT_HTTPHEADER, slist); response.erase(response.begin(), response.end()); extra_hdrs.erase(extra_hdrs.begin(), extra_hdrs.end()); CURLcode res = curl_easy_perform(curl_inst); if(res != CURLE_OK){ cout << "Curl perform failed for " << url << ", res: " << curl_easy_strerror(res) << "\n"; return -1; } curl_slist_free_all(slist); } curl_easy_cleanup(curl_inst); return 0; } }; admin_log::test_helper *g_test; Finisher *finisher; int run_rgw_admin(string& cmd, string& resp) { pid_t pid; pid = fork(); if (pid == 0) { /* child */ list<string> l; get_str_list(cmd, " \t", l); char *argv[l.size()]; unsigned loop = 1; argv[0] = (char *)"radosgw-admin"; for (list<string>::iterator it = l.begin(); it != l.end(); ++it) { argv[loop++] = (char *)(*it).c_str(); } argv[loop] = NULL; if (!freopen(RGW_ADMIN_RESP_PATH, "w+", stdout)) { cout << "Unable to open stdout file" << std::endl; } execv((g_test->get_rgw_admin_path()).c_str(), argv); } else if (pid > 0) { int status; waitpid(pid, &status, 0); if (WIFEXITED(status)) { if(WEXITSTATUS(status) != 0) { cout << "Child exited with status " << WEXITSTATUS(status) << std::endl; return -1; } } ifstream in; struct stat st; if (stat(RGW_ADMIN_RESP_PATH, &st) < 0) { cout << "Error stating the admin response file, errno " << errno << std::endl; return -1; } else { char *data = (char *)malloc(st.st_size + 1); in.open(RGW_ADMIN_RESP_PATH); in.read(data, st.st_size); in.close(); data[st.st_size] = 0; resp = data; free(data); unlink(RGW_ADMIN_RESP_PATH); /* cout << "radosgw-admin " << cmd << ": " << resp << std::endl; */ } } else return -1; return 0; } int get_creds(string& json, string& creds) { JSONParser parser; if(!parser.parse(json.c_str(), json.length())) { cout << "Error parsing create user response" << std::endl; return -1; } RGWUserInfo info; decode_json_obj(info, &parser); creds = ""; for(map<string, RGWAccessKey>::iterator it = info.access_keys.begin(); it != info.access_keys.end(); ++it) { RGWAccessKey _k = it->second; /*cout << "accesskeys [ " << it->first << " ] = " << "{ " << _k.id << ", " << _k.key << ", " << _k.subuser << "}" << std::endl;*/ creds.append(it->first + string(":") + _k.key); break; } return 0; } int user_create(string& uid, string& display_name, bool set_creds = true) { stringstream ss; string creds; ss << "-c " << g_test->get_ceph_conf_path() << " user create --uid=" << uid << " --display-name=" << display_name; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error creating user" << std::endl; return -1; } get_creds(out, creds); if(set_creds) g_test->set_creds(creds); return 0; } int user_info(string& uid, string& display_name, RGWUserInfo& uinfo) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " user info --uid=" << uid << " --display-name=" << display_name; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error reading user information" << std::endl; return -1; } JSONParser parser; if(!parser.parse(out.c_str(), out.length())) { cout << "Error parsing create user response" << std::endl; return -1; } decode_json_obj(uinfo, &parser); return 0; } int user_rm(string& uid, string& display_name) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " metadata rm --metadata-key=user:" << uid; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error removing user" << std::endl; return -1; } return 0; } int caps_add(const char * name, const char *perm) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " caps add --caps=" << name << "=" << perm << " --uid=" << uid; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error creating user" << std::endl; return -1; } return 0; } int caps_rm(const char * name, const char *perm) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " caps rm --caps=" << name << "=" << perm << " --uid=" << uid; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error creating user" << std::endl; return -1; } return 0; } static int create_bucket(void){ g_test->send_request(string("PUT"), string("/" TEST_BUCKET_NAME)); if(g_test->get_resp_code() != 200U){ cout << "Error creating bucket, http code " << g_test->get_resp_code(); return -1; } return 0; } static int delete_bucket(void){ g_test->send_request(string("DELETE"), string("/" TEST_BUCKET_NAME)); if(g_test->get_resp_code() != 204U){ cout << "Error deleting bucket, http code " << g_test->get_resp_code(); return -1; } return 0; } size_t read_dummy_post(void *ptr, size_t s, size_t n, void *ud) { int dummy = 0; memcpy(ptr, &dummy, sizeof(dummy)); return sizeof(dummy); } size_t read_bucket_object(void *ptr, size_t s, size_t n, void *ud) { memcpy(ptr, ud, TEST_BUCKET_OBJECT_SIZE); return TEST_BUCKET_OBJECT_SIZE; } static int put_bucket_obj(const char *obj_name, char *data, unsigned len) { string req = "/" TEST_BUCKET_NAME"/"; req.append(obj_name); g_test->send_request(string("PUT"), req, read_bucket_object, (void *)data, (size_t)len); if (g_test->get_resp_code() != 200U) { cout << "Errror sending object to the bucket, http_code " << g_test->get_resp_code(); return -1; } return 0; } static int read_bucket_obj(const char *obj_name) { string req = "/" TEST_BUCKET_NAME"/"; req.append(obj_name); g_test->send_request(string("GET"), req); if (g_test->get_resp_code() != 200U) { cout << "Errror sending object to the bucket, http_code " << g_test->get_resp_code(); return -1; } return 0; } static int delete_obj(const char *obj_name) { string req = "/" TEST_BUCKET_NAME"/"; req.append(obj_name); g_test->send_request(string("DELETE"), req); if (g_test->get_resp_code() != 204U) { cout << "Errror deleting object from bucket, http_code " << g_test->get_resp_code(); return -1; } return 0; } int get_formatted_time(string& ret) { struct tm *tm = NULL; char str_time[200]; const char *format = "%Y-%m-%d%%20%H:%M:%S"; time_t t; t = time(NULL); tm = gmtime(&t); if(!tm) { cerr << "Error returned by gmtime\n"; return -1; } if (strftime(str_time, sizeof(str_time), format, tm) == 0) { cerr << "Error returned by strftime\n"; return -1; } ret = str_time; return 0; } int parse_json_resp(JSONParser &parser) { string *resp; resp = (string *)g_test->get_response_data(); if(!resp) return -1; if(!parser.parse(resp->c_str(), resp->length())) { cout << "Error parsing create user response" << std::endl; return -1; } return 0; } struct cls_log_entry_json { string section; string name; utime_t timestamp; RGWMetadataLogData log_data; }; static int decode_json(JSONObj *obj, RGWMetadataLogData &data) { JSONObj *jo; jo = obj->find_obj("read_version"); if (!jo) return -1; data.read_version.decode_json(obj); data.write_version.decode_json(obj); jo = obj->find_obj("status"); if (!jo) return -1; JSONDecoder::decode_json("status", data, jo); return 0; } static int decode_json(JSONObj *obj, cls_log_entry_json& ret) { JSONDecoder::decode_json("section", ret.section, obj); JSONDecoder::decode_json("name", ret.name, obj); JSONObj *jo = obj->find_obj("data"); if(!jo) return 0; return decode_json(jo, ret.log_data); } static int get_log_list(list<cls_log_entry_json> &entries) { JSONParser parser; if (parse_json_resp(parser) != 0) return -1; if (!parser.is_array()) return -1; vector<string> l; l = parser.get_array_elements(); int loop = 0; for(vector<string>::iterator it = l.begin(); it != l.end(); ++it, loop++) { JSONParser jp; cls_log_entry_json entry; if(!jp.parse((*it).c_str(), (*it).length())) { cerr << "Error parsing log json object" << std::endl; return -1; } EXPECT_EQ(decode_json((JSONObj *)&jp, entry), 0); entries.push_back(entry); } return 0; } struct cls_bilog_entry { string op_id; string op_tag; string op; string object; string status; unsigned index_ver; }; static int decode_json(JSONObj *obj, cls_bilog_entry& ret) { JSONDecoder::decode_json("op_id", ret.op_id, obj); JSONDecoder::decode_json("op_tag", ret.op_tag, obj); JSONDecoder::decode_json("op", ret.op, obj); JSONDecoder::decode_json("object", ret.object, obj); JSONDecoder::decode_json("state", ret.status, obj); JSONDecoder::decode_json("index_ver", ret.index_ver, obj); return 0; } static int get_bilog_list(list<cls_bilog_entry> &entries) { JSONParser parser; if (parse_json_resp(parser) != 0) return -1; if (!parser.is_array()) return -1; vector<string> l; l = parser.get_array_elements(); int loop = 0; for(vector<string>::iterator it = l.begin(); it != l.end(); ++it, loop++) { JSONParser jp; cls_bilog_entry entry; if(!jp.parse((*it).c_str(), (*it).length())) { cerr << "Error parsing log json object" << std::endl; return -1; } EXPECT_EQ(decode_json((JSONObj *)&jp, entry), 0); entries.push_back(entry); } return 0; } static int decode_json(JSONObj *obj, rgw_data_change& ret) { string entity; JSONDecoder::decode_json("entity_type", entity, obj); if (entity.compare("bucket") == 0) ret.entity_type = ENTITY_TYPE_BUCKET; JSONDecoder::decode_json("key", ret.key, obj); return 0; } static int get_datalog_list(list<rgw_data_change> &entries) { JSONParser parser; if (parse_json_resp(parser) != 0) return -1; if (!parser.is_array()) return -1; vector<string> l; l = parser.get_array_elements(); int loop = 0; for(vector<string>::iterator it = l.begin(); it != l.end(); ++it, loop++) { JSONParser jp; rgw_data_change entry; if(!jp.parse((*it).c_str(), (*it).length())) { cerr << "Error parsing log json object" << std::endl; return -1; } EXPECT_EQ(decode_json((JSONObj *)&jp, entry), 0); entries.push_back(entry); } return 0; } unsigned get_mdlog_shard_id(string& key, int max_shards) { string section = "user"; uint32_t val = ceph_str_hash_linux(key.c_str(), key.size()); val ^= ceph_str_hash_linux(section.c_str(), section.size()); return (unsigned)(val % max_shards); } unsigned get_datalog_shard_id(const char *bucket_name, int max_shards) { uint32_t r = ceph_str_hash_linux(bucket_name, strlen(bucket_name)) % max_shards; return (int)r; } TEST(TestRGWAdmin, datalog_list) { string start_time, end_time; const char *cname = "datalog", *perm = "*"; string rest_req; unsigned shard_id = get_datalog_shard_id(TEST_BUCKET_NAME, g_ceph_context->_conf->rgw_data_log_num_shards); stringstream ss; list<rgw_data_change> entries; ASSERT_EQ(get_formatted_time(start_time), 0); ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=data"; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); JSONParser parser; int num_objects; EXPECT_EQ (parse_json_resp(parser), 0); JSONDecoder::decode_json("num_objects", num_objects, (JSONObj *)&parser); ASSERT_EQ(num_objects,g_ceph_context->_conf->rgw_data_log_num_shards); sleep(1); ASSERT_EQ(0, create_bucket()); char *bucket_obj = (char *)calloc(1, TEST_BUCKET_OBJECT_SIZE); ASSERT_TRUE(bucket_obj != NULL); EXPECT_EQ(put_bucket_obj(TEST_BUCKET_OBJECT, bucket_obj, TEST_BUCKET_OBJECT_SIZE), 0); sleep(1); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_datalog_list(entries); EXPECT_EQ(1U, entries.size()); if (entries.size() == 1) { rgw_data_change entry = *(entries.begin()); EXPECT_EQ(entry.entity_type, ENTITY_TYPE_BUCKET); EXPECT_EQ(entry.key.compare(TEST_BUCKET_NAME), 0); } ASSERT_EQ(0, delete_obj(TEST_BUCKET_OBJECT)); sleep(1); ASSERT_EQ(get_formatted_time(end_time), 0); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_datalog_list(entries); EXPECT_EQ(1U, entries.size()); if (entries.size() == 1) { list<rgw_data_change>::iterator it = (entries.begin()); EXPECT_EQ((*it).entity_type, ENTITY_TYPE_BUCKET); EXPECT_EQ((*it).key.compare(TEST_BUCKET_NAME), 0); } sleep(1); EXPECT_EQ(put_bucket_obj(TEST_BUCKET_OBJECT, bucket_obj, TEST_BUCKET_OBJECT_SIZE), 0); free(bucket_obj); sleep(20); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_datalog_list(entries); EXPECT_EQ(2U, entries.size()); if (entries.size() == 2) { list<rgw_data_change>::iterator it = (entries.begin()); EXPECT_EQ((*it).entity_type, ENTITY_TYPE_BUCKET); EXPECT_EQ((*it).key.compare(TEST_BUCKET_NAME), 0); ++it; EXPECT_EQ((*it).entity_type, ENTITY_TYPE_BUCKET); EXPECT_EQ((*it).key.compare(TEST_BUCKET_NAME), 0); } ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time << "&max-entries=1"; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_datalog_list(entries); EXPECT_EQ(1U, entries.size()); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_datalog_list(entries); EXPECT_EQ(1U, entries.size()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "read"; ASSERT_EQ(0, caps_add(cname, perm)); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, delete_obj(TEST_BUCKET_OBJECT)); ASSERT_EQ(0, delete_bucket()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, datalog_lock_unlock) { const char *cname = "datalog", *perm = "*"; string rest_req; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=data&lock&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=data&lock&id=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=data&lock&length=3&id=1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=data&lock&length=3&id=1&locker-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=data&unlock&id=1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=data&unlock&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=data&unlock&locker-id=ceph&id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&unlock&id=1&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); utime_t sleep_time(3, 0); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(500U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph1&zone-id=2"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(500U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); sleep_time.sleep(); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&unlock&id=1&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "read"; ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "write"; ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); rest_req = "/admin/log?type=data&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); rest_req = "/admin/log?type=data&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, datalog_trim) { string start_time, end_time; const char *cname = "datalog", *perm = "*"; string rest_req; unsigned shard_id = get_datalog_shard_id(TEST_BUCKET_NAME, g_ceph_context->_conf->rgw_data_log_num_shards); stringstream ss; list<rgw_data_change> entries; ASSERT_EQ(get_formatted_time(start_time), 0); ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=data"; g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ ss.str(""); ss << "/admin/log?type=data&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ ASSERT_EQ(0, create_bucket()); char *bucket_obj = (char *)calloc(1, TEST_BUCKET_OBJECT_SIZE); ASSERT_TRUE(bucket_obj != NULL); EXPECT_EQ(put_bucket_obj(TEST_BUCKET_OBJECT, bucket_obj, TEST_BUCKET_OBJECT_SIZE), 0); ASSERT_EQ(0, delete_obj(TEST_BUCKET_OBJECT)); sleep(1); EXPECT_EQ(put_bucket_obj(TEST_BUCKET_OBJECT, bucket_obj, TEST_BUCKET_OBJECT_SIZE), 0); ASSERT_EQ(0, delete_obj(TEST_BUCKET_OBJECT)); sleep(20); free(bucket_obj); ASSERT_EQ(get_formatted_time(end_time), 0); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_datalog_list(entries); EXPECT_TRUE(!entries.empty()); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_datalog_list(entries); EXPECT_TRUE(entries.empty()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "write"; ASSERT_EQ(0, caps_add(cname, perm)); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = ""; ASSERT_EQ(0, caps_add(cname, perm)); ss.str(""); ss << "/admin/log?type=data&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, delete_bucket()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, mdlog_list) { string start_time, end_time, start_time_2; const char *cname = "mdlog", *perm = "*"; string rest_req; unsigned shard_id = get_mdlog_shard_id(uid, g_ceph_context->_conf->rgw_md_log_max_shards); stringstream ss; sleep(2); ASSERT_EQ(get_formatted_time(start_time), 0); ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=metadata"; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); JSONParser parser; int num_objects; EXPECT_EQ (parse_json_resp(parser), 0); JSONDecoder::decode_json("num_objects", num_objects, (JSONObj *)&parser); ASSERT_EQ(num_objects,g_ceph_context->_conf->rgw_md_log_max_shards); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); list<cls_log_entry_json> entries; EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 4U); if(entries.size() == 4) { list<cls_log_entry_json>::iterator it = entries.begin(); EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_WRITE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_COMPLETE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_WRITE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_COMPLETE); } sleep(1); /*To get a modified time*/ ASSERT_EQ(get_formatted_time(start_time_2), 0); ASSERT_EQ(0, caps_rm(cname, perm)); perm="read"; ASSERT_EQ(0, caps_add(cname, perm)); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time_2; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 4U); if(entries.size() == 4) { list<cls_log_entry_json>::iterator it = entries.begin(); EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_WRITE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_COMPLETE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_WRITE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_COMPLETE); } sleep(1); ASSERT_EQ(get_formatted_time(start_time_2), 0); ASSERT_EQ(0, user_rm(uid, display_name)); ASSERT_EQ(0, user_create(uid, display_name)); perm = "*"; ASSERT_EQ(0, caps_add(cname, perm)); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time_2; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 6U); if(entries.size() == 6) { list<cls_log_entry_json>::iterator it = entries.begin(); EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_REMOVE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_WRITE); ++it; EXPECT_TRUE(it->section.compare("user") == 0); EXPECT_TRUE(it->name.compare(uid) == 0); EXPECT_TRUE(it->log_data.status == MDLOG_STATUS_COMPLETE); } sleep(1); ASSERT_EQ(get_formatted_time(end_time), 0); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 14U); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time << "&max-entries=" << 1; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 1U); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time << "&max-entries=" << 6; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 6U); ASSERT_EQ(0, caps_rm(cname, perm)); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(403U, g_test->get_resp_code()); /*cleanup*/ ASSERT_EQ(0, caps_add(cname, perm)); sleep(1); ASSERT_EQ(get_formatted_time(end_time), 0); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, mdlog_trim) { string start_time, end_time; const char *cname = "mdlog", *perm = "*"; string rest_req; list<cls_log_entry_json> entries; unsigned shard_id = get_mdlog_shard_id(uid, g_ceph_context->_conf->rgw_md_log_max_shards); ostringstream ss; sleep(1); ASSERT_EQ(get_formatted_time(start_time), 0); ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 4U); sleep(1); ASSERT_EQ(get_formatted_time(end_time), 0); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time; rest_req = ss.str(); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); EXPECT_EQ(get_log_list(entries), 0); EXPECT_EQ(entries.size(), 0U); ASSERT_EQ(0, caps_rm(cname, perm)); perm="write"; ASSERT_EQ(0, caps_add(cname, perm)); ASSERT_EQ(get_formatted_time(end_time), 0); ss.str(""); ss << "/admin/log?type=metadata&id=" << shard_id << "&start-time=" << start_time << "&end-time=" << end_time; rest_req = ss.str(); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, mdlog_lock_unlock) { const char *cname = "mdlog", *perm = "*"; string rest_req; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=metadata&lock&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=metadata&lock&id=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=metadata&lock&length=3&id=1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=metadata&lock&id=3&locker-id=ceph&length=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=metadata&unlock&id=1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=metadata&unlock&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=metadata&unlock&locker-id=ceph&id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&unlock&id=1&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); utime_t sleep_time(3, 0); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(500U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph&zone-id=2"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(500U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); sleep_time.sleep(); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&unlock&id=1&locker-id=ceph1&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "read"; ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "write"; ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); rest_req = "/admin/log?type=metadata&lock&id=1&length=3&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); rest_req = "/admin/log?type=metadata&unlock&id=1&locker-id=ceph&zone-id=1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, bilog_list) { const char *cname = "bilog", *perm = "*"; string rest_req; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); ASSERT_EQ(0, create_bucket()); char *bucket_obj = (char *)calloc(1, TEST_BUCKET_OBJECT_SIZE); ASSERT_TRUE(bucket_obj != NULL); EXPECT_EQ(put_bucket_obj(TEST_BUCKET_OBJECT, bucket_obj, TEST_BUCKET_OBJECT_SIZE), 0); free(bucket_obj); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); list<cls_bilog_entry> entries; get_bilog_list(entries); EXPECT_EQ(2U, entries.size()); if (entries.size() == 2) { list<cls_bilog_entry>::iterator it = entries.begin(); EXPECT_EQ(it->op.compare("write"), 0); EXPECT_EQ(it->object.compare(TEST_BUCKET_OBJECT), 0); EXPECT_EQ(it->status.compare("pending"), 0); EXPECT_EQ(it->index_ver, 1U); ++it; EXPECT_EQ(it->op.compare("write"), 0); EXPECT_EQ(it->object.compare(TEST_BUCKET_OBJECT), 0); EXPECT_EQ(it->status.compare("complete"), 0); EXPECT_EQ(it->index_ver, 2U); } EXPECT_EQ(read_bucket_obj(TEST_BUCKET_OBJECT), 0); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_bilog_list(entries); EXPECT_EQ(2U, entries.size()); bucket_obj = (char *)calloc(1, TEST_BUCKET_OBJECT_SIZE); ASSERT_TRUE(bucket_obj != NULL); EXPECT_EQ(put_bucket_obj(TEST_BUCKET_OBJECT_1, bucket_obj, TEST_BUCKET_OBJECT_SIZE), 0); free(bucket_obj); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_bilog_list(entries); EXPECT_EQ(4U, entries.size()); if (entries.size() == 4) { list<cls_bilog_entry>::iterator it = entries.begin(); ++it; ++it; EXPECT_EQ(it->op.compare("write"), 0); EXPECT_EQ(it->object.compare(TEST_BUCKET_OBJECT_1), 0); EXPECT_EQ(it->status.compare("pending"), 0); EXPECT_EQ(it->index_ver, 3U); ++it; EXPECT_EQ(it->op.compare("write"), 0); EXPECT_EQ(it->object.compare(TEST_BUCKET_OBJECT_1), 0); EXPECT_EQ(it->status.compare("complete"), 0); EXPECT_EQ(it->index_ver, 4U); } ASSERT_EQ(0, delete_obj(TEST_BUCKET_OBJECT)); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_bilog_list(entries); EXPECT_EQ(6U, entries.size()); string marker; if (entries.size() == 6) { list<cls_bilog_entry>::iterator it = entries.begin(); ++it; ++it; ++it; ++it; marker = it->op_id; EXPECT_EQ(it->op.compare("del"), 0); EXPECT_EQ(it->object.compare(TEST_BUCKET_OBJECT), 0); EXPECT_EQ(it->status.compare("pending"), 0); EXPECT_EQ(it->index_ver, 5U); ++it; EXPECT_EQ(it->op.compare("del"), 0); EXPECT_EQ(it->object.compare(TEST_BUCKET_OBJECT), 0); EXPECT_EQ(it->status.compare("complete"), 0); EXPECT_EQ(it->index_ver, 6U); } rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; rest_req.append("&marker="); rest_req.append(marker); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_bilog_list(entries); EXPECT_EQ(2U, entries.size()); if (entries.size() == 2U) { list<cls_bilog_entry>::iterator it = entries.begin(); EXPECT_EQ(it->index_ver, 5U); ++it; EXPECT_EQ(it->index_ver, 6U); EXPECT_EQ(it->op.compare("del"), 0); } rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; rest_req.append("&marker="); rest_req.append(marker); rest_req.append("&max-entries=1"); g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_bilog_list(entries); EXPECT_EQ(1U, entries.size()); EXPECT_EQ((entries.begin())->index_ver, 5U); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "read"; ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, caps_rm(cname, perm)); perm = "write"; ASSERT_EQ(0, caps_add(cname, perm)); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, delete_obj(TEST_BUCKET_OBJECT_1)); ASSERT_EQ(0, delete_bucket()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, bilog_trim) { const char *cname = "bilog", *perm = "*"; string rest_req, start_marker, end_marker; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, caps_add(cname, perm)); ASSERT_EQ(0, create_bucket()); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ char *bucket_obj = (char *)calloc(1, TEST_BUCKET_OBJECT_SIZE); ASSERT_TRUE(bucket_obj != NULL); EXPECT_EQ(put_bucket_obj(TEST_BUCKET_OBJECT, bucket_obj, TEST_BUCKET_OBJECT_SIZE), 0); free(bucket_obj); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); list<cls_bilog_entry> entries; get_bilog_list(entries); EXPECT_EQ(2U, entries.size()); list<cls_bilog_entry>::iterator it = entries.begin(); start_marker = it->op_id; ++it; end_marker = it->op_id; rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; rest_req.append("&start-marker="); rest_req.append(start_marker); rest_req.append("&end-marker="); rest_req.append(end_marker); g_test->send_request(string("DELETE"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/log?type=bucket-index&bucket=" TEST_BUCKET_NAME; g_test->send_request(string("GET"), rest_req); EXPECT_EQ(200U, g_test->get_resp_code()); entries.clear(); get_bilog_list(entries); EXPECT_EQ(0U, entries.size()); ASSERT_EQ(0, delete_obj(TEST_BUCKET_OBJECT)); ASSERT_EQ(0, delete_bucket()); ASSERT_EQ(0, user_rm(uid, display_name)); } int main(int argc, char *argv[]){ auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); g_test = new admin_log::test_helper(); finisher = new Finisher(g_ceph_context); #ifdef GTEST ::testing::InitGoogleTest(&argc, argv); #endif finisher->start(); if(g_test->extract_input(argc, argv) < 0){ print_usage(argv[0]); return -1; } #ifdef GTEST int r = RUN_ALL_TESTS(); if (r >= 0) { cout << "There are no failures in the test case\n"; } else { cout << "There are some failures\n"; } #endif finisher->stop(); return 0; }
53,791
32.810182
111
cc
null
ceph-main/src/test/test_rgw_admin_meta.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 eNovance SAS <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/wait.h> #include <unistd.h> #include <fstream> #include <map> #include <list> extern "C"{ #include <curl/curl.h> } #include "common/ceph_crypto.h" #include "include/str_list.h" #include "common/ceph_json.h" #include "common/code_environment.h" #include "common/ceph_argparse.h" #include "common/Finisher.h" #include "global/global_init.h" #include "rgw_common.h" #include "rgw_rados.h" #include <gtest/gtest.h> using namespace std; #define CURL_VERBOSE 0 #define HTTP_RESPONSE_STR "RespCode" #define CEPH_CRYPTO_HMACSHA1_DIGESTSIZE 20 #define RGW_ADMIN_RESP_PATH "/tmp/.test_rgw_admin_resp" #define CEPH_UID "ceph" static string uid = CEPH_UID; static string display_name = "CEPH"; static string meta_caps = "metadata"; extern "C" int ceph_armor(char *dst, const char *dst_end, const char *src, const char *end); static void print_usage(char *exec){ cout << "Usage: " << exec << " <Options>\n"; cout << "Options:\n" "-g <gw-ip> - The ip address of the gateway\n" "-p <gw-port> - The port number of the gateway\n" "-c <ceph.conf> - Absolute path of ceph config file\n" "-rgw-admin <path/to/radosgw-admin> - radosgw-admin absolute path\n"; } namespace admin_meta { class test_helper { private: string host; string port; string creds; string rgw_admin_path; string conf_path; CURL *curl_inst; map<string, string> response; list<string> extra_hdrs; string *resp_data; unsigned resp_code; public: test_helper() : curl_inst(0), resp_data(NULL), resp_code(0) { curl_global_init(CURL_GLOBAL_ALL); } ~test_helper(){ curl_global_cleanup(); } int send_request(string method, string uri, size_t (*function)(void *,size_t,size_t,void *) = 0, void *ud = 0, size_t length = 0); int extract_input(int argc, char *argv[]); string& get_response(string hdr){ return response[hdr]; } void set_extra_header(string hdr){ extra_hdrs.push_back(hdr); } void set_response(char *val); void set_response_data(char *data, size_t len){ if(resp_data) delete resp_data; resp_data = new string(data, len); } string& get_rgw_admin_path() { return rgw_admin_path; } string& get_ceph_conf_path() { return conf_path; } void set_creds(string& c) { creds = c; } const string *get_response_data(){return resp_data;} unsigned get_resp_code(){return resp_code;} }; int test_helper::extract_input(int argc, char *argv[]){ #define ERR_CHECK_NEXT_PARAM(o) \ if(((int)loop + 1) >= argc)return -1; \ else o = argv[loop+1]; for(unsigned loop = 1;loop < (unsigned)argc; loop += 2){ if(strcmp(argv[loop], "-g") == 0){ ERR_CHECK_NEXT_PARAM(host); }else if(strcmp(argv[loop],"-p") == 0){ ERR_CHECK_NEXT_PARAM(port); }else if(strcmp(argv[loop], "-c") == 0){ ERR_CHECK_NEXT_PARAM(conf_path); }else if(strcmp(argv[loop], "-rgw-admin") == 0){ ERR_CHECK_NEXT_PARAM(rgw_admin_path); }else return -1; } if(host.empty() || rgw_admin_path.empty()) return -1; return 0; } void test_helper::set_response(char *r){ string sr(r), h, v; size_t off = sr.find(": "); if(off != string::npos){ h.assign(sr, 0, off); v.assign(sr, off + 2, sr.find("\r\n") - (off+2)); }else{ /*Could be the status code*/ if(sr.find("HTTP/") != string::npos){ h.assign(HTTP_RESPONSE_STR); off = sr.find(" "); v.assign(sr, off + 1, sr.find("\r\n") - (off + 1)); resp_code = atoi((v.substr(0, 3)).c_str()); } } response[h] = v; } size_t write_header(void *ptr, size_t size, size_t nmemb, void *ud){ test_helper *h = static_cast<test_helper *>(ud); h->set_response((char *)ptr); return size*nmemb; } size_t write_data(void *ptr, size_t size, size_t nmemb, void *ud){ test_helper *h = static_cast<test_helper *>(ud); h->set_response_data((char *)ptr, size*nmemb); return size*nmemb; } static inline void buf_to_hex(const unsigned char *buf, int len, char *str) { int i; str[0] = '\0'; for (i = 0; i < len; i++) { sprintf(&str[i*2], "%02x", (int)buf[i]); } } static void calc_hmac_sha1(const char *key, int key_len, const char *msg, int msg_len, char *dest) /* destination should be CEPH_CRYPTO_HMACSHA1_DIGESTSIZE bytes long */ { ceph::crypto::HMACSHA1 hmac((const unsigned char *)key, key_len); hmac.Update((const unsigned char *)msg, msg_len); hmac.Final((unsigned char *)dest); char hex_str[(CEPH_CRYPTO_HMACSHA1_DIGESTSIZE * 2) + 1]; admin_meta::buf_to_hex((unsigned char *)dest, CEPH_CRYPTO_HMACSHA1_DIGESTSIZE, hex_str); } static int get_s3_auth(const string &method, string creds, const string &date, string res, string& out){ string aid, secret, auth_hdr; string tmp_res; size_t off = creds.find(":"); out = ""; if(off != string::npos){ aid.assign(creds, 0, off); secret.assign(creds, off + 1, string::npos); /*sprintf(auth_hdr, "%s\n\n\n%s\n%s", req_type, date, res);*/ char hmac_sha1[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE]; char b64[65]; /* 64 is really enough */ size_t off = res.find("?"); if(off == string::npos) tmp_res = res; else tmp_res.assign(res, 0, off); auth_hdr.append(method + string("\n\n\n") + date + string("\n") + tmp_res); admin_meta::calc_hmac_sha1(secret.c_str(), secret.length(), auth_hdr.c_str(), auth_hdr.length(), hmac_sha1); int ret = ceph_armor(b64, b64 + 64, hmac_sha1, hmac_sha1 + CEPH_CRYPTO_HMACSHA1_DIGESTSIZE); if (ret < 0) { cout << "ceph_armor failed\n"; return -1; } b64[ret] = 0; out.append(aid + string(":") + b64); }else return -1; return 0; } void get_date(string& d){ struct timeval tv; char date[64]; struct tm tm; char *days[] = {(char *)"Sun", (char *)"Mon", (char *)"Tue", (char *)"Wed", (char *)"Thu", (char *)"Fri", (char *)"Sat"}; char *months[] = {(char *)"Jan", (char *)"Feb", (char *)"Mar", (char *)"Apr", (char *)"May", (char *)"Jun", (char *)"Jul",(char *) "Aug", (char *)"Sep", (char *)"Oct", (char *)"Nov", (char *)"Dec"}; gettimeofday(&tv, NULL); gmtime_r(&tv.tv_sec, &tm); sprintf(date, "%s, %d %s %d %d:%d:%d GMT", days[tm.tm_wday], tm.tm_mday, months[tm.tm_mon], tm.tm_year + 1900, tm.tm_hour, tm.tm_min, 0 /*tm.tm_sec*/); d = date; } int test_helper::send_request(string method, string res, size_t (*read_function)( void *,size_t,size_t,void *), void *ud, size_t length){ string url; string auth, date; url.append(string("http://") + host); if(port.length() > 0)url.append(string(":") + port); url.append(res); curl_inst = curl_easy_init(); if(curl_inst){ curl_easy_setopt(curl_inst, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl_inst, CURLOPT_CUSTOMREQUEST, method.c_str()); curl_easy_setopt(curl_inst, CURLOPT_VERBOSE, CURL_VERBOSE); curl_easy_setopt(curl_inst, CURLOPT_HEADERFUNCTION, admin_meta::write_header); curl_easy_setopt(curl_inst, CURLOPT_WRITEHEADER, (void *)this); curl_easy_setopt(curl_inst, CURLOPT_WRITEFUNCTION, admin_meta::write_data); curl_easy_setopt(curl_inst, CURLOPT_WRITEDATA, (void *)this); if(read_function){ curl_easy_setopt(curl_inst, CURLOPT_READFUNCTION, read_function); curl_easy_setopt(curl_inst, CURLOPT_READDATA, (void *)ud); curl_easy_setopt(curl_inst, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl_inst, CURLOPT_INFILESIZE_LARGE, (curl_off_t)length); } get_date(date); string http_date; http_date.append(string("Date: ") + date); string s3auth; if (admin_meta::get_s3_auth(method, creds, date, res, s3auth) < 0) return -1; auth.append(string("Authorization: AWS ") + s3auth); struct curl_slist *slist = NULL; slist = curl_slist_append(slist, auth.c_str()); slist = curl_slist_append(slist, http_date.c_str()); for(list<string>::iterator it = extra_hdrs.begin(); it != extra_hdrs.end(); ++it){ slist = curl_slist_append(slist, (*it).c_str()); } if(read_function) curl_slist_append(slist, "Expect:"); curl_easy_setopt(curl_inst, CURLOPT_HTTPHEADER, slist); response.erase(response.begin(), response.end()); extra_hdrs.erase(extra_hdrs.begin(), extra_hdrs.end()); CURLcode res = curl_easy_perform(curl_inst); if(res != CURLE_OK){ cout << "Curl perform failed for " << url << ", res: " << curl_easy_strerror(res) << "\n"; return -1; } curl_slist_free_all(slist); } curl_easy_cleanup(curl_inst); return 0; } }; admin_meta::test_helper *g_test; Finisher *finisher; int run_rgw_admin(string& cmd, string& resp) { pid_t pid; pid = fork(); if (pid == 0) { /* child */ list<string> l; get_str_list(cmd, " \t", l); char *argv[l.size()]; unsigned loop = 1; argv[0] = (char *)"radosgw-admin"; for (list<string>::iterator it = l.begin(); it != l.end(); ++it) { argv[loop++] = (char *)(*it).c_str(); } argv[loop] = NULL; if (!freopen(RGW_ADMIN_RESP_PATH, "w+", stdout)) { cout << "Unable to open stdout file" << std::endl; } execv((g_test->get_rgw_admin_path()).c_str(), argv); } else if (pid > 0) { int status; waitpid(pid, &status, 0); if (WIFEXITED(status)) { if(WEXITSTATUS(status) != 0) { cout << "Child exited with status " << WEXITSTATUS(status) << std::endl; return -1; } } ifstream in; struct stat st; if (stat(RGW_ADMIN_RESP_PATH, &st) < 0) { cout << "Error stating the admin response file, errno " << errno << std::endl; return -1; } else { char *data = (char *)malloc(st.st_size + 1); in.open(RGW_ADMIN_RESP_PATH); in.read(data, st.st_size); in.close(); data[st.st_size] = 0; resp = data; free(data); unlink(RGW_ADMIN_RESP_PATH); /* cout << "radosgw-admin " << cmd << ": " << resp << std::endl;*/ } } else return -1; return 0; } int get_creds(string& json, string& creds) { JSONParser parser; if(!parser.parse(json.c_str(), json.length())) { cout << "Error parsing create user response" << std::endl; return -1; } RGWUserInfo info; decode_json_obj(info, &parser); creds = ""; for(map<string, RGWAccessKey>::iterator it = info.access_keys.begin(); it != info.access_keys.end(); ++it) { RGWAccessKey _k = it->second; /*cout << "accesskeys [ " << it->first << " ] = " << "{ " << _k.id << ", " << _k.key << ", " << _k.subuser << "}" << std::endl;*/ creds.append(it->first + string(":") + _k.key); break; } return 0; } int user_create(string& uid, string& display_name, bool set_creds = true) { stringstream ss; string creds; ss << "-c " << g_test->get_ceph_conf_path() << " user create --uid=" << uid << " --display-name=" << display_name; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error creating user" << std::endl; return -1; } get_creds(out, creds); if(set_creds) g_test->set_creds(creds); return 0; } int user_info(string& uid, string& display_name, RGWUserInfo& uinfo) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " user info --uid=" << uid << " --display-name=" << display_name; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error reading user information" << std::endl; return -1; } JSONParser parser; if(!parser.parse(out.c_str(), out.length())) { cout << "Error parsing create user response" << std::endl; return -1; } decode_json_obj(uinfo, &parser); return 0; } int user_rm(string& uid, string& display_name) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " user rm --uid=" << uid << " --display-name=" << display_name; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error removing user" << std::endl; return -1; } return 0; } int meta_caps_add(const char *perm) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " caps add --caps=" << meta_caps << "=" << perm << " --uid=" << uid; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error creating user" << std::endl; return -1; } return 0; } int meta_caps_rm(const char *perm) { stringstream ss; ss << "-c " << g_test->get_ceph_conf_path() << " caps rm --caps=" << meta_caps << "=" << perm << " --uid=" << uid; string out; string cmd = ss.str(); if(run_rgw_admin(cmd, out) != 0) { cout << "Error creating user" << std::endl; return -1; } return 0; } int compare_access_keys(RGWAccessKey& k1, RGWAccessKey& k2) { if (k1.id.compare(k2.id) != 0) return -1; if (k1.key.compare(k2.key) != 0) return -1; if (k1.subuser.compare(k2.subuser) != 0) return -1; return 0; } int compare_user_info(RGWUserInfo& i1, RGWUserInfo& i2) { int rv; if ((rv = i1.user_id.compare(i2.user_id)) != 0) return rv; if ((rv = i1.display_name.compare(i2.display_name)) != 0) return rv; if ((rv = i1.user_email.compare(i2.user_email)) != 0) return rv; if (i1.access_keys.size() != i2.access_keys.size()) return -1; for (map<string, RGWAccessKey>::iterator it = i1.access_keys.begin(); it != i1.access_keys.end(); ++it) { RGWAccessKey k1, k2; k1 = it->second; if (i2.access_keys.count(it->first) == 0) return -1; k2 = i2.access_keys[it->first]; if (compare_access_keys(k1, k2) != 0) return -1; } if (i1.swift_keys.size() != i2.swift_keys.size()) return -1; for (map<string, RGWAccessKey>::iterator it = i1.swift_keys.begin(); it != i1.swift_keys.end(); ++it) { RGWAccessKey k1, k2; k1 = it->second; if (i2.swift_keys.count(it->first) == 0) return -1; k2 = i2.swift_keys[it->first]; if (compare_access_keys(k1, k2) != 0) return -1; } if (i1.subusers.size() != i2.subusers.size()) return -1; for (map<string, RGWSubUser>::iterator it = i1.subusers.begin(); it != i1.subusers.end(); ++it) { RGWSubUser k1, k2; k1 = it->second; if (!i2.subusers.count(it->first)) return -1; k2 = i2.subusers[it->first]; if (k1.name.compare(k2.name) != 0) return -1; if (k1.perm_mask != k2.perm_mask) return -1; } if (i1.suspended != i2.suspended) return -1; if (i1.max_buckets != i2.max_buckets) return -1; uint32_t p1, p2; p1 = p2 = RGW_CAP_ALL; if (i1.caps.check_cap(meta_caps, p1) != 0) return -1; if (i2.caps.check_cap(meta_caps, p2) != 0) return -1; return 0; } size_t read_dummy_post(void *ptr, size_t s, size_t n, void *ud) { int dummy = 0; memcpy(ptr, &dummy, sizeof(dummy)); return sizeof(dummy); } int parse_json_resp(JSONParser &parser) { string *resp; resp = (string *)g_test->get_response_data(); if(!resp) return -1; if(!parser.parse(resp->c_str(), resp->length())) { cout << "Error parsing create user response" << std::endl; return -1; } return 0; } size_t meta_read_json(void *ptr, size_t s, size_t n, void *ud){ stringstream *ss = (stringstream *)ud; size_t len = ss->str().length(); if(s*n < len){ cout << "Cannot copy json data, as len is not enough\n"; return 0; } memcpy(ptr, (void *)ss->str().c_str(), len); return len; } TEST(TestRGWAdmin, meta_list){ JSONParser parser; bool found = false; const char *perm = "*"; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, meta_caps_add(perm)); /*Check the sections*/ g_test->send_request(string("GET"), string("/admin/metadata/")); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_TRUE(parse_json_resp(parser) == 0); EXPECT_TRUE(parser.is_array()); vector<string> l; l = parser.get_array_elements(); for(vector<string>::iterator it = l.begin(); it != l.end(); ++it) { if((*it).compare("\"user\"") == 0) { found = true; break; } } EXPECT_TRUE(found); /*Check with a wrong section*/ g_test->send_request(string("GET"), string("/admin/metadata/users")); EXPECT_EQ(404U, g_test->get_resp_code()); /*Check the list of keys*/ g_test->send_request(string("GET"), string("/admin/metadata/user")); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_TRUE(parse_json_resp(parser) == 0); EXPECT_TRUE(parser.is_array()); l = parser.get_array_elements(); EXPECT_EQ(1U, l.size()); for(vector<string>::iterator it = l.begin(); it != l.end(); ++it) { if((*it).compare(string("\"") + uid + string("\"")) == 0) { found = true; break; } } EXPECT_TRUE(found); /*Check with second user*/ string uid2 = "ceph1", display_name2 = "CEPH1"; ASSERT_EQ(0, user_create(uid2, display_name2, false)); /*Check the list of keys*/ g_test->send_request(string("GET"), string("/admin/metadata/user")); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_TRUE(parse_json_resp(parser) == 0); EXPECT_TRUE(parser.is_array()); l = parser.get_array_elements(); EXPECT_EQ(2U, l.size()); bool found2 = false; for(vector<string>::iterator it = l.begin(); it != l.end(); ++it) { if((*it).compare(string("\"") + uid + string("\"")) == 0) { found = true; } if((*it).compare(string("\"") + uid2 + string("\"")) == 0) { found2 = true; } } EXPECT_TRUE(found && found2); ASSERT_EQ(0, user_rm(uid2, display_name2)); /*Remove the metadata caps*/ int rv = meta_caps_rm(perm); EXPECT_EQ(0, rv); if(rv == 0) { g_test->send_request(string("GET"), string("/admin/metadata/")); EXPECT_EQ(403U, g_test->get_resp_code()); g_test->send_request(string("GET"), string("/admin/metadata/user")); EXPECT_EQ(403U, g_test->get_resp_code()); } ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, meta_get){ JSONParser parser; const char *perm = "*"; RGWUserInfo info; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, meta_caps_add(perm)); ASSERT_EQ(0, user_info(uid, display_name, info)); g_test->send_request(string("GET"), string("/admin/metadata/user?key=test")); EXPECT_EQ(404U, g_test->get_resp_code()); g_test->send_request(string("GET"), (string("/admin/metadata/user?key=") + uid)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_TRUE(parse_json_resp(parser) == 0); RGWObjVersionTracker objv_tracker; string metadata_key; obj_version *objv = &objv_tracker.read_version; JSONDecoder::decode_json("key", metadata_key, &parser); JSONDecoder::decode_json("ver", *objv, &parser); JSONObj *jo = parser.find_obj("data"); ASSERT_TRUE(jo); string exp_meta_key = "user:"; exp_meta_key.append(uid); EXPECT_TRUE(metadata_key.compare(exp_meta_key) == 0); RGWUserInfo obt_info; decode_json_obj(obt_info, jo); EXPECT_TRUE(compare_user_info(info, obt_info) == 0); /*Make a modification and check if its reflected*/ ASSERT_EQ(0, meta_caps_rm(perm)); perm = "read"; ASSERT_EQ(0, meta_caps_add(perm)); JSONParser parser1; g_test->send_request(string("GET"), (string("/admin/metadata/user?key=") + uid)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_TRUE(parse_json_resp(parser1) == 0); RGWObjVersionTracker objv_tracker1; obj_version *objv1 = &objv_tracker1.read_version; JSONDecoder::decode_json("key", metadata_key, &parser1); JSONDecoder::decode_json("ver", *objv1, &parser1); jo = parser1.find_obj("data"); ASSERT_TRUE(jo); decode_json_obj(obt_info, jo); uint32_t p1, p2; p1 = RGW_CAP_ALL; p2 = RGW_CAP_READ; EXPECT_TRUE (info.caps.check_cap(meta_caps, p1) == 0); EXPECT_TRUE (obt_info.caps.check_cap(meta_caps, p2) == 0); p2 = RGW_CAP_WRITE; EXPECT_TRUE (obt_info.caps.check_cap(meta_caps, p2) != 0); /*Version and tag infromation*/ EXPECT_TRUE(objv1->ver > objv->ver); EXPECT_EQ(objv1->tag, objv->tag); int rv = meta_caps_rm(perm); EXPECT_EQ(0, rv); if(rv == 0) { g_test->send_request(string("GET"), (string("/admin/metadata/user?key=") + uid)); EXPECT_EQ(403U, g_test->get_resp_code()); } ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, meta_put){ JSONParser parser; const char *perm = "*"; RGWUserInfo info; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, meta_caps_add(perm)); g_test->send_request(string("GET"), (string("/admin/metadata/user?key=") + uid)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_TRUE(parse_json_resp(parser) == 0); RGWObjVersionTracker objv_tracker; string metadata_key; obj_version *objv = &objv_tracker.read_version; JSONDecoder::decode_json("key", metadata_key, &parser); JSONDecoder::decode_json("ver", *objv, &parser); JSONObj *jo = parser.find_obj("data"); ASSERT_TRUE(jo); string exp_meta_key = "user:"; exp_meta_key.append(uid); EXPECT_TRUE(metadata_key.compare(exp_meta_key) == 0); RGWUserInfo obt_info; decode_json_obj(obt_info, jo); /*Change the cap and PUT */ RGWUserCaps caps; string new_cap; Formatter *f = new JSONFormatter(); new_cap = meta_caps + string("=write"); caps.add_from_string(new_cap); obt_info.caps = caps; f->open_object_section("metadata_info"); ::encode_json("key", metadata_key, f); ::encode_json("ver", *objv, f); ::encode_json("data", obt_info, f); f->close_section(); std::stringstream ss; f->flush(ss); g_test->send_request(string("PUT"), (string("/admin/metadata/user?key=") + uid), meta_read_json, (void *)&ss, ss.str().length()); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, user_info(uid, display_name, obt_info)); uint32_t cp; cp = RGW_CAP_WRITE; EXPECT_TRUE (obt_info.caps.check_cap(meta_caps, cp) == 0); cp = RGW_CAP_READ; EXPECT_TRUE (obt_info.caps.check_cap(meta_caps, cp) != 0); int rv = meta_caps_rm("write"); EXPECT_EQ(0, rv); if(rv == 0) { g_test->send_request(string("PUT"), (string("/admin/metadata/user?key=") + uid)); EXPECT_EQ(403U, g_test->get_resp_code()); } ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, meta_lock_unlock) { const char *perm = "*"; string rest_req; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, meta_caps_add(perm)); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/metadata/user?lock&length=3&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/metadata/user?key=" CEPH_UID "&unlock"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/metadata/user?unlock&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(400U, g_test->get_resp_code()); /*Bad request*/ rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&unlock&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&unlock&lock_id=ceph1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); utime_t sleep_time(3, 0); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(500U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(409U, g_test->get_resp_code()); sleep_time.sleep(); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&unlock&lock_id=ceph1"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, meta_caps_rm(perm)); perm = "read"; ASSERT_EQ(0, meta_caps_add(perm)); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&unlock&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, meta_caps_rm(perm)); perm = "write"; ASSERT_EQ(0, meta_caps_add(perm)); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&unlock&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_EQ(0, meta_caps_rm(perm)); rest_req = "/admin/metadata/user?key=" CEPH_UID "&lock&length=3&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); rest_req = "/admin/metadata/user?key=" CEPH_UID "&unlock&lock_id=ceph"; g_test->send_request(string("POST"), rest_req, read_dummy_post, NULL, sizeof(int)); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, user_rm(uid, display_name)); } TEST(TestRGWAdmin, meta_delete){ JSONParser parser; const char *perm = "*"; RGWUserInfo info; ASSERT_EQ(0, user_create(uid, display_name)); ASSERT_EQ(0, meta_caps_add(perm)); g_test->send_request(string("DELETE"), (string("/admin/metadata/user?key=") + uid)); EXPECT_EQ(200U, g_test->get_resp_code()); ASSERT_TRUE(user_info(uid, display_name, info) != 0); ASSERT_EQ(0, user_create(uid, display_name)); perm = "read"; ASSERT_EQ(0, meta_caps_add(perm)); g_test->send_request(string("DELETE"), (string("/admin/metadata/user?key=") + uid)); EXPECT_EQ(403U, g_test->get_resp_code()); ASSERT_EQ(0, user_rm(uid, display_name)); } int main(int argc, char *argv[]){ auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); g_test = new admin_meta::test_helper(); finisher = new Finisher(g_ceph_context); #ifdef GTEST ::testing::InitGoogleTest(&argc, argv); #endif finisher->start(); if(g_test->extract_input(argc, argv) < 0){ print_usage(argv[0]); return -1; } #ifdef GTEST int r = RUN_ALL_TESTS(); if (r >= 0) { cout << "There are no failures in the test case\n"; } else { cout << "There are some failures\n"; } #endif finisher->stop(); return 0; }
28,954
30.302703
104
cc
null
ceph-main/src/test/test_rgw_ldap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2015 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <stdint.h> #include <tuple> #include <iostream> #include <vector> #include <map> #include <random> #include "rgw_ldap.h" #include "rgw_token.h" #include "gtest/gtest.h" #include "common/ceph_argparse.h" #include "common/debug.h" #define dout_subsys ceph_subsys_rgw using namespace std; namespace { struct { int argc; char **argv; } saved_args; bool do_hexdump = false; string access_key("ewogICAgIlJHV19UT0tFTiI6IHsKICAgICAgICAidmVyc2lvbiI6IDEsCiAgICAgICAgInR5cGUiOiAibGRhcCIsCiAgICAgICAgImlkIjogImFkbWluIiwKICAgICAgICAia2V5IjogImxpbnV4Ym94IgogICAgfQp9Cg=="); // {admin,linuxbox} string other_key("ewogICAgIlJHV19UT0tFTiI6IHsKICAgICAgICAidmVyc2lvbiI6IDEsCiAgICAgICAgInR5cGUiOiAibGRhcCIsCiAgICAgICAgImlkIjogImFkbWluIiwKICAgICAgICAia2V5IjogImJhZHBhc3MiCiAgICB9Cn0K"); // {admin,badpass} string ldap_uri = "ldaps://f23-kdc.rgw.com"; string ldap_binddn = "uid=admin,cn=users,cn=accounts,dc=rgw,dc=com"; string ldap_bindpw = "supersecret"; string ldap_searchdn = "cn=users,cn=accounts,dc=rgw,dc=com"; string ldap_searchfilter = ""; string ldap_dnattr = "uid"; rgw::LDAPHelper ldh(ldap_uri, ldap_binddn, ldap_bindpw, ldap_searchdn, ldap_searchfilter, ldap_dnattr); } /* namespace */ TEST(RGW_LDAP, INIT) { int ret = ldh.init(); ASSERT_EQ(ret, 0); } TEST(RGW_LDAP, BIND) { int ret = ldh.bind(); ASSERT_EQ(ret, 0); } TEST(RGW_LDAP, AUTH) { using std::get; using namespace rgw; int ret = 0; { RGWToken token{from_base64(access_key)}; ret = ldh.auth(token.id, token.key); ASSERT_EQ(ret, 0); } { RGWToken token{from_base64(other_key)}; ret = ldh.auth(token.id, token.key); ASSERT_NE(ret, 0); } } TEST(RGW_LDAP, SHUTDOWN) { // nothing } int main(int argc, char *argv[]) { auto args = argv_to_vec(argc, argv); env_to_vec(args); string val; for (auto arg_iter = args.begin(); arg_iter != args.end();) { if (ceph_argparse_witharg(args, arg_iter, &val, "--access", (char*) nullptr)) { access_key = val; } else if (ceph_argparse_flag(args, arg_iter, "--hexdump", (char*) nullptr)) { do_hexdump = true; } else { ++arg_iter; } } /* don't accidentally run as anonymous */ if (access_key == "") { std::cout << argv[0] << " no AWS credentials, exiting" << std::endl; return EPERM; } saved_args.argc = argc; saved_args.argv = argv; ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
2,885
23.666667
212
cc
null
ceph-main/src/test/test_rgw_token.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2016 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <errno.h> #include <iostream> #include <sstream> #include <string> #include "common/config.h" #include "common/ceph_argparse.h" #include "common/debug.h" #include "include/ceph_assert.h" #include "gtest/gtest.h" #include "rgw_token.h" #include "rgw_b64.h" #define dout_subsys ceph_subsys_rgw namespace { using namespace rgw; using std::get; using std::string; string access_key{"Smonny"}; string secret_key{"Turjan of Miir"}; std::vector<RGWToken> tokens; std::string enc_ad{"ewogICAgIlJHV19UT0tFTiI6IHsKICAgICAgICAidmVyc2lvbiI6IDEsCiAgICAgICAgInR5cGUiOiAiYWQiLAogICAgICAgICJpZCI6ICJTbW9ubnkiLAogICAgICAgICJrZXkiOiAiVHVyamFuIG9mIE1paXIiCiAgICB9Cn0K"}; std::string enc_ldap{"ewogICAgIlJHV19UT0tFTiI6IHsKICAgICAgICAidmVyc2lvbiI6IDEsCiAgICAgICAgInR5cGUiOiAibGRhcCIsCiAgICAgICAgImlkIjogIlNtb25ueSIsCiAgICAgICAgImtleSI6ICJUdXJqYW4gb2YgTWlpciIKICAgIH0KfQo="}; std::string non_base64{"stuff here"}; std::string non_base64_sploded{"90KLscc0Dz4U49HX-7Tx"}; Formatter* token_formatter{nullptr}; bool verbose {false}; } using namespace std; TEST(TOKEN, INIT) { token_formatter = new JSONFormatter(true /* pretty */); ASSERT_NE(token_formatter, nullptr); } TEST(TOKEN, ENCODE) { // encode the two supported types RGWToken token_ad(RGWToken::TOKEN_AD, access_key, secret_key); ASSERT_EQ(token_ad.encode_json_base64(token_formatter), enc_ad); tokens.push_back(token_ad); // provies copiable RGWToken token_ldap(RGWToken::TOKEN_LDAP, access_key, secret_key); ASSERT_EQ(token_ldap.encode_json_base64(token_formatter), enc_ldap); tokens.push_back(token_ldap); } TEST(TOKEN, DECODE) { for (const auto& enc_tok : {enc_ad, enc_ldap}) { RGWToken token{from_base64(enc_tok)}; // decode ctor ASSERT_EQ(token.id, access_key); ASSERT_EQ(token.key, secret_key); } } TEST(TOKEN, EMPTY) { std::string empty{""}; RGWToken token{from_base64(empty)}; // decode ctor ASSERT_FALSE(token.valid()); } TEST(TOKEN, BADINPUT) { RGWToken token{from_base64(non_base64)}; // decode ctor ASSERT_FALSE(token.valid()); } TEST(TOKEN, BADINPUT2) { RGWToken token{from_base64(non_base64_sploded)}; // decode ctor ASSERT_FALSE(token.valid()); } TEST(TOKEN, BADINPUT3) { try { std::string stuff = from_base64(non_base64_sploded); // decode } catch(...) { // do nothing } ASSERT_EQ(1, 1); } TEST(TOKEN, SHUTDOWN) { delete token_formatter; } int main(int argc, char *argv[]) { auto args = argv_to_vec(argc, argv); env_to_vec(args); string val; for (auto arg_iter = args.begin(); arg_iter != args.end();) { if (ceph_argparse_flag(args, arg_iter, "--verbose", (char*) nullptr)) { verbose = true; } else { ++arg_iter; } } ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
3,222
24.784
203
cc
null
ceph-main/src/test/test_rw.sh
#!/usr/bin/env bash set -x # # Generic read/write from object store test # # Includes source "`dirname $0`/test_common.sh" TEST_POOL=rbd # Functions my_write_objects() { write_objects $1 $2 10 1000000 $TEST_POOL } setup() { export CEPH_NUM_OSD=$1 # Start ceph ./stop.sh ./vstart.sh -d -n || die "vstart.sh failed" } read_write_1_impl() { write_objects 1 2 100 8192 $TEST_POOL read_objects 2 100 8192 write_objects 3 3 10 81920 $TEST_POOL read_objects 3 10 81920 write_objects 4 4 100 4 $TEST_POOL read_objects 4 100 4 write_objects 1 2 100 8192 $TEST_POOL read_objects 2 100 8192 # success return 0 } read_write_1() { setup 3 read_write_1_impl } run() { read_write_1 || die "test failed" } $@
854
14.833333
51
sh
null
ceph-main/src/test/test_snap_mapper.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- #include <iterator> #include <map> #include <set> #include <boost/scoped_ptr.hpp> #include <sys/types.h> #include <cstdlib> #include "include/buffer.h" #include "common/map_cacher.hpp" #include "osd/osd_types_fmt.h" #include "osd/SnapMapper.h" #include "common/Cond.h" #include "gtest/gtest.h" using namespace std; template <typename T> typename T::iterator rand_choose(T &cont) { if (std::empty(cont)) { return std::end(cont); } return std::next(std::begin(cont), rand() % cont.size()); } string random_string(size_t size) { string name; for (size_t j = 0; j < size; ++j) { name.push_back('a' + (rand() % 26)); } return name; } class PausyAsyncMap : public MapCacher::StoreDriver<string, bufferlist> { struct _Op { virtual void operate(map<string, bufferlist> *store) = 0; virtual ~_Op() {} }; typedef std::shared_ptr<_Op> Op; struct Remove : public _Op { set<string> to_remove; explicit Remove(const set<string> &to_remove) : to_remove(to_remove) {} void operate(map<string, bufferlist> *store) override { for (set<string>::iterator i = to_remove.begin(); i != to_remove.end(); ++i) { store->erase(*i); } } }; struct Insert : public _Op { map<string, bufferlist> to_insert; explicit Insert(const map<string, bufferlist> &to_insert) : to_insert(to_insert) {} void operate(map<string, bufferlist> *store) override { for (map<string, bufferlist>::iterator i = to_insert.begin(); i != to_insert.end(); ++i) { store->erase(i->first); store->insert(*i); } } }; struct Callback : public _Op { Context *context; explicit Callback(Context *c) : context(c) {} void operate(map<string, bufferlist> *store) override { context->complete(0); } }; public: class Transaction : public MapCacher::Transaction<string, bufferlist> { friend class PausyAsyncMap; list<Op> ops; list<Op> callbacks; public: void set_keys(const map<string, bufferlist> &i) override { ops.push_back(Op(new Insert(i))); } void remove_keys(const set<string> &r) override { ops.push_back(Op(new Remove(r))); } void add_callback(Context *c) override { callbacks.push_back(Op(new Callback(c))); } }; private: ceph::mutex lock = ceph::make_mutex("PausyAsyncMap"); map<string, bufferlist> store; class Doer : public Thread { static const size_t MAX_SIZE = 100; PausyAsyncMap *parent; ceph::mutex lock = ceph::make_mutex("Doer lock"); ceph::condition_variable cond; int stopping; bool paused; list<Op> queue; public: explicit Doer(PausyAsyncMap *parent) : parent(parent), stopping(0), paused(false) {} void *entry() override { while (1) { list<Op> ops; { std::unique_lock l{lock}; cond.wait(l, [this] { return stopping || (!queue.empty() && !paused); }); if (stopping && queue.empty()) { stopping = 2; cond.notify_all(); return 0; } ceph_assert(!queue.empty()); ceph_assert(!paused); ops.swap(queue); cond.notify_all(); } ceph_assert(!ops.empty()); for (list<Op>::iterator i = ops.begin(); i != ops.end(); ops.erase(i++)) { if (!(rand()%3)) usleep(1+(rand() % 5000)); std::lock_guard l{parent->lock}; (*i)->operate(&(parent->store)); } } } void pause() { std::lock_guard l{lock}; paused = true; cond.notify_all(); } void resume() { std::lock_guard l{lock}; paused = false; cond.notify_all(); } void submit(list<Op> &in) { std::unique_lock l{lock}; cond.wait(l, [this] { return queue.size() < MAX_SIZE;}); queue.splice(queue.end(), in, in.begin(), in.end()); cond.notify_all(); } void stop() { std::unique_lock l{lock}; stopping = 1; cond.notify_all(); cond.wait(l, [this] { return stopping == 2; }); cond.notify_all(); } } doer; public: PausyAsyncMap() : doer(this) { doer.create("doer"); } ~PausyAsyncMap() override { doer.join(); } int get_keys( const set<string> &keys, map<string, bufferlist> *out) override { std::lock_guard l{lock}; for (set<string>::const_iterator i = keys.begin(); i != keys.end(); ++i) { map<string, bufferlist>::iterator j = store.find(*i); if (j != store.end()) out->insert(*j); } return 0; } int get_next( const string &key, pair<string, bufferlist> *next) override { std::lock_guard l{lock}; map<string, bufferlist>::iterator j = store.upper_bound(key); if (j != store.end()) { if (next) *next = *j; return 0; } else { return -ENOENT; } } int get_next_or_current( const string &key, pair<string, bufferlist> *next_or_current) override { std::lock_guard l{lock}; map<string, bufferlist>::iterator j = store.lower_bound(key); if (j != store.end()) { if (next_or_current) *next_or_current = *j; return 0; } else { return -ENOENT; } } void submit(Transaction *t) { doer.submit(t->ops); doer.submit(t->callbacks); } void flush() { ceph::mutex lock = ceph::make_mutex("flush lock"); ceph::condition_variable cond; bool done = false; class OnFinish : public Context { ceph::mutex *lock; ceph::condition_variable *cond; bool *done; public: OnFinish(ceph::mutex *lock, ceph::condition_variable *cond, bool *done) : lock(lock), cond(cond), done(done) {} void finish(int) override { std::lock_guard l{*lock}; *done = true; cond->notify_all(); } }; Transaction t; t.add_callback(new OnFinish(&lock, &cond, &done)); submit(&t); { std::unique_lock l{lock}; cond.wait(l, [&] { return done; }); } } void pause() { doer.pause(); } void resume() { doer.resume(); } void stop() { doer.stop(); } }; class MapCacherTest : public ::testing::Test { protected: boost::scoped_ptr< PausyAsyncMap > driver; boost::scoped_ptr<MapCacher::MapCacher<string, bufferlist> > cache; map<string, bufferlist> truth; set<string> names; public: void assert_bl_eq(bufferlist &bl1, bufferlist &bl2) { ASSERT_EQ(bl1.length(), bl2.length()); bufferlist::iterator j = bl2.begin(); for (bufferlist::iterator i = bl1.begin(); !i.end(); ++i, ++j) { ASSERT_TRUE(!j.end()); ASSERT_EQ(*i, *j); } } void assert_bl_map_eq(map<string, bufferlist> &m1, map<string, bufferlist> &m2) { ASSERT_EQ(m1.size(), m2.size()); map<string, bufferlist>::iterator j = m2.begin(); for (map<string, bufferlist>::iterator i = m1.begin(); i != m1.end(); ++i, ++j) { ASSERT_TRUE(j != m2.end()); ASSERT_EQ(i->first, j->first); assert_bl_eq(i->second, j->second); } } size_t random_num() { return random() % 10; } size_t random_size() { return random() % 1000; } void random_bl(size_t size, bufferlist *bl) { for (size_t i = 0; i < size; ++i) { bl->append(rand()); } } void do_set() { size_t set_size = random_num(); map<string, bufferlist> to_set; for (size_t i = 0; i < set_size; ++i) { bufferlist bl; random_bl(random_size(), &bl); string key = *rand_choose(names); to_set.insert( make_pair(key, bl)); } for (map<string, bufferlist>::iterator i = to_set.begin(); i != to_set.end(); ++i) { truth.erase(i->first); truth.insert(*i); } { PausyAsyncMap::Transaction t; cache->set_keys(to_set, &t); driver->submit(&t); } } void remove() { size_t remove_size = random_num(); set<string> to_remove; for (size_t i = 0; i < remove_size ; ++i) { to_remove.insert(*rand_choose(names)); } for (set<string>::iterator i = to_remove.begin(); i != to_remove.end(); ++i) { truth.erase(*i); } { PausyAsyncMap::Transaction t; cache->remove_keys(to_remove, &t); driver->submit(&t); } } void get() { set<string> to_get; size_t get_size = random_num(); for (size_t i = 0; i < get_size; ++i) { to_get.insert(*rand_choose(names)); } map<string, bufferlist> got_truth; for (set<string>::iterator i = to_get.begin(); i != to_get.end(); ++i) { map<string, bufferlist>::iterator j = truth.find(*i); if (j != truth.end()) got_truth.insert(*j); } map<string, bufferlist> got; cache->get_keys(to_get, &got); assert_bl_map_eq(got, got_truth); } void get_next() { string cur; while (true) { pair<string, bufferlist> next; int r = cache->get_next(cur, &next); pair<string, bufferlist> next_truth; map<string, bufferlist>::iterator i = truth.upper_bound(cur); int r_truth = (i == truth.end()) ? -ENOENT : 0; if (i != truth.end()) next_truth = *i; ASSERT_EQ(r, r_truth); if (r == -ENOENT) break; ASSERT_EQ(next.first, next_truth.first); assert_bl_eq(next.second, next_truth.second); cur = next.first; } } void SetUp() override { driver.reset(new PausyAsyncMap()); cache.reset(new MapCacher::MapCacher<string, bufferlist>(driver.get())); names.clear(); truth.clear(); size_t names_size(random_num() + 10); for (size_t i = 0; i < names_size; ++i) { names.insert(random_string(1 + (random_size() % 10))); } } void TearDown() override { driver->stop(); cache.reset(); driver.reset(); } }; TEST_F(MapCacherTest, Simple) { driver->pause(); map<string, bufferlist> truth; set<string> truth_keys; string blah("asdf"); bufferlist bl; encode(blah, bl); truth[string("asdf")] = bl; truth_keys.insert(truth.begin()->first); { PausyAsyncMap::Transaction t; cache->set_keys(truth, &t); driver->submit(&t); cache->set_keys(truth, &t); driver->submit(&t); } map<string, bufferlist> got; cache->get_keys(truth_keys, &got); assert_bl_map_eq(got, truth); driver->resume(); sleep(1); got.clear(); cache->get_keys(truth_keys, &got); assert_bl_map_eq(got, truth); } TEST_F(MapCacherTest, Random) { for (size_t i = 0; i < 5000; ++i) { if (!(i % 50)) { std::cout << "On iteration " << i << std::endl; } switch (rand() % 4) { case 0: get(); break; case 1: do_set(); break; case 2: get_next(); break; case 3: remove(); break; } } } class MapperVerifier { PausyAsyncMap *driver; boost::scoped_ptr< SnapMapper > mapper; map<snapid_t, set<hobject_t> > snap_to_hobject; map<hobject_t, set<snapid_t>> hobject_to_snap; snapid_t next; uint32_t mask; uint32_t bits; ceph::mutex lock = ceph::make_mutex("lock"); public: MapperVerifier( PausyAsyncMap *driver, uint32_t mask, uint32_t bits) : driver(driver), mapper(new SnapMapper(g_ceph_context, driver, mask, bits, 0, shard_id_t(1))), mask(mask), bits(bits) {} hobject_t random_hobject() { return hobject_t( random_string(1+(rand() % 16)), random_string(1+(rand() % 16)), snapid_t(rand() % 1000), (rand() & ((~0)<<bits)) | (mask & ~((~0)<<bits)), 0, random_string(rand() % 16)); } void choose_random_snaps(int num, set<snapid_t> *snaps) { ceph_assert(snaps); ceph_assert(!snap_to_hobject.empty()); for (int i = 0; i < num || snaps->empty(); ++i) { snaps->insert(rand_choose(snap_to_hobject)->first); } } void create_snap() { snap_to_hobject[next]; ++next; } void create_object() { std::lock_guard l{lock}; if (snap_to_hobject.empty()) return; hobject_t obj; do { obj = random_hobject(); } while (hobject_to_snap.count(obj)); set<snapid_t> &snaps = hobject_to_snap[obj]; choose_random_snaps(1 + (rand() % 20), &snaps); for (set<snapid_t>::iterator i = snaps.begin(); i != snaps.end(); ++i) { map<snapid_t, set<hobject_t> >::iterator j = snap_to_hobject.find(*i); ceph_assert(j != snap_to_hobject.end()); j->second.insert(obj); } { PausyAsyncMap::Transaction t; mapper->add_oid(obj, snaps, &t); driver->submit(&t); } } std::pair<std::string, ceph::buffer::list> to_raw( const std::pair<snapid_t, hobject_t> &to_map) { return mapper->to_raw(to_map); } std::string to_legacy_raw_key( const std::pair<snapid_t, hobject_t> &to_map) { return mapper->to_legacy_raw_key(to_map); } template <typename... Args> std::string to_object_key(Args&&... args) { return mapper->to_object_key(std::forward<Args>(args)...); } std::string to_raw_key( const std::pair<snapid_t, hobject_t> &to_map) { return mapper->to_raw_key(to_map); } template <typename... Args> std::string make_purged_snap_key(Args&&... args) { return mapper->make_purged_snap_key(std::forward<Args>(args)...); } void trim_snap() { std::lock_guard l{lock}; if (snap_to_hobject.empty()) return; map<snapid_t, set<hobject_t> >::iterator snap = rand_choose(snap_to_hobject); set<hobject_t> hobjects = snap->second; vector<hobject_t> hoids; while (mapper->get_next_objects_to_trim( snap->first, rand() % 5 + 1, &hoids) == 0) { for (auto &&hoid: hoids) { ceph_assert(!hoid.is_max()); ceph_assert(hobjects.count(hoid)); hobjects.erase(hoid); map<hobject_t, set<snapid_t>>::iterator j = hobject_to_snap.find(hoid); ceph_assert(j->second.count(snap->first)); set<snapid_t> old_snaps(j->second); j->second.erase(snap->first); { PausyAsyncMap::Transaction t; mapper->update_snaps( hoid, j->second, &old_snaps, &t); driver->submit(&t); } if (j->second.empty()) { hobject_to_snap.erase(j); } hoid = hobject_t::get_max(); } hoids.clear(); } ceph_assert(hobjects.empty()); snap_to_hobject.erase(snap); } void remove_oid() { std::lock_guard l{lock}; if (hobject_to_snap.empty()) return; map<hobject_t, set<snapid_t>>::iterator obj = rand_choose(hobject_to_snap); for (set<snapid_t>::iterator i = obj->second.begin(); i != obj->second.end(); ++i) { map<snapid_t, set<hobject_t> >::iterator j = snap_to_hobject.find(*i); ceph_assert(j->second.count(obj->first)); j->second.erase(obj->first); } { PausyAsyncMap::Transaction t; mapper->remove_oid( obj->first, &t); driver->submit(&t); } hobject_to_snap.erase(obj); } void check_oid() { std::lock_guard l{lock}; if (hobject_to_snap.empty()) return; map<hobject_t, set<snapid_t>>::iterator obj = rand_choose(hobject_to_snap); set<snapid_t> snaps; int r = mapper->get_snaps(obj->first, &snaps); ceph_assert(r == 0); ASSERT_EQ(snaps, obj->second); } }; class SnapMapperTest : public ::testing::Test { protected: boost::scoped_ptr< PausyAsyncMap > driver; map<pg_t, std::shared_ptr<MapperVerifier> > mappers; uint32_t pgnum; void SetUp() override { driver.reset(new PausyAsyncMap()); pgnum = 0; } void TearDown() override { driver->stop(); mappers.clear(); driver.reset(); } MapperVerifier &get_tester() { //return *(mappers.begin()->second); return *(rand_choose(mappers)->second); } void init(uint32_t to_set) { pgnum = to_set; for (uint32_t i = 0; i < pgnum; ++i) { pg_t pgid(i, 0); mappers[pgid].reset( new MapperVerifier( driver.get(), i, pgid.get_split_bits(pgnum) ) ); } } void run() { for (int i = 0; i < 5000; ++i) { if (!(i % 50)) std::cout << i << std::endl; switch (rand() % 5) { case 0: get_tester().create_snap(); break; case 1: get_tester().create_object(); break; case 2: get_tester().trim_snap(); break; case 3: get_tester().check_oid(); break; case 4: get_tester().remove_oid(); break; } } } }; TEST_F(SnapMapperTest, Simple) { init(1); get_tester().create_snap(); get_tester().create_object(); get_tester().trim_snap(); } TEST_F(SnapMapperTest, More) { init(1); run(); } TEST_F(SnapMapperTest, MultiPG) { init(50); run(); } // Check to_object_key against current format to detect accidental changes in encoding TEST_F(SnapMapperTest, CheckObjectKeyFormat) { init(1); // <object, test_raw_key> std::vector<std::tuple<hobject_t, std::string>> object_to_object_key({ {hobject_t{"test_object", "", 20, 0x01234567, 20, ""}, "OBJ_.1_0000000000000014.76543210.14.test%uobject.."}, {hobject_t{"test._ob.ject", "k.ey", 20, 0x01234567, 20, ""}, "OBJ_.1_0000000000000014.76543210.14.test%e%uob%eject.k%eey."}, {hobject_t{"test_object", "", 20, 0x01234567, 20, "namespace"}, "OBJ_.1_0000000000000014.76543210.14.test%uobject..namespace"}, {hobject_t{ "test_object", "", std::numeric_limits<snapid_t>::max() - 20, 0x01234567, std::numeric_limits<int64_t>::max() - 20, "namespace"}, "OBJ_.1_7FFFFFFFFFFFFFEB.76543210.ffffffffffffffec.test%uobject..namespace"} }); for (auto &[object, test_object_key]: object_to_object_key) { auto object_key = get_tester().to_object_key(object); if (object_key != test_object_key) { std::cout << object << " should be " << test_object_key << " is " << get_tester().to_object_key(object) << std::endl; } ASSERT_EQ(object_key, test_object_key); } } // Check to_raw_key against current format to detect accidental changes in encoding TEST_F(SnapMapperTest, CheckRawKeyFormat) { init(1); // <object, snapid, test_raw_key> std::vector<std::tuple<hobject_t, snapid_t, std::string>> object_to_raw_key({ {hobject_t{"test_object", "", 20, 0x01234567, 20, ""}, 25, "SNA_20_0000000000000019_.1_0000000000000014.76543210.14.test%uobject.."}, {hobject_t{"test._ob.ject", "k.ey", 20, 0x01234567, 20, ""}, 25, "SNA_20_0000000000000019_.1_0000000000000014.76543210.14.test%e%uob%eject.k%eey."}, {hobject_t{"test_object", "", 20, 0x01234567, 20, "namespace"}, 25, "SNA_20_0000000000000019_.1_0000000000000014.76543210.14.test%uobject..namespace"}, {hobject_t{ "test_object", "", std::numeric_limits<snapid_t>::max() - 20, 0x01234567, std::numeric_limits<int64_t>::max() - 20, "namespace"}, std::numeric_limits<snapid_t>::max() - 20, "SNA_9223372036854775787_FFFFFFFFFFFFFFEC_.1_7FFFFFFFFFFFFFEB.76543210.ffffffffffffffec.test%uobject..namespace"} }); for (auto &[object, snap, test_raw_key]: object_to_raw_key) { auto raw_key = get_tester().to_raw_key(std::make_pair(snap, object)); if (raw_key != test_raw_key) { std::cout << object << " " << snap << " should be " << test_raw_key << " is " << get_tester().to_raw_key(std::make_pair(snap, object)) << std::endl; } ASSERT_EQ(raw_key, test_raw_key); } } // Check make_purged_snap_key against current format to detect accidental changes // in encoding TEST_F(SnapMapperTest, CheckMakePurgedSnapKeyFormat) { init(1); // <pool, snap, test_key> std::vector<std::tuple<int64_t, snapid_t, std::string>> purged_snap_to_key({ {20, 30, "PSN__20_000000000000001e"}, {std::numeric_limits<int64_t>::max() - 20, std::numeric_limits<snapid_t>::max() - 20, "PSN__9223372036854775787_ffffffffffffffec"} }); for (auto &[pool, snap, test_key]: purged_snap_to_key) { auto raw_purged_snap_key = get_tester().make_purged_snap_key(pool, snap); if (raw_purged_snap_key != test_key) { std::cout << "<" << pool << ", " << snap << "> should be " << test_key << " is " << raw_purged_snap_key << std::endl; } // retesting (mostly for test numbers accounting) ASSERT_EQ(raw_purged_snap_key, test_key); } } TEST_F(SnapMapperTest, LegacyKeyConvertion) { init(1); auto obj = get_tester().random_hobject(); snapid_t snapid = random() % 10; auto snap_obj = make_pair(snapid, obj); auto raw = get_tester().to_raw(snap_obj); std::string old_key = get_tester().to_legacy_raw_key(snap_obj); std::string converted_key = SnapMapper::convert_legacy_key(old_key, raw.second); std::string new_key = get_tester().to_raw_key(snap_obj); if (converted_key != new_key) { std::cout << "Converted: " << old_key << "\nTo: " << converted_key << "\nNew key: " << new_key << std::endl; } ASSERT_EQ(converted_key, new_key); } /** * 'DirectMapper' provides simple, controlled, interface to the underlying * SnapMapper. */ class DirectMapper { public: std::unique_ptr<PausyAsyncMap> driver{make_unique<PausyAsyncMap>()}; std::unique_ptr<SnapMapper> mapper; uint32_t mask; uint32_t bits; ceph::mutex lock = ceph::make_mutex("lock"); DirectMapper( uint32_t mask, uint32_t bits) : mapper(new SnapMapper(g_ceph_context, driver.get(), mask, bits, 0, shard_id_t(1))), mask(mask), bits(bits) {} hobject_t random_hobject() { return hobject_t( random_string(1+(rand() % 16)), random_string(1+(rand() % 16)), snapid_t(rand() % 1000), (rand() & ((~0)<<bits)) | (mask & ~((~0)<<bits)), 0, random_string(rand() % 16)); } void create_object(const hobject_t& obj, const set<snapid_t> &snaps) { std::lock_guard l{lock}; PausyAsyncMap::Transaction t; mapper->add_oid(obj, snaps, &t); driver->submit(&t); } std::pair<std::string, ceph::buffer::list> to_raw( const std::pair<snapid_t, hobject_t> &to_map) { return mapper->to_raw(to_map); } std::string to_legacy_raw_key( const std::pair<snapid_t, hobject_t> &to_map) { return mapper->to_legacy_raw_key(to_map); } std::string to_raw_key( const std::pair<snapid_t, hobject_t> &to_map) { return mapper->to_raw_key(to_map); } void shorten_mapping_key(snapid_t snap, const hobject_t &clone) { // calculate the relevant key std::string k = mapper->to_raw_key(snap, clone); // find the value for this key map<string, bufferlist> kvmap; auto r = mapper->backend.get_keys(set{k}, &kvmap); ASSERT_GE(r, 0); // replace the key with its shortened version PausyAsyncMap::Transaction t; mapper->backend.remove_keys(set{k}, &t); auto short_k = k.substr(0, 10); mapper->backend.set_keys(map<string, bufferlist>{{short_k, kvmap[k]}}, &t); driver->submit(&t); driver->flush(); } }; class DirectMapperTest : public ::testing::Test { public: // ctor & initialization DirectMapperTest() = default; ~DirectMapperTest() = default; void SetUp() override; void TearDown() override; protected: std::unique_ptr<DirectMapper> direct; }; void DirectMapperTest::SetUp() { direct = std::make_unique<DirectMapper>(0, 0); } void DirectMapperTest::TearDown() { direct->driver->stop(); direct->mapper.reset(); direct->driver.reset(); } TEST_F(DirectMapperTest, BasciObject) { auto obj = direct->random_hobject(); set<snapid_t> snaps{100, 200}; direct->create_object(obj, snaps); // verify that the OBJ_ & SNA_ entries are there auto osn1 = direct->mapper->get_snaps(obj); ASSERT_EQ(snaps, osn1); auto vsn1 = direct->mapper->get_snaps_check_consistency(obj); ASSERT_EQ(snaps, vsn1); } TEST_F(DirectMapperTest, CorruptedSnaRecord) { object_t base_name{"obj"}; std::string key{"key"}; hobject_t head{base_name, key, CEPH_NOSNAP, 0x17, 0, ""}; hobject_t cln1{base_name, key, 10, 0x17, 0, ""}; hobject_t cln2{base_name, key, 20, 0x17, 0, ""}; // the oldest version set<snapid_t> head_snaps{400, 500}; set<snapid_t> cln1_snaps{300}; set<snapid_t> cln2_snaps{100, 200}; PausyAsyncMap::Transaction t; direct->mapper->add_oid(head, head_snaps, &t); direct->mapper->add_oid(cln1, cln1_snaps, &t); direct->mapper->add_oid(cln2, cln2_snaps, &t); direct->driver->submit(&t); direct->driver->flush(); // verify that the OBJ_ & SNA_ entries are there { auto osn1 = direct->mapper->get_snaps(cln1); EXPECT_EQ(cln1_snaps, osn1); auto osn2 = direct->mapper->get_snaps(cln2); EXPECT_EQ(cln2_snaps, osn2); auto osnh = direct->mapper->get_snaps(head); EXPECT_EQ(head_snaps, osnh); } { auto vsn1 = direct->mapper->get_snaps_check_consistency(cln1); EXPECT_EQ(cln1_snaps, vsn1); auto vsn2 = direct->mapper->get_snaps_check_consistency(cln2); EXPECT_EQ(cln2_snaps, vsn2); auto vsnh = direct->mapper->get_snaps_check_consistency(head); EXPECT_EQ(head_snaps, vsnh); } // corrupt the SNA_ entry for cln1 direct->shorten_mapping_key(300, cln1); { auto vsnh = direct->mapper->get_snaps_check_consistency(head); EXPECT_EQ(head_snaps, vsnh); auto vsn1 = direct->mapper->get_snaps(cln1); EXPECT_EQ(cln1_snaps, vsn1); auto osn1 = direct->mapper->get_snaps_check_consistency(cln1); EXPECT_NE(cln1_snaps, osn1); auto vsn2 = direct->mapper->get_snaps_check_consistency(cln2); EXPECT_EQ(cln2_snaps, vsn2); } } ///\todo test the case of a corrupted OBJ_ entry
25,223
25.467996
116
cc
null
ceph-main/src/test/test_split.sh
#!/usr/bin/env bash set -x # # Add some objects to the data PGs, and then test splitting those PGs # # Includes source "`dirname $0`/test_common.sh" TEST_POOL=rbd # Constants my_write_objects() { write_objects $1 $2 10 1000000 $TEST_POOL } setup() { export CEPH_NUM_OSD=$1 # Start ceph ./stop.sh ./vstart.sh -d -n } get_pgp_num() { ./ceph -c ./ceph.conf osd pool get $TEST_POOL pgp_num > $TEMPDIR/pgp_num [ $? -eq 0 ] || die "failed to get pgp_num" PGP_NUM=`grep PGP_NUM $TEMPDIR/pgp_num | sed 's/.*PGP_NUM:\([ 0123456789]*\).*$/\1/'` } split1_impl() { # Write lots and lots of objects my_write_objects 1 2 get_pgp_num echo "\$PGP_NUM=$PGP_NUM" # Double the number of PGs PGP_NUM=$((PGP_NUM*2)) echo "doubling PGP_NUM to $PGP_NUM..." ./ceph -c ./ceph.conf osd pool set $TEST_POOL pgp_num $PGP_NUM sleep 30 # success return 0 } split1() { setup 2 split1_impl } many_pools() { setup 3 for i in `seq 1 3000`; do ./ceph -c ./ceph.conf osd pool create "pool${i}" 8 || die "pool create failed" done my_write_objects 1 10 } run() { split1 || die "test failed" } $@
1,299
17.84058
94
sh
null
ceph-main/src/test/test_str_list.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/str_list.h" #include "gtest/gtest.h" // SplitTest is parameterized for list/vector/set using Types = ::testing::Types<std::list<std::string>, std::vector<std::string>>; template <typename T> struct SplitTest : ::testing::Test { void test(const char* input, const char *delim, const std::list<std::string>& expected) { EXPECT_EQ(expected, get_str_list(input, delim)); } void test(const char* input, const char *delim, const std::vector<std::string>& expected) { EXPECT_EQ(expected, get_str_vec(input, delim)); } }; TYPED_TEST_SUITE(SplitTest, Types); TYPED_TEST(SplitTest, Get) { this->test("", " ", TypeParam{}); this->test(" ", " ", TypeParam{}); this->test("foo", " ", TypeParam{"foo"}); this->test("foo bar", " ", TypeParam{"foo","bar"}); this->test(" foo bar", " ", TypeParam{"foo","bar"}); this->test("foo bar ", " ", TypeParam{"foo","bar"}); this->test("foo bar ", " ", TypeParam{"foo","bar"}); // default delimiter const char *delims = ";,= \t"; this->test(" ; , = \t ", delims, TypeParam{}); this->test(" ; foo = \t ", delims, TypeParam{"foo"}); this->test("a,b,c", delims, TypeParam{"a","b","c"}); this->test("a\tb\tc\t", delims, TypeParam{"a","b","c"}); this->test("a, b, c", delims, TypeParam{"a","b","c"}); this->test("a b c", delims, TypeParam{"a","b","c"}); this->test("a=b=c", delims, TypeParam{"a","b","c"}); }
1,553
32.782609
70
cc
null
ceph-main/src/test/test_stress_watch.cc
#include "include/rados/librados.h" #include "include/rados/librados.hpp" #include "include/utime.h" #include "common/Thread.h" #include "common/Clock.h" #include "test/librados/test_cxx.h" #include "gtest/gtest.h" #include <semaphore.h> #include <errno.h> #include <map> #include <sstream> #include <iostream> #include <string> #include <atomic> #include "test/librados/testcase_cxx.h" using namespace librados; using std::map; using std::ostringstream; using std::string; static sem_t sem; static std::atomic<bool> stop_flag = { false }; class WatchNotifyTestCtx : public WatchCtx { public: void notify(uint8_t opcode, uint64_t ver, bufferlist& bl) override { sem_post(&sem); } }; #pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" struct WatcherUnwatcher : public Thread { string pool; explicit WatcherUnwatcher(string& _pool) : pool(_pool) {} void *entry() override { Rados cluster; connect_cluster_pp(cluster); while (!stop_flag) { IoCtx ioctx; cluster.ioctx_create(pool.c_str(), ioctx); uint64_t handle; WatchNotifyTestCtx watch_ctx; int r = ioctx.watch("foo", 0, &handle, &watch_ctx); if (r == 0) ioctx.unwatch("foo", handle); ioctx.close(); } return NULL; } }; typedef RadosTestParamPP WatchStress; INSTANTIATE_TEST_SUITE_P(WatchStressTests, WatchStress, ::testing::Values("", "cache")); TEST_P(WatchStress, Stress1) { ASSERT_EQ(0, sem_init(&sem, 0, 0)); Rados ncluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, ncluster)); IoCtx nioctx; ncluster.ioctx_create(pool_name.c_str(), nioctx); WatcherUnwatcher *thr = new WatcherUnwatcher(pool_name); thr->create("watcher_unwatch"); ASSERT_EQ(0, nioctx.create("foo", false)); for (unsigned i = 0; i < 75; ++i) { std::cerr << "Iteration " << i << std::endl; uint64_t handle; Rados cluster; IoCtx ioctx; WatchNotifyTestCtx ctx; connect_cluster_pp(cluster); cluster.ioctx_create(pool_name.c_str(), ioctx); ASSERT_EQ(0, ioctx.watch("foo", 0, &handle, &ctx)); bool do_blocklist = i % 2; if (do_blocklist) { cluster.test_blocklist_self(true); std::cerr << "blocklisted" << std::endl; sleep(1); } bufferlist bl2; ASSERT_EQ(0, nioctx.notify("foo", 0, bl2)); if (do_blocklist) { sleep(1); // Give a change to see an incorrect notify } else { TestAlarm alarm; sem_wait(&sem); } if (do_blocklist) { cluster.test_blocklist_self(false); } ioctx.unwatch("foo", handle); ioctx.close(); } stop_flag = true; thr->join(); nioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, ncluster)); sem_destroy(&sem); } #pragma GCC diagnostic pop #pragma GCC diagnostic warning "-Wpragmas"
2,922
22.572581
70
cc
null
ceph-main/src/test/test_striper.cc
#include "gtest/gtest.h" #include "global/global_context.h" #include "osdc/Striper.h" using namespace std; TEST(Striper, Stripe1) { file_layout_t l; l.object_size = 262144; l.stripe_unit = 4096; l.stripe_count = 3; vector<ObjectExtent> ex; Striper::file_to_extents(g_ceph_context, 1, &l, 5006035, 46419, 5006035, ex); cout << "result " << ex << std::endl; ASSERT_EQ(3u, ex.size()); ASSERT_EQ(98304u, ex[0].truncate_size); ASSERT_EQ(ex[1].offset, ex[1].truncate_size); ASSERT_EQ(94208u, ex[2].truncate_size); } TEST(Striper, EmptyPartialResult) { file_layout_t l; l.object_size = 4194304; l.stripe_unit = 4194304; l.stripe_count = 1; vector<ObjectExtent> ex; Striper::file_to_extents(g_ceph_context, 1, &l, 725549056, 131072, 72554905600, ex); cout << "ex " << ex << std::endl; ASSERT_EQ(2u, ex.size()); Striper::StripedReadResult r; bufferlist bl; r.add_partial_result(g_ceph_context, bl, ex[1].buffer_extents); bufferptr bp(65536); bp.zero(); bl.append(bp); r.add_partial_result(g_ceph_context, bl, ex[0].buffer_extents); bufferlist outbl; r.assemble_result(g_ceph_context, outbl, false); ASSERT_EQ(65536u, outbl.length()); } TEST(Striper, GetNumObj) { file_layout_t l; l.object_size = 262144; l.stripe_unit = 4096; l.stripe_count = 3; uint64_t size,numobjs; size = 6999; numobjs = Striper::get_num_objects(l, size); ASSERT_EQ(2u, numobjs); size = 793320; numobjs = Striper::get_num_objects(l, size); ASSERT_EQ(5u, numobjs); size = 805608; numobjs = Striper::get_num_objects(l, size); ASSERT_EQ(6u, numobjs); } TEST(Striper, GetFileOffset) { file_layout_t l; l.object_size = 262144; l.stripe_unit = 4096; l.stripe_count = 3; uint64_t object_no = 100; uint64_t object_off = 200000; uint64_t file_offset = Striper::get_file_offset( g_ceph_context, &l, object_no, object_off); ASSERT_EQ(26549568u, file_offset); }
1,945
20.622222
86
cc
null
ceph-main/src/test/test_subprocess.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph distributed storage system * * Copyright (C) 2015 Mirantis Inc * * Author: Mykola Golub <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * */ #include <unistd.h> #include <iostream> #include "common/SubProcess.h" #include "common/safe_io.h" #include "gtest/gtest.h" #include "common/fork_function.h" #ifdef _WIN32 // Some of the tests expect GNU binaries to be available. We'll just rely on // the ones provided by Msys (which also comes with Git for Windows). #define SHELL "bash.exe" #else #define SHELL "/bin/sh" #endif bool read_from_fd(int fd, std::string &out) { out.clear(); char buf[1024]; ssize_t n = safe_read(fd, buf, sizeof(buf) - 1); if (n < 0) return false; buf[n] = '\0'; out = buf; return true; } TEST(SubProcess, True) { SubProcess p("true"); ASSERT_EQ(p.spawn(), 0); ASSERT_EQ(p.join(), 0); ASSERT_TRUE(p.err().c_str()[0] == '\0'); } TEST(SubProcess, False) { SubProcess p("false"); ASSERT_EQ(p.spawn(), 0); ASSERT_EQ(p.join(), 1); ASSERT_FALSE(p.err().c_str()[0] == '\0'); } TEST(SubProcess, NotFound) { SubProcess p("NOTEXISTENTBINARY", SubProcess::CLOSE, SubProcess::CLOSE, SubProcess::PIPE); #ifdef _WIN32 // Windows will error out early. ASSERT_EQ(p.spawn(), -1); #else ASSERT_EQ(p.spawn(), 0); std::string buf; ASSERT_TRUE(read_from_fd(p.get_stderr(), buf)); std::cerr << "stderr: " << buf; ASSERT_EQ(p.join(), 1); std::cerr << "err: " << p.err() << std::endl; ASSERT_FALSE(p.err().c_str()[0] == '\0'); #endif } TEST(SubProcess, Echo) { SubProcess echo("echo", SubProcess::CLOSE, SubProcess::PIPE); echo.add_cmd_args("1", "2", "3", NULL); ASSERT_EQ(echo.spawn(), 0); std::string buf; ASSERT_TRUE(read_from_fd(echo.get_stdout(), buf)); std::cerr << "stdout: " << buf; ASSERT_EQ(buf, "1 2 3\n"); ASSERT_EQ(echo.join(), 0); ASSERT_TRUE(echo.err().c_str()[0] == '\0'); } TEST(SubProcess, Cat) { SubProcess cat("cat", SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE); ASSERT_EQ(cat.spawn(), 0); std::string msg("to my, trociny!"); int n = write(cat.get_stdin(), msg.c_str(), msg.size()); ASSERT_EQ(n, (int)msg.size()); cat.close_stdin(); std::string buf; ASSERT_TRUE(read_from_fd(cat.get_stdout(), buf)); std::cerr << "stdout: " << buf << std::endl; ASSERT_EQ(buf, msg); ASSERT_TRUE(read_from_fd(cat.get_stderr(), buf)); ASSERT_EQ(buf, ""); ASSERT_EQ(cat.join(), 0); ASSERT_TRUE(cat.err().c_str()[0] == '\0'); } TEST(SubProcess, CatDevNull) { SubProcess cat("cat", SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE); cat.add_cmd_arg("/dev/null"); ASSERT_EQ(cat.spawn(), 0); std::string buf; ASSERT_TRUE(read_from_fd(cat.get_stdout(), buf)); ASSERT_EQ(buf, ""); ASSERT_TRUE(read_from_fd(cat.get_stderr(), buf)); ASSERT_EQ(buf, ""); ASSERT_EQ(cat.join(), 0); ASSERT_TRUE(cat.err().c_str()[0] == '\0'); } TEST(SubProcess, Killed) { SubProcessTimed cat("cat", SubProcess::PIPE, SubProcess::PIPE); ASSERT_EQ(cat.spawn(), 0); cat.kill(); ASSERT_EQ(cat.join(), 128 + SIGTERM); std::cerr << "err: " << cat.err() << std::endl; ASSERT_FALSE(cat.err().c_str()[0] == '\0'); } #ifndef _WIN32 TEST(SubProcess, CatWithArgs) { SubProcess cat("cat", SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE); cat.add_cmd_args("/dev/stdin", "/dev/null", "/NOTEXIST", NULL); ASSERT_EQ(cat.spawn(), 0); std::string msg("Hello, Word!"); int n = write(cat.get_stdin(), msg.c_str(), msg.size()); ASSERT_EQ(n, (int)msg.size()); cat.close_stdin(); std::string buf; ASSERT_TRUE(read_from_fd(cat.get_stdout(), buf)); std::cerr << "stdout: " << buf << std::endl; ASSERT_EQ(buf, msg); ASSERT_TRUE(read_from_fd(cat.get_stderr(), buf)); std::cerr << "stderr: " << buf; ASSERT_FALSE(buf.empty()); ASSERT_EQ(cat.join(), 1); std::cerr << "err: " << cat.err() << std::endl; ASSERT_FALSE(cat.err().c_str()[0] == '\0'); } #endif TEST(SubProcess, Subshell) { SubProcess sh(SHELL, SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE); sh.add_cmd_args("-c", "sleep 0; " "cat; " "echo 'error from subshell' >&2; " SHELL " -c 'exit 13'", NULL); ASSERT_EQ(sh.spawn(), 0); std::string msg("hello via subshell"); int n = write(sh.get_stdin(), msg.c_str(), msg.size()); ASSERT_EQ(n, (int)msg.size()); sh.close_stdin(); std::string buf; ASSERT_TRUE(read_from_fd(sh.get_stdout(), buf)); std::cerr << "stdout: " << buf << std::endl; ASSERT_EQ(buf, msg); ASSERT_TRUE(read_from_fd(sh.get_stderr(), buf)); std::cerr << "stderr: " << buf; ASSERT_EQ(buf, "error from subshell\n"); ASSERT_EQ(sh.join(), 13); std::cerr << "err: " << sh.err() << std::endl; ASSERT_FALSE(sh.err().c_str()[0] == '\0'); } TEST(SubProcessTimed, True) { SubProcessTimed p("true", SubProcess::CLOSE, SubProcess::CLOSE, SubProcess::CLOSE, 10); ASSERT_EQ(p.spawn(), 0); ASSERT_EQ(p.join(), 0); ASSERT_TRUE(p.err().c_str()[0] == '\0'); } TEST(SubProcessTimed, SleepNoTimeout) { SubProcessTimed sleep("sleep", SubProcess::CLOSE, SubProcess::CLOSE, SubProcess::CLOSE, 0); sleep.add_cmd_arg("1"); ASSERT_EQ(sleep.spawn(), 0); ASSERT_EQ(sleep.join(), 0); ASSERT_TRUE(sleep.err().c_str()[0] == '\0'); } TEST(SubProcessTimed, Killed) { SubProcessTimed cat("cat", SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE, 5); ASSERT_EQ(cat.spawn(), 0); cat.kill(); std::string buf; ASSERT_TRUE(read_from_fd(cat.get_stdout(), buf)); ASSERT_TRUE(buf.empty()); ASSERT_TRUE(read_from_fd(cat.get_stderr(), buf)); ASSERT_TRUE(buf.empty()); ASSERT_EQ(cat.join(), 128 + SIGTERM); std::cerr << "err: " << cat.err() << std::endl; ASSERT_FALSE(cat.err().c_str()[0] == '\0'); } TEST(SubProcessTimed, SleepTimedout) { SubProcessTimed sleep("sleep", SubProcess::CLOSE, SubProcess::CLOSE, SubProcess::PIPE, 1); sleep.add_cmd_arg("10"); ASSERT_EQ(sleep.spawn(), 0); std::string buf; ASSERT_TRUE(read_from_fd(sleep.get_stderr(), buf)); #ifndef _WIN32 std::cerr << "stderr: " << buf; ASSERT_FALSE(buf.empty()); #endif ASSERT_EQ(sleep.join(), 128 + SIGKILL); std::cerr << "err: " << sleep.err() << std::endl; ASSERT_FALSE(sleep.err().c_str()[0] == '\0'); } TEST(SubProcessTimed, SubshellNoTimeout) { SubProcessTimed sh(SHELL, SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE, 0); sh.add_cmd_args("-c", "cat >&2", NULL); ASSERT_EQ(sh.spawn(), 0); std::string msg("the quick brown fox jumps over the lazy dog"); int n = write(sh.get_stdin(), msg.c_str(), msg.size()); ASSERT_EQ(n, (int)msg.size()); sh.close_stdin(); std::string buf; ASSERT_TRUE(read_from_fd(sh.get_stdout(), buf)); std::cerr << "stdout: " << buf << std::endl; ASSERT_TRUE(buf.empty()); ASSERT_TRUE(read_from_fd(sh.get_stderr(), buf)); std::cerr << "stderr: " << buf << std::endl; ASSERT_EQ(buf, msg); ASSERT_EQ(sh.join(), 0); ASSERT_TRUE(sh.err().c_str()[0] == '\0'); } TEST(SubProcessTimed, SubshellKilled) { SubProcessTimed sh(SHELL, SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE, 10); sh.add_cmd_args("-c", SHELL "-c cat", NULL); ASSERT_EQ(sh.spawn(), 0); std::string msg("etaoin shrdlu"); int n = write(sh.get_stdin(), msg.c_str(), msg.size()); ASSERT_EQ(n, (int)msg.size()); sh.kill(); std::string buf; ASSERT_TRUE(read_from_fd(sh.get_stderr(), buf)); ASSERT_TRUE(buf.empty()); ASSERT_EQ(sh.join(), 128 + SIGTERM); std::cerr << "err: " << sh.err() << std::endl; ASSERT_FALSE(sh.err().c_str()[0] == '\0'); } TEST(SubProcessTimed, SubshellTimedout) { SubProcessTimed sh(SHELL, SubProcess::PIPE, SubProcess::PIPE, SubProcess::PIPE, 1, SIGTERM); sh.add_cmd_args("-c", "sleep 1000& cat; NEVER REACHED", NULL); ASSERT_EQ(sh.spawn(), 0); std::string buf; #ifndef _WIN32 ASSERT_TRUE(read_from_fd(sh.get_stderr(), buf)); std::cerr << "stderr: " << buf; ASSERT_FALSE(buf.empty()); #endif ASSERT_EQ(sh.join(), 128 + SIGTERM); std::cerr << "err: " << sh.err() << std::endl; ASSERT_FALSE(sh.err().c_str()[0] == '\0'); } #ifndef _WIN32 TEST(fork_function, normal) { ASSERT_EQ(0, fork_function(10, std::cerr, [&]() { return 0; })); ASSERT_EQ(1, fork_function(10, std::cerr, [&]() { return 1; })); ASSERT_EQ(13, fork_function(10, std::cerr, [&]() { return 13; })); ASSERT_EQ(-1, fork_function(10, std::cerr, [&]() { return -1; })); ASSERT_EQ(-13, fork_function(10, std::cerr, [&]() { return -13; })); ASSERT_EQ(-ETIMEDOUT, fork_function(10, std::cerr, [&]() { return -ETIMEDOUT; })); } TEST(fork_function, timeout) { ASSERT_EQ(-ETIMEDOUT, fork_function(2, std::cerr, [&]() { sleep(60); return 0; })); ASSERT_EQ(-ETIMEDOUT, fork_function(2, std::cerr, [&]() { sleep(60); return 1; })); ASSERT_EQ(-ETIMEDOUT, fork_function(2, std::cerr, [&]() { sleep(60); return -111; })); } #endif
9,150
28.050794
94
cc
null
ceph-main/src/test/test_texttable.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2012 Inktank Storage, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/TextTable.h" #include <iostream> #include "gtest/gtest.h" #include "include/coredumpctl.h" TEST(TextTable, Alignment) { TextTable t; // test alignment // 3 5-character columns t.define_column("HEAD1", TextTable::LEFT, TextTable::LEFT); t.define_column("HEAD2", TextTable::LEFT, TextTable::CENTER); t.define_column("HEAD3", TextTable::LEFT, TextTable::RIGHT); t << "1" << 2 << 3 << TextTable::endrow; std::ostringstream oss; oss << t; ASSERT_STREQ("HEAD1 HEAD2 HEAD3\n1 2 3\n", oss.str().c_str()); } TEST(TextTable, WidenAndClearShrink) { TextTable t; t.define_column("1", TextTable::LEFT, TextTable::LEFT); // default column size is 1, widen to 5 t << "wider"; // validate wide output std::ostringstream oss; oss << t; ASSERT_STREQ("1 \nwider\n", oss.str().c_str()); oss.str(""); // reset, validate single-char width output t.clear(); t << "s"; oss << t; ASSERT_STREQ("1\ns\n", oss.str().c_str()); } TEST(TextTable, Indent) { TextTable t; t.define_column("1", TextTable::LEFT, TextTable::LEFT); t.set_indent(10); t << "s"; std::ostringstream oss; oss << t; ASSERT_STREQ(" 1\n s\n", oss.str().c_str()); } TEST(TextTable, TooManyItems) { TextTable t; t.define_column("1", TextTable::LEFT, TextTable::LEFT); t.define_column("2", TextTable::LEFT, TextTable::LEFT); t.define_column("3", TextTable::LEFT, TextTable::LEFT); // expect assertion failure on this, which throws FailedAssertion PrCtl unset_dumpable; ASSERT_DEATH((t << "1" << "2" << "3" << "4" << TextTable::endrow), ""); }
2,036
24.78481
80
cc
null
ceph-main/src/test/test_trans.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include "common/ceph_argparse.h" #include "common/debug.h" #include "os/bluestore/BlueStore.h" #include "global/global_init.h" #include "include/ceph_assert.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_filestore #undef dout_prefix #define dout_prefix *_dout using namespace std; struct Foo : public Thread { void *entry() override { dout(0) << "foo started" << dendl; sleep(1); dout(0) << "foo asserting 0" << dendl; ceph_abort(); } } foo; int main(int argc, const char **argv) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); // args if (args.size() < 2) return -1; const char *filename = args[0]; int mb = atoi(args[1]); cout << "#dev " << filename << std::endl; cout << "#mb " << mb << std::endl; ObjectStore *fs = new BlueStore(cct.get(), filename); if (fs->mount() < 0) { cout << "mount failed" << std::endl; return -1; } ObjectStore::Transaction t; char buf[1 << 20]; bufferlist bl; bl.append(buf, sizeof(buf)); auto ch = fs->create_new_collection(coll_t()); t.create_collection(coll_t(), 0); for (int i=0; i<mb; i++) { char f[30]; snprintf(f, sizeof(f), "foo%d\n", i); sobject_t soid(f, CEPH_NOSNAP); t.write(coll_t(), ghobject_t(hobject_t(soid)), 0, bl.length(), bl); } dout(0) << "starting thread" << dendl; foo.create("foo"); dout(0) << "starting op" << dendl; fs->queue_transaction(ch, std::move(t)); }
2,052
24.345679
71
cc
null
ceph-main/src/test/test_unfound.sh
#!/usr/bin/env bash set -x # # Creates some unfound objects and then tests finding them. # # Includes source "`dirname $0`/test_common.sh" TEST_POOL=rbd # Functions my_write_objects() { write_objects $1 $2 10 1000000 $TEST_POOL } setup() { export CEPH_NUM_OSD=$1 # Start ceph ./stop.sh # set recovery start to a really long time to ensure that we don't start recovery ./vstart.sh -d -n -o 'osd recovery delay start = 10000 osd max scrubs = 0' || die "vstart failed" } osd_resurrection_1_impl() { # Write lots and lots of objects my_write_objects 1 2 # Take down osd1 stop_osd 1 # Continue writing a lot of objects my_write_objects 3 4 # Bring up osd1 restart_osd 1 # Finish peering. sleep 15 # Stop osd0. # At this point we have peered, but *NOT* recovered. # Objects should be lost. stop_osd 0 poll_cmd "./ceph pg debug unfound_objects_exist" TRUE 3 120 [ $? -eq 1 ] || die "Failed to see unfound objects." echo "Got unfound objects." ( ./rados -c ./ceph.conf -p $TEST_POOL get obj01 $TEMPDIR/obj01 || die "radostool failed" ) & sleep 5 [ -e $TEMPDIR/obj01 ] && die "unexpected error: fetched unfound object?" restart_osd 0 poll_cmd "./ceph pg debug unfound_objects_exist" FALSE 3 120 [ $? -eq 1 ] || die "Failed to recover unfound objects." wait [ -e $TEMPDIR/obj01 ] || die "unexpected error: failed to fetched newly-found object" # Turn off recovery delay start and verify that every osd gets copies # of the correct objects. echo "starting recovery..." start_recovery 2 # success return 0 } osd_resurrection_1() { setup 2 osd_resurrection_1_impl } stray_test_impl() { stop_osd 0 # 0:stopped 1:active 2:active my_write_objects 1 1 stop_osd 1 sleep 15 # 0:stopped 1:stopped(ver1) 2:active(ver1) my_write_objects 2 2 restart_osd 1 sleep 15 # 0:stopped 1:active(ver1) 2:active(ver2) stop_osd 2 sleep 15 # 0:stopped 1:active(ver1) 2:stopped(ver2) restart_osd 0 sleep 15 # 0:active 1:active(ver1) 2:stopped(ver2) poll_cmd "./ceph pg debug unfound_objects_exist" TRUE 5 300 [ $? -eq 1 ] || die "Failed to see unfound objects." # # Now, when we bring up osd2, it will be considered a stray. However, it # has the version that we need-- the very latest version of the # objects. # restart_osd 2 sleep 15 poll_cmd "./ceph pg debug unfound_objects_exist" FALSE 4 240 [ $? -eq 1 ] || die "Failed to discover unfound objects." echo "starting recovery..." start_recovery 3 # success return 0 } stray_test() { setup 3 stray_test_impl } run() { osd_resurrection_1 || die "test failed" stray_test || die "test failed" } $@
3,137
21.414286
103
sh
null
ceph-main/src/test/test_utime.cc
#include "include/utime.h" #include "gtest/gtest.h" #include "include/stringify.h" #include "common/ceph_context.h" using namespace std; TEST(utime_t, localtime) { utime_t t(1556122013, 839991182); string s = stringify(t); cout << s << std::endl; // time zone may vary where unit test is run, so be cirsumspect... ASSERT_EQ(s.size(), strlen("2019-04-24T11:06:53.839991-0500")); ASSERT_TRUE(s[26] == '-' || s[26] == '+'); ASSERT_EQ(s.substr(0, 9), "2019-04-2"); } TEST(utime_t, gmtime) { utime_t t(1556122013, 39991182); { ostringstream ss; t.gmtime(ss); ASSERT_EQ(ss.str(), "2019-04-24T16:06:53.039991Z"); } { ostringstream ss; t.gmtime_nsec(ss); ASSERT_EQ(ss.str(), "2019-04-24T16:06:53.039991182Z"); } } TEST(utime_t, asctime) { utime_t t(1556122013, 839991182); ostringstream ss; t.asctime(ss); string s = ss.str(); ASSERT_EQ(s, "Wed Apr 24 16:06:53 2019"); } const char *v[][2] = { { "2019-04-24T16:06:53.039991Z", "2019-04-24T16:06:53.039991Z" }, { "2019-04-24 16:06:53.039991Z", "2019-04-24T16:06:53.039991Z" }, { "2019-04-24 16:06:53.039991+0000", "2019-04-24T16:06:53.039991Z" }, { "2019-04-24 16:06:53.039991-0100", "2019-04-24T17:06:53.039991Z" }, { "2019-04-24 16:06:53.039991+0430", "2019-04-24T11:36:53.039991Z" }, { "2019-04-24 16:06:53+0000", "2019-04-24T16:06:53.000000Z" }, { "2019-04-24T16:06:53-0100", "2019-04-24T17:06:53.000000Z" }, { "2019-04-24 16:06:53+0430", "2019-04-24T11:36:53.000000Z" }, { "2019-04-24", "2019-04-24T00:00:00.000000Z" }, { 0, 0 }, }; TEST(utime_t, parse_date) { for (unsigned i = 0; v[i][0]; ++i) { cout << v[i][0] << " -> " << v[i][1] << std::endl; utime_t t; bool r = t.parse(string(v[i][0])); ASSERT_TRUE(r); ostringstream ss; t.gmtime(ss); ASSERT_EQ(ss.str(), v[i][1]); } }
1,839
26.058824
71
cc
null
ceph-main/src/test/test_weighted_shuffle.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "common/weighted_shuffle.h" #include <array> #include <map> #include "gtest/gtest.h" TEST(WeightedShuffle, Basic) { std::array<char, 5> choices{'a', 'b', 'c', 'd', 'e'}; std::array<int, 5> weights{100, 50, 25, 10, 1}; std::map<char, std::array<unsigned, 5>> frequency { {'a', {0, 0, 0, 0, 0}}, {'b', {0, 0, 0, 0, 0}}, {'c', {0, 0, 0, 0, 0}}, {'d', {0, 0, 0, 0, 0}}, {'e', {0, 0, 0, 0, 0}} }; // count each element appearing in each position const int samples = 10000; std::random_device rd; for (auto i = 0; i < samples; i++) { weighted_shuffle(begin(choices), end(choices), begin(weights), end(weights), std::mt19937{rd()}); for (size_t j = 0; j < choices.size(); ++j) ++frequency[choices[j]][j]; } // verify that the probability that the nth choice is selected as the first // one is the nth weight divided by the sum of all weights const auto total_weight = std::accumulate(weights.begin(), weights.end(), 0); constexpr float epsilon = 0.02; for (unsigned i = 0; i < choices.size(); i++) { const auto& f = frequency[choices[i]]; const auto& w = weights[i]; ASSERT_NEAR(float(w) / total_weight, float(f.front()) / samples, epsilon); } }
1,340
32.525
79
cc
null
ceph-main/src/test/test_workqueue.cc
#include "gtest/gtest.h" #include "common/WorkQueue.h" #include "common/ceph_argparse.h" using namespace std; TEST(WorkQueue, StartStop) { ThreadPool tp(g_ceph_context, "foo", "tp_foo", 10, ""); tp.start(); tp.pause(); tp.pause_new(); tp.unpause(); tp.unpause(); tp.drain(); tp.stop(); } TEST(WorkQueue, Resize) { ThreadPool tp(g_ceph_context, "bar", "tp_bar", 2, "filestore_op_threads"); tp.start(); sleep(1); ASSERT_EQ(2, tp.get_num_threads()); g_conf().set_val("filestore op threads", "5"); g_conf().apply_changes(&cout); sleep(1); ASSERT_EQ(5, tp.get_num_threads()); g_conf().set_val("filestore op threads", "3"); g_conf().apply_changes(&cout); sleep(1); ASSERT_EQ(3, tp.get_num_threads()); g_conf().set_val("filestore op threads", "0"); g_conf().apply_changes(&cout); sleep(1); ASSERT_EQ(0, tp.get_num_threads()); g_conf().set_val("filestore op threads", "15"); g_conf().apply_changes(&cout); sleep(1); ASSERT_EQ(15, tp.get_num_threads()); g_conf().set_val("filestore op threads", "-1"); g_conf().apply_changes(&cout); sleep(1); ASSERT_EQ(15, tp.get_num_threads()); sleep(1); tp.stop(); } class twq : public ThreadPool::WorkQueue<int> { public: twq(time_t timeout, time_t suicide_timeout, ThreadPool *tp) : ThreadPool::WorkQueue<int>("test_wq", ceph::make_timespan(timeout), ceph::make_timespan(suicide_timeout), tp) {} bool _enqueue(int* item) override { return true; } void _dequeue(int* item) override { ceph_abort(); } bool _empty() override { return true; } int *_dequeue() override { return nullptr; } void _process(int *osr, ThreadPool::TPHandle &handle) override { } void _process_finish(int *osr) override { } void _clear() override { } }; TEST(WorkQueue, change_timeout){ ThreadPool tp(g_ceph_context, "bar", "tp_bar", 2, "filestore_op_threads"); tp.start(); twq wq(2, 20, &tp); // check timeout and suicide ASSERT_EQ(ceph::make_timespan(2), wq.timeout_interval.load()); ASSERT_EQ(ceph::make_timespan(20), wq.suicide_interval.load()); // change the timeout and suicide and then check them wq.set_timeout(4); wq.set_suicide_timeout(40); ASSERT_EQ(ceph::make_timespan(4), wq.timeout_interval.load()); ASSERT_EQ(ceph::make_timespan(40), wq.suicide_interval.load()); tp.stop(); }
2,428
23.535354
122
cc
null
ceph-main/src/test/test_xlist.cc
#include <algorithm> #include <iterator> #include <vector> #include "include/xlist.h" #include "gtest/gtest.h" struct Item { xlist<Item*>::item xitem; int val; explicit Item(int v) : xitem(this), val(v) {} }; class XlistTest : public testing::Test { protected: typedef xlist<Item*> ItemList; typedef std::vector<Item*> Items; typedef std::vector<ItemList::item*> Refs; Items items; // for filling up an ItemList Refs refs; void SetUp() override { for (int i = 0; i < 13; i++) { items.push_back(new Item(i)); refs.push_back(&items.back()->xitem); } } void TearDown() override { for (Items::iterator i = items.begin(); i != items.end(); ++i) { delete *i; } items.clear(); } }; TEST_F(XlistTest, capability) { ItemList list; ASSERT_TRUE(list.empty()); ASSERT_EQ(0u, list.size()); std::copy(refs.begin(), refs.end(), std::back_inserter(list)); ASSERT_EQ((size_t)list.size(), refs.size()); list.clear(); ASSERT_TRUE(list.empty()); ASSERT_EQ(0u, list.size()); } TEST_F(XlistTest, traverse) { ItemList list; std::copy(refs.begin(), refs.end(), std::back_inserter(list)); // advance until iterator::end() size_t index = 0; for (ItemList::iterator i = list.begin(); !i.end(); ++i) { ASSERT_EQ(*i, items[index]); index++; } // advance until i == v.end() index = 0; for (ItemList::iterator i = list.begin(); i != list.end(); ++i) { ASSERT_EQ(*i, items[index]); index++; } list.clear(); } TEST_F(XlistTest, move_around) { Item item1(42), item2(17); ItemList list; // only a single element in the list list.push_back(&item1.xitem); ASSERT_EQ(&item1, list.front()); ASSERT_EQ(&item1, list.back()); list.push_back(&item2.xitem); ASSERT_EQ(&item1, list.front()); ASSERT_EQ(&item2, list.back()); // move item2 to the front list.push_front(&item2.xitem); ASSERT_EQ(&item2, list.front()); ASSERT_EQ(&item1, list.back()); // and move it back list.push_back(&item2.xitem); ASSERT_EQ(&item1, list.front()); ASSERT_EQ(&item2, list.back()); list.clear(); } TEST_F(XlistTest, item_queries) { Item item(42); ItemList list; list.push_back(&item.xitem); ASSERT_TRUE(item.xitem.is_on_list()); ASSERT_EQ(&list, item.xitem.get_list()); ASSERT_TRUE(item.xitem.remove_myself()); ASSERT_FALSE(item.xitem.is_on_list()); ASSERT_TRUE(item.xitem.get_list() == NULL); } // Local Variables: // compile-command: "cd .. ; // make unittest_xlist && // ./unittest_xlist" // End:
2,540
20.352941
68
cc
null
ceph-main/src/test/testclass.cc
#include <iostream> #include <string.h> #include <stdlib.h> #include "objclass/objclass.h" CLS_VER(1,0) CLS_NAME(test) cls_handle_t h_class; cls_method_handle_t h_foo; int foo_method(cls_method_context_t ctx, char *indata, int datalen, char **outdata, int *outdatalen) { int i, r; cls_log("hello world"); cls_log("indata=%s", indata); *outdata = (char *)cls_alloc(128); for (i=0; i<strlen(indata) + 1; i++) { if (indata[i] == '0') { (*outdata)[i] = '*'; } else { (*outdata)[i] = indata[i]; } } *outdatalen = strlen(*outdata) + 1; cls_log("outdata=%s", *outdata); r = cls_call(ctx, "foo", "foo", *outdata, *outdatalen, outdata, outdatalen); return r; } static cls_deps_t depend[] = {{"foo", "1.0"}, {"bar", "1.0"}, {NULL, NULL}}; extern "C" cls_deps_t *class_deps() { return depend; }; void class_init() { cls_log("Loaded class test!"); cls_register("test", &h_class); cls_register_method(h_class, "foo", foo_method, &h_foo); return; }
1,032
16.810345
79
cc
null
ceph-main/src/test/testcrypto.cc
#include "auth/Crypto.h" #include "common/Clock.h" #include "common/config.h" #include "common/debug.h" #define dout_subsys ceph_subsys_auth #define AES_KEY_LEN 16 #define dout_context g_ceph_context using namespace std; int main(int argc, char *argv[]) { char aes_key[AES_KEY_LEN]; memset(aes_key, 0x77, sizeof(aes_key)); bufferptr keybuf(aes_key, sizeof(aes_key)); CryptoKey key(CEPH_CRYPTO_AES, ceph_clock_now(), keybuf); const char *msg="hello! this is a message\n"; char pad[16]; memset(pad, 0, 16); bufferptr ptr(msg, strlen(msg)); bufferlist enc_in; enc_in.append(ptr); enc_in.append(msg, strlen(msg)); bufferlist enc_out; std::string error; if (key.encrypt(g_ceph_context, enc_in, enc_out, &error) < 0) { ceph_assert(!error.empty()); dout(0) << "couldn't encode! error " << error << dendl; exit(1); } const char *enc_buf = enc_out.c_str(); for (unsigned i=0; i<enc_out.length(); i++) { std::cout << hex << (int)(unsigned char)enc_buf[i] << dec << " "; if (i && !(i%16)) std::cout << std::endl; } bufferlist dec_in, dec_out; dec_in = enc_out; if (key.decrypt(g_ceph_context, dec_in, dec_out, &error) < 0) { ceph_assert(!error.empty()); dout(0) << "couldn't decode! error " << error << dendl; exit(1); } dout(0) << "decoded len: " << dec_out.length() << dendl; dout(0) << "decoded msg: " << dec_out.c_str() << dendl; return 0; }
1,438
22.590164
69
cc
null
ceph-main/src/test/testkeys.cc
#include "auth/cephx/CephxKeyServer.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "common/config.h" #include "common/debug.h" #define dout_context g_ceph_context #define AES_KEY_LEN 16 using namespace std; int main(int argc, const char **argv) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); KeyRing extra; KeyServer server(g_ceph_context, &extra); generic_dout(0) << "server created" << dendl; getchar(); #if 0 char aes_key[AES_KEY_LEN]; memset(aes_key, 0x77, sizeof(aes_key)); bufferptr keybuf(aes_key, sizeof(aes_key)); CryptoKey key(CEPH_CRYPTO_AES, ceph_clock_now(), keybuf); const char *msg="hello! this is a message\n"; char pad[16]; memset(pad, 0, 16); bufferptr ptr(msg, strlen(msg)); bufferlist enc_in; enc_in.append(ptr); enc_in.append(msg, strlen(msg)); bufferlist enc_out; if (key.encrypt(enc_in, enc_out) < 0) { derr(0) << "couldn't encode!" << dendl; exit(1); } const char *enc_buf = enc_out.c_str(); for (unsigned i=0; i<enc_out.length(); i++) { std::cout << hex << (int)(unsigned char)enc_buf[i] << dec << " "; if (i && !(i%16)) std::cout << std::endl; } bufferlist dec_in, dec_out; dec_in = enc_out; if (key.decrypt(dec_in, dec_out) < 0) { derr(0) << "couldn't decode!" << dendl; } dout(0) << "decoded len: " << dec_out.length() << dendl; dout(0) << "decoded msg: " << dec_out.c_str() << dendl; return 0; #endif }
1,647
22.542857
69
cc
null
ceph-main/src/test/testmsgr.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <sys/stat.h> #include <iostream> #include <string> using namespace std; #include "common/config.h" #include "mon/MonMap.h" #include "mon/MonClient.h" #include "msg/Messenger.h" #include "messages/MPing.h" #include "common/Timer.h" #include "global/global_init.h" #include "common/ceph_argparse.h" #include <sys/types.h> #include <fcntl.h> #define dout_subsys ceph_subsys_ms Messenger *messenger = 0; ceph::mutex test_lock = ceph::make_mutex("mylock"); ceph::condition_variable cond; uint64_t received = 0; class Admin : public Dispatcher { public: Admin() : Dispatcher(g_ceph_context) { } private: bool ms_dispatch(Message *m) { //cerr << "got ping from " << m->get_source() << std::endl; dout(0) << "got ping from " << m->get_source() << dendl; test_lock.lock(); ++received; cond.notify_all(); test_lock.unlock(); m->put(); return true; } bool ms_handle_reset(Connection *con) { return false; } void ms_handle_remote_reset(Connection *con) {} bool ms_handle_refused(Connection *con) { return false; } } dispatcher; int main(int argc, const char **argv, const char *envp[]) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); dout(0) << "i am mon " << args[0] << dendl; // get monmap MonClient mc(g_ceph_context); if (mc.build_initial_monmap() < 0) return -1; // start up network int whoami = mc.monmap.get_rank(args[0]); ceph_assert(whoami >= 0); ostringstream ss; ss << mc.monmap.get_addr(whoami); std::string sss(ss.str()); g_ceph_context->_conf.set_val("public_addr", sss.c_str()); g_ceph_context->_conf.apply_changes(nullptr); std::string public_msgr_type = g_conf()->ms_public_type.empty() ? g_conf().get_val<std::string>("ms_type") : g_conf()->ms_public_type; Messenger *rank = Messenger::create(g_ceph_context, public_msgr_type, entity_name_t::MON(whoami), "tester", getpid()); int err = rank->bind(g_ceph_context->_conf->public_addr); if (err < 0) return 1; // start monitor messenger = rank; messenger->set_default_send_priority(CEPH_MSG_PRIO_HIGH); messenger->add_dispatcher_head(&dispatcher); rank->start(); int isend = 0; if (whoami == 0) isend = 100; std::unique_lock l{test_lock}; uint64_t sent = 0; while (1) { while (received + isend <= sent) { //cerr << "wait r " << received << " s " << sent << " is " << isend << std::endl; dout(0) << "wait r " << received << " s " << sent << " is " << isend << dendl; cond.wait(l); } int t = rand() % mc.get_num_mon(); if (t == whoami) continue; if (rand() % 10 == 0) { //cerr << "mark_down " << t << std::endl; dout(0) << "mark_down " << t << dendl; messenger->mark_down_addrs(mc.get_mon_addrs(t)); } //cerr << "pinging " << t << std::endl; dout(0) << "pinging " << t << dendl; messenger->send_to_mon(new MPing, mc.get_mon_addrs(t)); cerr << isend << "\t" << ++sent << "\t" << received << "\r"; } l.unlock(); // wait for messenger to finish rank->wait(); return 0; }
3,699
24.517241
136
cc
null
ceph-main/src/test/unit.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_UNIT_TEST_H #define CEPH_UNIT_TEST_H #include "include/types.h" // FIXME: ordering shouldn't be important, but right // now, this include has to come before the others. #include "common/ceph_argparse.h" #include "common/code_environment.h" #include "common/config.h" #include "global/global_context.h" #include "global/global_init.h" #include "include/msgr.h" // for CEPH_ENTITY_TYPE_CLIENT #include "gtest/gtest.h" #include <vector> /* * You only need to include this file if you are testing Ceph internal code. If * you are testing library code, the library init() interfaces will handle * initialization for you. */ int main(int argc, char **argv) { std::vector<const char*> args(argv, argv + argc); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_MON_CONFIG); common_init_finish(g_ceph_context); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #endif
1,407
27.734694
80
cc
null
ceph-main/src/test/utf8.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/utf8.h" #include "gtest/gtest.h" #include <stdint.h> TEST(IsValidUtf8, SimpleAscii) { ASSERT_EQ(0, check_utf8_cstr("Ascii ftw.")); ASSERT_EQ(0, check_utf8_cstr("")); ASSERT_EQ(0, check_utf8_cstr("B")); ASSERT_EQ(0, check_utf8_cstr("Badgers badgers badgers badgers " "mushroom mushroom")); ASSERT_EQ(0, check_utf8("foo", strlen("foo"))); } TEST(IsValidUtf8, ControlChars) { // Sadly, control characters are valid utf8... uint8_t control_chars[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d }; ASSERT_EQ(0, check_utf8((char*)control_chars, sizeof(control_chars))); } TEST(IsValidUtf8, SimpleUtf8) { uint8_t funkystr[] = { 0x66, 0xd1, 0x86, 0xd1, 0x9d, 0xd2, 0xa0, 0xd3, 0xad, 0xd3, 0xae, 0x0a }; ASSERT_EQ(0, check_utf8((char*)funkystr, sizeof(funkystr))); uint8_t valid2[] = { 0xc3, 0xb1 }; ASSERT_EQ(0, check_utf8((char*)valid2, sizeof(valid2))); } TEST(IsValidUtf8, InvalidUtf8) { uint8_t inval[] = { 0xe2, 0x28, 0xa1 }; ASSERT_NE(0, check_utf8((char*)inval, sizeof(inval))); uint8_t invalid2[] = { 0xc3, 0x28 }; ASSERT_NE(0, check_utf8((char*)invalid2, sizeof(invalid2))); } TEST(HasControlChars, HasControlChars1) { uint8_t has_control_chars[] = { 0x41, 0x01, 0x00 }; ASSERT_NE(0, check_for_control_characters_cstr((const char*)has_control_chars)); uint8_t has_control_chars2[] = { 0x7f, 0x41, 0x00 }; ASSERT_NE(0, check_for_control_characters_cstr((const char*)has_control_chars2)); char has_newline[] = "blah blah\n"; ASSERT_NE(0, check_for_control_characters_cstr(has_newline)); char no_control_chars[] = "blah blah"; ASSERT_EQ(0, check_for_control_characters_cstr(no_control_chars)); uint8_t validutf[] = { 0x66, 0xd1, 0x86, 0xd1, 0x9d, 0xd2, 0xa0, 0xd3, 0xad, 0xd3, 0xae, 0x0 }; ASSERT_EQ(0, check_for_control_characters_cstr((const char*)validutf)); }
2,326
33.731343
83
cc
null
ceph-main/src/test/vstart_wrapper.sh
#!/usr/bin/env bash # # Copyright (C) 2013 Cloudwatt <[email protected]> # Copyright (C) 2015 Red Hat <[email protected]> # # Author: Loic Dachary <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Library Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Public License for more details. # source $CEPH_ROOT/qa/standalone/ceph-helpers.sh export CEPH_VSTART_WRAPPER=1 export CEPH_DIR="${TMPDIR:-$PWD}/td/t-$CEPH_PORT" export CEPH_DEV_DIR="$CEPH_DIR/dev" export CEPH_OUT_DIR="$CEPH_DIR/out" export CEPH_ASOK_DIR="$CEPH_DIR/out" export MGR_PYTHON_PATH=$CEPH_ROOT/src/pybind/mgr function vstart_setup() { rm -fr $CEPH_DEV_DIR $CEPH_OUT_DIR mkdir -p $CEPH_DEV_DIR trap "teardown $CEPH_DIR" EXIT export LC_ALL=C # some tests are vulnerable to i18n export PATH="$(pwd):${PATH}" OBJSTORE_ARGS="" if [ "bluestore" = "${CEPH_OBJECTSTORE}" ]; then OBJSTORE_ARGS="-b" fi $CEPH_ROOT/src/vstart.sh \ --short \ $OBJSTORE_ARGS \ -o 'paxos propose interval = 0.01' \ -d -n -l || return 1 export CEPH_CONF=$CEPH_DIR/ceph.conf crit=$(expr 100 - $(ceph-conf --show-config-value mon_data_avail_crit)) if [ $(df . | perl -ne 'print if(s/.*\s(\d+)%.*/\1/)') -ge $crit ] ; then df . cat <<EOF error: not enough free disk space for mon to run The mon will shutdown with a message such as "reached critical levels of available space on local monitor storage -- shutdown!" as soon as it finds the disk has is more than ${crit}% full. This is a limit determined by ceph-conf --show-config-value mon_data_avail_crit EOF return 1 fi } function main() { teardown $CEPH_DIR vstart_setup || return 1 if CEPH_CONF=$CEPH_DIR/ceph.conf "$@"; then code=0 else code=1 display_logs $CEPH_OUT_DIR fi return $code } main "$@"
2,231
28.368421
83
sh
null
ceph-main/src/test/xattr_bench.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <stdio.h> #include <time.h> #include <string.h> #include <iostream> #include <iterator> #include <sstream> #include "os/bluestore/BlueStore.h" #include "include/Context.h" #include "common/ceph_argparse.h" #include "common/ceph_mutex.h" #include "common/Cond.h" #include "global/global_init.h" #include <boost/scoped_ptr.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/binomial_distribution.hpp> #include <gtest/gtest.h> #include "include/unordered_map.h" void usage(const string &name) { std::cerr << "Usage: " << name << " [xattr|omap] store_path" << std::endl; } const int THREADS = 5; template <typename T> typename T::iterator rand_choose(T &cont) { if (std::empty(cont) == 0) { return std::end(cont); } return std::next(std::begin(cont), rand() % cont.size()); } class OnApplied : public Context { public: ceph::mutex *lock; ceph::condition_variable *cond; int *in_progress; ObjectStore::Transaction *t; OnApplied(ceph::mutex *lock, ceph::condition_variable *cond, int *in_progress, ObjectStore::Transaction *t) : lock(lock), cond(cond), in_progress(in_progress), t(t) { std::lock_guard l{*lock}; (*in_progress)++; } void finish(int r) override { std::lock_guard l{*lock}; (*in_progress)--; cond->notify_all(); } }; uint64_t get_time() { time_t start; time(&start); return start * 1000; } double print_time(uint64_t ms) { return ((double)ms)/1000; } uint64_t do_run(ObjectStore *store, int attrsize, int numattrs, int run, int transsize, int ops, ostream &out) { ceph::mutex lock = ceph::make_mutex("lock"); ceph::condition_variable cond; int in_flight = 0; ObjectStore::Sequencer osr(__func__); ObjectStore::Transaction t; map<coll_t, pair<set<string>, ObjectStore::Sequencer*> > collections; for (int i = 0; i < 3*THREADS; ++i) { coll_t coll(spg_t(pg_t(0, i + 1000*run), shard_id_t::NO_SHARD)); t.create_collection(coll, 0); set<string> objects; for (int i = 0; i < transsize; ++i) { stringstream obj_str; obj_str << i; t.touch(coll, ghobject_t(hobject_t(sobject_t(obj_str.str(), CEPH_NOSNAP)))); objects.insert(obj_str.str()); } collections[coll] = make_pair(objects, new ObjectStore::Sequencer(coll.to_str())); } store->queue_transaction(&osr, std::move(t)); bufferlist bl; for (int i = 0; i < attrsize; ++i) { bl.append('\0'); } uint64_t start = get_time(); for (int i = 0; i < ops; ++i) { { std::unique_lock l{lock}; cond.wait(l, [&] { in_flight < THREADS; }); } ObjectStore::Transaction *t = new ObjectStore::Transaction; map<coll_t, pair<set<string>, ObjectStore::Sequencer*> >::iterator iter = rand_choose(collections); for (set<string>::iterator obj = iter->second.first.begin(); obj != iter->second.first.end(); ++obj) { for (int j = 0; j < numattrs; ++j) { stringstream ss; ss << i << ", " << j << ", " << *obj; t->setattr(iter->first, ghobject_t(hobject_t(sobject_t(*obj, CEPH_NOSNAP))), ss.str().c_str(), bl); } } store->queue_transaction(iter->second.second, std::move(*t), new OnApplied(&lock, &cond, &in_flight, t)); delete t; } { std::unique_lock l{lock}; cond.wait(l, [&] { return in_flight == 0; }); } return get_time() - start; } int main(int argc, char **argv) { auto args = argv_to_vec(argc, argv); if (args.empty()) { cerr << argv[0] << ": -h or --help for usage" << std::endl; exit(1); } if (ceph_argparse_need_usage(args)) { usage(argv[0]); exit(0); } auto cct = global_init(0, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); std::cerr << "args: " << args << std::endl; if (args.size() < 2) { usage(argv[0]); return 1; } string store_path(args[1]); boost::scoped_ptr<ObjectStore> store(new BlueStore(cct.get(), store_path)); std::cerr << "mkfs starting" << std::endl; ceph_assert(!store->mkfs()); ceph_assert(!store->mount()); std::cerr << "mounted" << std::endl; std::cerr << "attrsize\tnumattrs\ttranssize\tops\ttime" << std::endl; int runs = 0; int total_size = 11; for (int i = 6; i < total_size; ++i) { for (int j = (total_size - i); j >= 0; --j) { std::cerr << "starting run " << runs << std::endl; ++runs; uint64_t time = do_run(store.get(), (1 << i), (1 << j), runs, 10, 1000, std::cout); std::cout << (1 << i) << "\t" << (1 << j) << "\t" << 10 << "\t" << 1000 << "\t" << print_time(time) << std::endl; } } store->umount(); return 0; }
5,204
25.42132
86
cc
null
ceph-main/src/test/ObjectMap/KeyValueDBMemory.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/encoding.h" #include "KeyValueDBMemory.h" #include <map> #include <set> #include <iostream> using namespace std; /** * Iterate over the whole key space of the in-memory store * * @note Removing keys from the store while iterating over the store key-space * may result in unspecified behavior. * If one wants to safely iterate over the store while updating the * store, one should instead use a snapshot iterator, which provides * strong read-consistency. */ class WholeSpaceMemIterator : public KeyValueDB::WholeSpaceIteratorImpl { protected: KeyValueDBMemory *db; bool ready; map<pair<string,string>, bufferlist>::iterator it; public: explicit WholeSpaceMemIterator(KeyValueDBMemory *db) : db(db), ready(false) { } ~WholeSpaceMemIterator() override { } int seek_to_first() override { if (db->db.empty()) { it = db->db.end(); ready = false; return 0; } it = db->db.begin(); ready = true; return 0; } int seek_to_first(const string &prefix) override { it = db->db.lower_bound(make_pair(prefix, "")); if (db->db.empty() || (it == db->db.end())) { it = db->db.end(); ready = false; return 0; } ready = true; return 0; } int seek_to_last() override { it = db->db.end(); if (db->db.empty()) { ready = false; return 0; } --it; ceph_assert(it != db->db.end()); ready = true; return 0; } int seek_to_last(const string &prefix) override { string tmp(prefix); tmp.append(1, (char) 0); it = db->db.upper_bound(make_pair(tmp,"")); if (db->db.empty() || (it == db->db.end())) { seek_to_last(); } else { ready = true; prev(); } return 0; } int lower_bound(const string &prefix, const string &to) override { it = db->db.lower_bound(make_pair(prefix,to)); if ((db->db.empty()) || (it == db->db.end())) { it = db->db.end(); ready = false; return 0; } ceph_assert(it != db->db.end()); ready = true; return 0; } int upper_bound(const string &prefix, const string &after) override { it = db->db.upper_bound(make_pair(prefix,after)); if ((db->db.empty()) || (it == db->db.end())) { it = db->db.end(); ready = false; return 0; } ceph_assert(it != db->db.end()); ready = true; return 0; } bool valid() override { return ready && (it != db->db.end()); } bool begin() { return ready && (it == db->db.begin()); } int prev() override { if (!begin() && ready) --it; else it = db->db.end(); return 0; } int next() override { if (valid()) ++it; return 0; } string key() override { if (valid()) return (*it).first.second; else return ""; } pair<string,string> raw_key() override { if (valid()) return (*it).first; else return make_pair("", ""); } bool raw_key_is_prefixed(const string &prefix) override { return prefix == (*it).first.first; } bufferlist value() override { if (valid()) return (*it).second; else return bufferlist(); } int status() override { return 0; } }; int KeyValueDBMemory::get(const string &prefix, const std::set<string> &key, map<string, bufferlist> *out) { if (!exists_prefix(prefix)) return 0; for (std::set<string>::const_iterator i = key.begin(); i != key.end(); ++i) { pair<string,string> k(prefix, *i); if (db.count(k)) (*out)[*i] = db[k]; } return 0; } int KeyValueDBMemory::get_keys(const string &prefix, const std::set<string> &key, std::set<string> *out) { if (!exists_prefix(prefix)) return 0; for (std::set<string>::const_iterator i = key.begin(); i != key.end(); ++i) { if (db.count(make_pair(prefix, *i))) out->insert(*i); } return 0; } int KeyValueDBMemory::set(const string &prefix, const string &key, const bufferlist &bl) { db[make_pair(prefix,key)] = bl; return 0; } int KeyValueDBMemory::rmkey(const string &prefix, const string &key) { db.erase(make_pair(prefix,key)); return 0; } int KeyValueDBMemory::rmkeys_by_prefix(const string &prefix) { map<std::pair<string,string>,bufferlist>::iterator i; i = db.lower_bound(make_pair(prefix, "")); if (i == db.end()) return 0; while (i != db.end()) { std::pair<string,string> key = (*i).first; if (key.first != prefix) break; ++i; rmkey(key.first, key.second); } return 0; } int KeyValueDBMemory::rm_range_keys(const string &prefix, const string &start, const string &end) { map<std::pair<string,string>,bufferlist>::iterator i; i = db.lower_bound(make_pair(prefix, start)); if (i == db.end()) return 0; while (i != db.end()) { std::pair<string,string> key = (*i).first; if (key.first != prefix) break; if (key.second >= end) break; ++i; rmkey(key.first, key.second); } return 0; } KeyValueDB::WholeSpaceIterator KeyValueDBMemory::get_wholespace_iterator(IteratorOpts opts) { return std::shared_ptr<KeyValueDB::WholeSpaceIteratorImpl>( new WholeSpaceMemIterator(this) ); } class WholeSpaceSnapshotMemIterator : public WholeSpaceMemIterator { public: /** * @note * We perform a copy of the db map, which is populated by bufferlists. * * These are designed as shallow containers, thus there is a chance that * changing the underlying memory pages will lead to the iterator seeing * erroneous states. * * Although we haven't verified this yet, there is this chance, so we should * keep it in mind. */ explicit WholeSpaceSnapshotMemIterator(KeyValueDBMemory *db) : WholeSpaceMemIterator(db) { } ~WholeSpaceSnapshotMemIterator() override { delete db; } };
5,982
21.577358
99
cc
null
ceph-main/src/test/ObjectMap/KeyValueDBMemory.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <map> #include <set> #include <string> #include "kv/KeyValueDB.h" #include "include/buffer.h" #include "include/Context.h" using std::string; class KeyValueDBMemory : public KeyValueDB { public: std::map<std::pair<string,string>,bufferlist> db; KeyValueDBMemory() { } explicit KeyValueDBMemory(KeyValueDBMemory *db) : db(db->db) { } ~KeyValueDBMemory() override { } int init(string _opt) override { return 0; } int open(std::ostream &out, const std::string& cfs="") override { return 0; } int create_and_open(std::ostream &out, const std::string& cfs="") override { return 0; } int get( const std::string &prefix, const std::set<std::string> &key, std::map<std::string, bufferlist> *out ) override; using KeyValueDB::get; int get_keys( const std::string &prefix, const std::set<std::string> &key, std::set<std::string> *out ); int set( const std::string &prefix, const std::string &key, const bufferlist &bl ); int rmkey( const std::string &prefix, const std::string &key ); int rmkeys_by_prefix( const std::string &prefix ); int rm_range_keys( const std::string &prefix, const std::string &start, const std::string &end ); class TransactionImpl_ : public TransactionImpl { public: std::list<Context *> on_commit; KeyValueDBMemory *db; explicit TransactionImpl_(KeyValueDBMemory *db) : db(db) {} struct SetOp : public Context { KeyValueDBMemory *db; std::pair<std::string,std::string> key; bufferlist value; SetOp(KeyValueDBMemory *db, const std::pair<std::string,std::string> &key, const bufferlist &value) : db(db), key(key), value(value) {} void finish(int r) override { db->set(key.first, key.second, value); } }; void set(const std::string &prefix, const std::string &k, const bufferlist& bl) override { on_commit.push_back(new SetOp(db, std::make_pair(prefix, k), bl)); } struct RmKeysOp : public Context { KeyValueDBMemory *db; std::pair<std::string,std::string> key; RmKeysOp(KeyValueDBMemory *db, const std::pair<std::string,std::string> &key) : db(db), key(key) {} void finish(int r) override { db->rmkey(key.first, key.second); } }; using KeyValueDB::TransactionImpl::rmkey; using KeyValueDB::TransactionImpl::set; void rmkey(const std::string &prefix, const std::string &key) override { on_commit.push_back(new RmKeysOp(db, std::make_pair(prefix, key))); } struct RmKeysByPrefixOp : public Context { KeyValueDBMemory *db; std::string prefix; RmKeysByPrefixOp(KeyValueDBMemory *db, const std::string &prefix) : db(db), prefix(prefix) {} void finish(int r) override { db->rmkeys_by_prefix(prefix); } }; void rmkeys_by_prefix(const std::string &prefix) override { on_commit.push_back(new RmKeysByPrefixOp(db, prefix)); } struct RmRangeKeys: public Context { KeyValueDBMemory *db; std::string prefix, start, end; RmRangeKeys(KeyValueDBMemory *db, const std::string &prefix, const std::string &s, const std::string &e) : db(db), prefix(prefix), start(s), end(e) {} void finish(int r) { db->rm_range_keys(prefix, start, end); } }; void rm_range_keys(const std::string &prefix, const std::string &start, const std::string &end) { on_commit.push_back(new RmRangeKeys(db, prefix, start, end)); } int complete() { for (auto i = on_commit.begin(); i != on_commit.end(); on_commit.erase(i++)) { (*i)->complete(0); } return 0; } ~TransactionImpl_() override { for (auto i = on_commit.begin(); i != on_commit.end(); on_commit.erase(i++)) { delete *i; } } }; Transaction get_transaction() override { return Transaction(new TransactionImpl_(this)); } int submit_transaction(Transaction trans) override { return static_cast<TransactionImpl_*>(trans.get())->complete(); } uint64_t get_estimated_size(std::map<std::string,uint64_t> &extras) override { uint64_t total_size = 0; for (auto& [key, bl] : db) { string prefix = key.first; uint64_t sz = bl.length(); total_size += sz; if (extras.count(prefix) == 0) extras[prefix] = 0; extras[prefix] += sz; } return total_size; } private: bool exists_prefix(const std::string &prefix) { std::map<std::pair<std::string,std::string>,bufferlist>::iterator it; it = db.lower_bound(std::make_pair(prefix, "")); return ((it != db.end()) && ((*it).first.first == prefix)); } friend class WholeSpaceMemIterator; public: WholeSpaceIterator get_wholespace_iterator(IteratorOpts opts = 0) override; };
4,938
25.132275
110
h
null
ceph-main/src/test/ObjectMap/test_keyvaluedb_atomicity.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- #include <pthread.h> #include "include/buffer.h" #include "kv/KeyValueDB.h" #include <sys/types.h> #include <dirent.h> #include <string> #include <vector> #include <boost/scoped_ptr.hpp> #include <iostream> #include <sstream> #include "stdlib.h" #include "global/global_context.h" #include "global/global_init.h" using namespace std; const string CONTROL_PREFIX = "CONTROL"; const string PRIMARY_PREFIX = "PREFIX"; const int NUM_COPIES = 100; const int NUM_THREADS = 30; string prefix_gen(int i) { stringstream ss; ss << PRIMARY_PREFIX << "_" << i << std::endl; return ss.str(); } int verify(KeyValueDB *db) { // Verify { map<int, KeyValueDB::Iterator> iterators; for (int i = 0; i < NUM_COPIES; ++i) { iterators[i] = db->get_iterator(prefix_gen(i)); iterators[i]->seek_to_first(); } while (iterators.rbegin()->second->valid()) { for (map<int, KeyValueDB::Iterator>::iterator i = iterators.begin(); i != iterators.end(); ++i) { ceph_assert(i->second->valid()); ceph_assert(i->second->key() == iterators.rbegin()->second->key()); bufferlist r = i->second->value(); bufferlist l = iterators.rbegin()->second->value(); i->second->next(); } } for (map<int, KeyValueDB::Iterator>::iterator i = iterators.begin(); i != iterators.end(); ++i) { ceph_assert(!i->second->valid()); } } return 0; } void *write(void *_db) { KeyValueDB *db = static_cast<KeyValueDB*>(_db); std::cout << "Writing..." << std::endl; for (int i = 0; i < 12000; ++i) { if (!(i % 10)) { std::cout << "Iteration: " << i << std::endl; } int key_num = rand(); stringstream key; key << key_num << std::endl; map<string, bufferlist> to_set; stringstream val; val << i << std::endl; bufferptr bp(val.str().c_str(), val.str().size() + 1); to_set[key.str()].push_back(bp); KeyValueDB::Transaction t = db->get_transaction(); for (int j = 0; j < NUM_COPIES; ++j) { t->set(prefix_gen(j), to_set); } ceph_assert(!db->submit_transaction(t)); } return 0; } int main() { char *path = getenv("OBJECT_MAP_PATH"); boost::scoped_ptr< KeyValueDB > db; if (!path) { std::cerr << "No path found, OBJECT_MAP_PATH undefined" << std::endl; return 0; } string strpath(path); std::cerr << "Using path: " << strpath << std::endl; std::vector<const char*> args; auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); KeyValueDB *store = KeyValueDB::create(g_ceph_context, "rocksdb", strpath); ceph_assert(!store->create_and_open(std::cerr)); db.reset(store); verify(db.get()); vector<pthread_t> threads(NUM_THREADS); for (vector<pthread_t>::iterator i = threads.begin(); i != threads.end(); ++i) { pthread_create(&*i, 0, &write, static_cast<void *>(db.get())); } for (vector<pthread_t>::iterator i = threads.begin(); i != threads.end(); ++i) { void *tmp; pthread_join(*i, &tmp); } verify(db.get()); }
3,191
26.282051
77
cc
null
ceph-main/src/test/ObjectMap/test_keyvaluedb_iterators.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2012 Inktank, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #include <map> #include <set> #include <deque> #include <boost/scoped_ptr.hpp> #include "test/ObjectMap/KeyValueDBMemory.h" #include "kv/KeyValueDB.h" #include <sys/types.h> #include "global/global_init.h" #include "common/ceph_argparse.h" #include "gtest/gtest.h" using namespace std; string store_path; class IteratorTest : public ::testing::Test { public: boost::scoped_ptr<KeyValueDB> db; boost::scoped_ptr<KeyValueDBMemory> mock; void SetUp() override { ceph_assert(!store_path.empty()); KeyValueDB *db_ptr = KeyValueDB::create(g_ceph_context, "rocksdb", store_path); ceph_assert(!db_ptr->create_and_open(std::cerr)); db.reset(db_ptr); mock.reset(new KeyValueDBMemory()); } void TearDown() override { } ::testing::AssertionResult validate_db_clear(KeyValueDB *store) { KeyValueDB::WholeSpaceIterator it = store->get_wholespace_iterator(); it->seek_to_first(); while (it->valid()) { pair<string,string> k = it->raw_key(); if (mock->db.count(k)) { return ::testing::AssertionFailure() << __func__ << " mock store count " << mock->db.count(k) << " key(" << k.first << "," << k.second << ")"; } it->next(); } return ::testing::AssertionSuccess(); } ::testing::AssertionResult validate_db_match() { KeyValueDB::WholeSpaceIterator it = db->get_wholespace_iterator(); it->seek_to_first(); while (it->valid()) { pair<string, string> k = it->raw_key(); if (!mock->db.count(k)) { return ::testing::AssertionFailure() << __func__ << " mock db.count() " << mock->db.count(k) << " key(" << k.first << "," << k.second << ")"; } bufferlist it_bl = it->value(); bufferlist mock_bl = mock->db[k]; string it_val = _bl_to_str(it_bl); string mock_val = _bl_to_str(mock_bl); if (it_val != mock_val) { return ::testing::AssertionFailure() << __func__ << " key(" << k.first << "," << k.second << ")" << " mismatch db value(" << it_val << ")" << " mock value(" << mock_val << ")"; } it->next(); } return ::testing::AssertionSuccess(); } ::testing::AssertionResult validate_iterator( KeyValueDB::WholeSpaceIterator it, string expected_prefix, const string &expected_key, const string &expected_value) { if (!it->valid()) { return ::testing::AssertionFailure() << __func__ << " iterator not valid"; } if (!it->raw_key_is_prefixed(expected_prefix)) { return ::testing::AssertionFailure() << __func__ << " expected raw_key_is_prefixed() == TRUE" << " got FALSE"; } if (it->raw_key_is_prefixed("??__SomeUnexpectedValue__??")) { return ::testing::AssertionFailure() << __func__ << " expected raw_key_is_prefixed() == FALSE" << " got TRUE"; } pair<string,string> key = it->raw_key(); if (expected_prefix != key.first) { return ::testing::AssertionFailure() << __func__ << " expected prefix '" << expected_prefix << "'" << " got prefix '" << key.first << "'"; } if (expected_key != it->key()) { return ::testing::AssertionFailure() << __func__ << " expected key '" << expected_key << "'" << " got key '" << it->key() << "'"; } if (it->key() != key.second) { return ::testing::AssertionFailure() << __func__ << " key '" << it->key() << "'" << " does not match" << " pair key '" << key.second << "'"; } if (_bl_to_str(it->value()) != expected_value) { return ::testing::AssertionFailure() << __func__ << " key '(" << key.first << "," << key.second << ")''" << " expected value '" << expected_value << "'" << " got value '" << _bl_to_str(it->value()) << "'"; } return ::testing::AssertionSuccess(); } /** * Checks if each key in the queue can be forward sequentially read from * the iterator iter. All keys must be present and be prefixed with prefix, * otherwise the validation will fail. * * Assumes that each key value must be based on the key name and generated * by _gen_val(). */ void validate_prefix(KeyValueDB::WholeSpaceIterator iter, string &prefix, deque<string> &keys) { while (!keys.empty()) { ASSERT_TRUE(iter->valid()); string expected_key = keys.front(); keys.pop_front(); string expected_value = _gen_val_str(expected_key); ASSERT_TRUE(validate_iterator(iter, prefix, expected_key, expected_value)); iter->next(); } } /** * Checks if each key in the queue can be backward sequentially read from * the iterator iter. All keys must be present and be prefixed with prefix, * otherwise the validation will fail. * * Assumes that each key value must be based on the key name and generated * by _gen_val(). */ void validate_prefix_backwards(KeyValueDB::WholeSpaceIterator iter, string &prefix, deque<string> &keys) { while (!keys.empty()) { ASSERT_TRUE(iter->valid()); string expected_key = keys.front(); keys.pop_front(); string expected_value = _gen_val_str(expected_key); ASSERT_TRUE(validate_iterator(iter, prefix, expected_key, expected_value)); iter->prev(); } } void clear(KeyValueDB *store) { KeyValueDB::WholeSpaceIterator it = store->get_wholespace_iterator(); it->seek_to_first(); KeyValueDB::Transaction t = store->get_transaction(); while (it->valid()) { pair<string,string> k = it->raw_key(); t->rmkey(k.first, k.second); it->next(); } store->submit_transaction_sync(t); } string _bl_to_str(bufferlist val) { string str(val.c_str(), val.length()); return str; } string _gen_val_str(const string &key) { ostringstream ss; ss << "##value##" << key << "##"; return ss.str(); } bufferlist _gen_val(const string &key) { bufferlist bl; bl.append(_gen_val_str(key)); return bl; } void print_iterator(KeyValueDB::WholeSpaceIterator iter) { if (!iter->valid()) { std::cerr << __func__ << " iterator is not valid; stop." << std::endl; return; } int i = 0; while (iter->valid()) { pair<string,string> k = iter->raw_key(); std::cerr << __func__ << " pos " << (++i) << " key (" << k.first << "," << k.second << ")" << " value(" << _bl_to_str(iter->value()) << ")" << std::endl; iter->next(); } } void print_db(KeyValueDB *store) { KeyValueDB::WholeSpaceIterator it = store->get_wholespace_iterator(); it->seek_to_first(); print_iterator(it); } }; // ------- Remove Keys / Remove Keys By Prefix ------- class RmKeysTest : public IteratorTest { public: string prefix1; string prefix2; string prefix3; void init(KeyValueDB *db) { KeyValueDB::Transaction tx = db->get_transaction(); tx->set(prefix1, "11", _gen_val("11")); tx->set(prefix1, "12", _gen_val("12")); tx->set(prefix1, "13", _gen_val("13")); tx->set(prefix2, "21", _gen_val("21")); tx->set(prefix2, "22", _gen_val("22")); tx->set(prefix2, "23", _gen_val("23")); tx->set(prefix3, "31", _gen_val("31")); tx->set(prefix3, "32", _gen_val("32")); tx->set(prefix3, "33", _gen_val("33")); db->submit_transaction_sync(tx); } void SetUp() override { IteratorTest::SetUp(); prefix1 = "_PREFIX_1_"; prefix2 = "_PREFIX_2_"; prefix3 = "_PREFIX_3_"; clear(db.get()); ASSERT_TRUE(validate_db_clear(db.get())); clear(mock.get()); ASSERT_TRUE(validate_db_match()); init(db.get()); init(mock.get()); ASSERT_TRUE(validate_db_match()); } void TearDown() override { IteratorTest::TearDown(); } /** * Test the transaction's rmkeys behavior when we remove a given prefix * from the beginning of the key space, or from the end of the key space, * or even simply in the middle. */ void RmKeysByPrefix(KeyValueDB *store) { // remove prefix2 ; check if prefix1 remains, and then prefix3 KeyValueDB::Transaction tx = store->get_transaction(); // remove the prefix in the middle of the key space tx->rmkeys_by_prefix(prefix2); store->submit_transaction_sync(tx); deque<string> key_deque; KeyValueDB::WholeSpaceIterator iter = store->get_wholespace_iterator(); iter->seek_to_first(); // check for prefix1 key_deque.push_back("11"); key_deque.push_back("12"); key_deque.push_back("13"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); // check for prefix3 ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("31"); key_deque.push_back("32"); key_deque.push_back("33"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); clear(store); ASSERT_TRUE(validate_db_clear(store)); init(store); // remove prefix1 ; check if prefix2 and then prefix3 remain tx = store->get_transaction(); // remove the prefix at the beginning of the key space tx->rmkeys_by_prefix(prefix1); store->submit_transaction_sync(tx); iter = store->get_wholespace_iterator(); iter->seek_to_first(); // check for prefix2 key_deque.clear(); key_deque.push_back("21"); key_deque.push_back("22"); key_deque.push_back("23"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); // check for prefix3 ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("31"); key_deque.push_back("32"); key_deque.push_back("33"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); clear(store); ASSERT_TRUE(validate_db_clear(store)); init(store); // remove prefix3 ; check if prefix1 and then prefix2 remain tx = store->get_transaction(); // remove the prefix at the end of the key space tx->rmkeys_by_prefix(prefix3); store->submit_transaction_sync(tx); iter = store->get_wholespace_iterator(); iter->seek_to_first(); // check for prefix1 key_deque.clear(); key_deque.push_back("11"); key_deque.push_back("12"); key_deque.push_back("13"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); // check for prefix2 ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("21"); key_deque.push_back("22"); key_deque.push_back("23"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); } /** * Test how the RocksDB's whole-space iterator behaves when we remove * keys from the store while iterating over them. */ void RmKeysWhileIteratingSnapshot(KeyValueDB *store, KeyValueDB::WholeSpaceIterator iter) { SCOPED_TRACE("RmKeysWhileIteratingSnapshot"); iter->seek_to_first(); ASSERT_TRUE(iter->valid()); KeyValueDB::Transaction t = store->get_transaction(); t->rmkey(prefix1, "11"); t->rmkey(prefix1, "12"); t->rmkey(prefix2, "23"); t->rmkey(prefix3, "33"); store->submit_transaction_sync(t); deque<string> key_deque; // check for prefix1 key_deque.push_back("11"); key_deque.push_back("12"); key_deque.push_back("13"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); // check for prefix2 key_deque.clear(); key_deque.push_back("21"); key_deque.push_back("22"); key_deque.push_back("23"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); // check for prefix3 key_deque.clear(); key_deque.push_back("31"); key_deque.push_back("32"); key_deque.push_back("33"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); iter->next(); ASSERT_FALSE(iter->valid()); // make sure those keys were removed from the store KeyValueDB::WholeSpaceIterator tmp_it = store->get_wholespace_iterator(); tmp_it->seek_to_first(); ASSERT_TRUE(tmp_it->valid()); key_deque.clear(); key_deque.push_back("13"); validate_prefix(tmp_it, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(tmp_it->valid()); key_deque.clear(); key_deque.push_back("21"); key_deque.push_back("22"); validate_prefix(tmp_it, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(tmp_it->valid()); key_deque.clear(); key_deque.push_back("31"); key_deque.push_back("32"); validate_prefix(tmp_it, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(tmp_it->valid()); } }; TEST_F(RmKeysTest, RmKeysByPrefixRocksDB) { SCOPED_TRACE("RocksDB"); RmKeysByPrefix(db.get()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(RmKeysTest, RmKeysByPrefixMockDB) { SCOPED_TRACE("Mock DB"); RmKeysByPrefix(mock.get()); ASSERT_FALSE(HasFatalFailure()); } /** * If you refer to function RmKeysTest::RmKeysWhileIteratingSnapshot(), * you will notice that we seek the iterator to the first key, and then * we go on to remove several keys from the underlying store, including * the first couple keys. * * We would expect that during this test, as soon as we removed the keys * from the store, the iterator would get invalid, or cause some sort of * unexpected mess. * * Instead, the current version of RocksDB handles it perfectly, by making * the iterator to use a snapshot instead of the store's real state. This * way, RocksDBStore's whole-space iterator will behave much like its own * whole-space snapshot iterator. * * However, this particular behavior of the iterator hasn't been documented * on RocksDB, and we should assume that it can be changed at any point in * time. * * Therefore, we keep this test, being exactly the same as the one for the * whole-space snapshot iterator, as we currently assume they should behave * identically. If this test fails, at some point, and the whole-space * snapshot iterator passes, then it probably means that RocksDB changed * how its iterator behaves. */ TEST_F(RmKeysTest, RmKeysWhileIteratingRocksDB) { SCOPED_TRACE("RocksDB -- WholeSpaceIterator"); RmKeysWhileIteratingSnapshot(db.get(), db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(RmKeysTest, RmKeysWhileIteratingMockDB) { std::cout << "There is no safe way to test key removal while iterating\n" << "over the mock store without using snapshots" << std::endl; } // ------- Set Keys / Update Values ------- class SetKeysTest : public IteratorTest { public: string prefix1; string prefix2; void init(KeyValueDB *db) { KeyValueDB::Transaction tx = db->get_transaction(); tx->set(prefix1, "aaa", _gen_val("aaa")); tx->set(prefix1, "ccc", _gen_val("ccc")); tx->set(prefix1, "eee", _gen_val("eee")); tx->set(prefix2, "vvv", _gen_val("vvv")); tx->set(prefix2, "xxx", _gen_val("xxx")); tx->set(prefix2, "zzz", _gen_val("zzz")); db->submit_transaction_sync(tx); } void SetUp() override { IteratorTest::SetUp(); prefix1 = "_PREFIX_1_"; prefix2 = "_PREFIX_2_"; clear(db.get()); ASSERT_TRUE(validate_db_clear(db.get())); clear(mock.get()); ASSERT_TRUE(validate_db_match()); init(db.get()); init(mock.get()); ASSERT_TRUE(validate_db_match()); } void TearDown() override { IteratorTest::TearDown(); } /** * Make sure that the iterator picks on new keys added if it hasn't yet * iterated away from that position. * * This should only happen for the whole-space iterator when not using * the snapshot version. * * We don't need to test the validity of all elements, but we do test * inserting while moving from the first element to the last, using next() * to move forward, and then we test the same behavior while iterating * from the last element to the first, using prev() to move backwards. */ void SetKeysWhileIterating(KeyValueDB *store, KeyValueDB::WholeSpaceIterator iter) { iter->seek_to_first(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "aaa", _gen_val_str("aaa"))); iter->next(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "ccc", _bl_to_str(_gen_val("ccc")))); // insert new key 'ddd' after 'ccc' and before 'eee' KeyValueDB::Transaction tx = store->get_transaction(); tx->set(prefix1, "ddd", _gen_val("ddd")); store->submit_transaction_sync(tx); iter->next(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "ddd", _gen_val_str("ddd"))); iter->seek_to_last(); ASSERT_TRUE(iter->valid()); tx = store->get_transaction(); tx->set(prefix2, "yyy", _gen_val("yyy")); store->submit_transaction_sync(tx); iter->prev(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix2, "yyy", _gen_val_str("yyy"))); } /** * Make sure that the whole-space snapshot iterator does not pick on new keys * added to the store since we created the iterator, thus guaranteeing * read-consistency. * * We don't need to test the validity of all elements, but we do test * inserting while moving from the first element to the last, using next() * to move forward, and then we test the same behavior while iterating * from the last element to the first, using prev() to move backwards. */ void SetKeysWhileIteratingSnapshot(KeyValueDB *store, KeyValueDB::WholeSpaceIterator iter) { iter->seek_to_first(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "aaa", _gen_val_str("aaa"))); iter->next(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "ccc", _bl_to_str(_gen_val("ccc")))); // insert new key 'ddd' after 'ccc' and before 'eee' KeyValueDB::Transaction tx = store->get_transaction(); tx->set(prefix1, "ddd", _gen_val("ddd")); store->submit_transaction_sync(tx); iter->next(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "eee", _gen_val_str("eee"))); iter->seek_to_last(); ASSERT_TRUE(iter->valid()); tx = store->get_transaction(); tx->set(prefix2, "yyy", _gen_val("yyy")); store->submit_transaction_sync(tx); iter->prev(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix2, "xxx", _gen_val_str("xxx"))); } /** * Make sure that the whole-space iterator is able to read values changed on * the store, even after we moved to the updated position. * * This should only be possible when not using the whole-space snapshot * version of the iterator. */ void UpdateValuesWhileIterating(KeyValueDB *store, KeyValueDB::WholeSpaceIterator iter) { iter->seek_to_first(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "aaa", _gen_val_str("aaa"))); KeyValueDB::Transaction tx = store->get_transaction(); tx->set(prefix1, "aaa", _gen_val("aaa_1")); store->submit_transaction_sync(tx); ASSERT_TRUE(validate_iterator(iter, prefix1, "aaa", _gen_val_str("aaa_1"))); iter->seek_to_last(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix2, "zzz", _gen_val_str("zzz"))); tx = store->get_transaction(); tx->set(prefix2, "zzz", _gen_val("zzz_1")); store->submit_transaction_sync(tx); ASSERT_TRUE(validate_iterator(iter, prefix2, "zzz", _gen_val_str("zzz_1"))); } /** * Make sure that the whole-space iterator is able to read values changed on * the store, even after we moved to the updated position. * * This should only be possible when not using the whole-space snapshot * version of the iterator. */ void UpdateValuesWhileIteratingSnapshot( KeyValueDB *store, KeyValueDB::WholeSpaceIterator iter) { iter->seek_to_first(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix1, "aaa", _gen_val_str("aaa"))); KeyValueDB::Transaction tx = store->get_transaction(); tx->set(prefix1, "aaa", _gen_val("aaa_1")); store->submit_transaction_sync(tx); ASSERT_TRUE(validate_iterator(iter, prefix1, "aaa", _gen_val_str("aaa"))); iter->seek_to_last(); ASSERT_TRUE(iter->valid()); ASSERT_TRUE(validate_iterator(iter, prefix2, "zzz", _gen_val_str("zzz"))); tx = store->get_transaction(); tx->set(prefix2, "zzz", _gen_val("zzz_1")); store->submit_transaction_sync(tx); ASSERT_TRUE(validate_iterator(iter, prefix2, "zzz", _gen_val_str("zzz"))); // check those values were really changed in the store KeyValueDB::WholeSpaceIterator tmp_iter = store->get_wholespace_iterator(); tmp_iter->seek_to_first(); ASSERT_TRUE(tmp_iter->valid()); ASSERT_TRUE(validate_iterator(tmp_iter, prefix1, "aaa", _gen_val_str("aaa_1"))); tmp_iter->seek_to_last(); ASSERT_TRUE(tmp_iter->valid()); ASSERT_TRUE(validate_iterator(tmp_iter, prefix2, "zzz", _gen_val_str("zzz_1"))); } }; TEST_F(SetKeysTest, DISABLED_SetKeysWhileIteratingRocksDB) { SCOPED_TRACE("RocksDB: SetKeysWhileIteratingRocksDB"); SetKeysWhileIterating(db.get(), db->get_wholespace_iterator()); ASSERT_TRUE(HasFatalFailure()); } TEST_F(SetKeysTest, SetKeysWhileIteratingMockDB) { SCOPED_TRACE("Mock DB: SetKeysWhileIteratingMockDB"); SetKeysWhileIterating(mock.get(), mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SetKeysTest, DISABLED_UpdateValuesWhileIteratingRocksDB) { SCOPED_TRACE("RocksDB: UpdateValuesWhileIteratingRocksDB"); UpdateValuesWhileIterating(db.get(), db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SetKeysTest, UpdateValuesWhileIteratingMockDB) { SCOPED_TRACE("MockDB: UpdateValuesWhileIteratingMockDB"); UpdateValuesWhileIterating(mock.get(), mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } class BoundsTest : public IteratorTest { public: string prefix1; string prefix2; string prefix3; void init(KeyValueDB *store) { KeyValueDB::Transaction tx = store->get_transaction(); tx->set(prefix1, "aaa", _gen_val("aaa")); tx->set(prefix1, "ccc", _gen_val("ccc")); tx->set(prefix1, "eee", _gen_val("eee")); tx->set(prefix2, "vvv", _gen_val("vvv")); tx->set(prefix2, "xxx", _gen_val("xxx")); tx->set(prefix2, "zzz", _gen_val("zzz")); tx->set(prefix3, "aaa", _gen_val("aaa")); tx->set(prefix3, "mmm", _gen_val("mmm")); tx->set(prefix3, "yyy", _gen_val("yyy")); store->submit_transaction_sync(tx); } void SetUp() override { IteratorTest::SetUp(); prefix1 = "_PREFIX_1_"; prefix2 = "_PREFIX_2_"; prefix3 = "_PREFIX_4_"; clear(db.get()); ASSERT_TRUE(validate_db_clear(db.get())); clear(mock.get()); ASSERT_TRUE(validate_db_match()); init(db.get()); init(mock.get()); ASSERT_TRUE(validate_db_match()); } void TearDown() override { IteratorTest::TearDown(); } void LowerBoundWithEmptyKeyOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // see what happens when we have an empty key and try to get to the // first available prefix iter->lower_bound(prefix1, ""); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // if we got here without problems, then it is safe to assume the // remaining prefixes are intact. // see what happens when we have an empty key and try to get to the // middle of the key-space iter->lower_bound(prefix2, ""); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("vvv"); key_deque.push_back("xxx"); key_deque.push_back("zzz"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // if we got here without problems, then it is safe to assume the // remaining prefixes are intact. // see what happens when we have an empty key and try to get to the // last prefix on the key-space iter->lower_bound(prefix3, ""); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); key_deque.push_back("mmm"); key_deque.push_back("yyy"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); // we reached the end of the key_space, so the iterator should no longer // be valid // see what happens when we look for an inexistent prefix, that will // compare higher than the existing prefixes, with an empty key // expected: reach the store's end; iterator becomes invalid iter->lower_bound("_PREFIX_9_", ""); ASSERT_FALSE(iter->valid()); // see what happens when we look for an inexistent prefix, that will // compare lower than the existing prefixes, with an empty key // expected: find the first prefix; iterator is valid iter->lower_bound("_PREFIX_0_", ""); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // see what happens when we look for an empty prefix (that should compare // lower than any existing prefixes) // expected: find the first prefix; iterator is valid iter->lower_bound("", ""); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); } void LowerBoundWithEmptyPrefixOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // check for an empty prefix, with key 'aaa'. Since this key is shared // among two different prefixes, it is relevant to check which will be // found first. // expected: find key (prefix1, aaa); iterator is valid iter->lower_bound("", "aaa"); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // since we found prefix1, it is safe to assume that the remaining // prefixes (prefix2 and prefix3) will follow // any lower_bound operation with an empty prefix should always put the // iterator in the first key in the key-space, despite what key is // specified. This means that looking for ("","AAAAAAAAAA") should // also position the iterator on (prefix1, aaa). // expected: find key (prefix1, aaa); iterator is valid iter->lower_bound("", "AAAAAAAAAA"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // note: this test is a duplicate of the one in the function above. Why? // Well, because it also fits here (being its prefix empty), and one could // very well run solely this test (instead of the whole battery) and would // certainly expect this case to be tested. // see what happens when we look for an empty prefix (that should compare // lower than any existing prefixes) // expected: find the first prefix; iterator is valid iter->lower_bound("", ""); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); } void LowerBoundOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // check that we find the first key in the store // expected: find (prefix1, aaa); iterator is valid iter->lower_bound(prefix1, "aaa"); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that we find the last key in the store // expected: find (prefix3, yyy); iterator is valid iter->lower_bound(prefix3, "yyy"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("yyy"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); // check that looking for non-existent prefix '_PREFIX_0_' will // always result in the first value of prefix1 (prefix1,"aaa") // expected: find (prefix1, aaa); iterator is valid iter->lower_bound("_PREFIX_0_", "AAAAA"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that looking for non-existent prefix '_PREFIX_3_' will // always result in the first value of prefix3 (prefix4,"aaa") // expected: find (prefix3, aaa); iterator is valid iter->lower_bound("_PREFIX_3_", "AAAAA"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that looking for non-existent prefix '_PREFIX_9_' will // always result in an invalid iterator. // expected: iterator is invalid iter->lower_bound("_PREFIX_9_", "AAAAA"); ASSERT_FALSE(iter->valid()); } void UpperBoundWithEmptyKeyOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // check that looking for (prefix1, "") will result in finding // the first key in prefix1 (prefix1, "aaa") // expected: find (prefix1, aaa); iterator is valid iter->upper_bound(prefix1, ""); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that looking for (prefix2, "") will result in finding // the first key in prefix2 (prefix2, vvv) // expected: find (prefix2, aaa); iterator is valid iter->upper_bound(prefix2, ""); key_deque.push_back("vvv"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that looking for (prefix3, "") will result in finding // the first key in prefix3 (prefix3, aaa) // expected: find (prefix3, aaa); iterator is valid iter->upper_bound(prefix3, ""); key_deque.push_back("aaa"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // see what happens when we look for an inexistent prefix, that will // compare higher than the existing prefixes, with an empty key // expected: reach the store's end; iterator becomes invalid iter->upper_bound("_PREFIX_9_", ""); ASSERT_FALSE(iter->valid()); // see what happens when we look for an inexistent prefix, that will // compare lower than the existing prefixes, with an empty key // expected: find the first prefix; iterator is valid iter->upper_bound("_PREFIX_0_", ""); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // see what happens when we look for an empty prefix (that should compare // lower than any existing prefixes) // expected: find the first prefix; iterator is valid iter->upper_bound("", ""); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); } void UpperBoundWithEmptyPrefixOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // check for an empty prefix, with key 'aaa'. Since this key is shared // among two different prefixes, it is relevant to check which will be // found first. // expected: find key (prefix1, aaa); iterator is valid iter->upper_bound("", "aaa"); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // any upper_bound operation with an empty prefix should always put the // iterator in the first key whose prefix compares greater, despite the // key that is specified. This means that looking for ("","AAAAAAAAAA") // should position the iterator on (prefix1, aaa). // expected: find key (prefix1, aaa); iterator is valid iter->upper_bound("", "AAAAAAAAAA"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // note: this test is a duplicate of the one in the function above. Why? // Well, because it also fits here (being its prefix empty), and one could // very well run solely this test (instead of the whole battery) and would // certainly expect this case to be tested. // see what happens when we look for an empty prefix (that should compare // lower than any existing prefixes) // expected: find the first prefix; iterator is valid iter->upper_bound("", ""); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); } void UpperBoundOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // check that we find the second key in the store // expected: find (prefix1, ccc); iterator is valid iter->upper_bound(prefix1, "bbb"); ASSERT_TRUE(iter->valid()); key_deque.push_back("ccc"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that we find the last key in the store // expected: find (prefix3, yyy); iterator is valid iter->upper_bound(prefix3, "xxx"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("yyy"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); // check that looking for non-existent prefix '_PREFIX_0_' will // always result in the first value of prefix1 (prefix1,"aaa") // expected: find (prefix1, aaa); iterator is valid iter->upper_bound("_PREFIX_0_", "AAAAA"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that looking for non-existent prefix '_PREFIX_3_' will // always result in the first value of prefix3 (prefix3,"aaa") // expected: find (prefix3, aaa); iterator is valid iter->upper_bound("_PREFIX_3_", "AAAAA"); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix3, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // check that looking for non-existent prefix '_PREFIX_9_' will // always result in an invalid iterator. // expected: iterator is invalid iter->upper_bound("_PREFIX_9_", "AAAAA"); ASSERT_FALSE(iter->valid()); } }; TEST_F(BoundsTest, LowerBoundWithEmptyKeyOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Lower Bound, Empty Key, Whole-Space Iterator"); LowerBoundWithEmptyKeyOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, LowerBoundWithEmptyKeyOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Lower Bound, Empty Key, Whole-Space Iterator"); LowerBoundWithEmptyKeyOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, LowerBoundWithEmptyPrefixOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Lower Bound, Empty Prefix, Whole-Space Iterator"); LowerBoundWithEmptyPrefixOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, LowerBoundWithEmptyPrefixOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Lower Bound, Empty Prefix, Whole-Space Iterator"); LowerBoundWithEmptyPrefixOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, LowerBoundOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Lower Bound, Whole-Space Iterator"); LowerBoundOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, LowerBoundOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Lower Bound, Whole-Space Iterator"); LowerBoundOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, UpperBoundWithEmptyKeyOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Upper Bound, Empty Key, Whole-Space Iterator"); UpperBoundWithEmptyKeyOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, UpperBoundWithEmptyKeyOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Upper Bound, Empty Key, Whole-Space Iterator"); UpperBoundWithEmptyKeyOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, UpperBoundWithEmptyPrefixOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Upper Bound, Empty Prefix, Whole-Space Iterator"); UpperBoundWithEmptyPrefixOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, UpperBoundWithEmptyPrefixOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Upper Bound, Empty Prefix, Whole-Space Iterator"); UpperBoundWithEmptyPrefixOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, UpperBoundOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Upper Bound, Whole-Space Iterator"); UpperBoundOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(BoundsTest, UpperBoundOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Upper Bound, Whole-Space Iterator"); UpperBoundOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } class SeeksTest : public IteratorTest { public: string prefix0; string prefix1; string prefix2; string prefix3; string prefix4; string prefix5; void init(KeyValueDB *store) { KeyValueDB::Transaction tx = store->get_transaction(); tx->set(prefix1, "aaa", _gen_val("aaa")); tx->set(prefix1, "ccc", _gen_val("ccc")); tx->set(prefix1, "eee", _gen_val("eee")); tx->set(prefix2, "vvv", _gen_val("vvv")); tx->set(prefix2, "xxx", _gen_val("xxx")); tx->set(prefix2, "zzz", _gen_val("zzz")); tx->set(prefix4, "aaa", _gen_val("aaa")); tx->set(prefix4, "mmm", _gen_val("mmm")); tx->set(prefix4, "yyy", _gen_val("yyy")); store->submit_transaction_sync(tx); } void SetUp() override { IteratorTest::SetUp(); prefix0 = "_PREFIX_0_"; prefix1 = "_PREFIX_1_"; prefix2 = "_PREFIX_2_"; prefix3 = "_PREFIX_3_"; prefix4 = "_PREFIX_4_"; prefix5 = "_PREFIX_5_"; clear(db.get()); ASSERT_TRUE(validate_db_clear(db.get())); clear(mock.get()); ASSERT_TRUE(validate_db_match()); init(db.get()); init(mock.get()); ASSERT_TRUE(validate_db_match()); } void TearDown() override { IteratorTest::TearDown(); } void SeekToFirstOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { iter->seek_to_first(); ASSERT_TRUE(iter->valid()); deque<string> key_deque; key_deque.push_back("aaa"); key_deque.push_back("ccc"); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); } void SeekToFirstWithPrefixOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // if the prefix is empty, we must end up seeking to the first key. // expected: seek to (prefix1, aaa); iterator is valid iter->seek_to_first(""); ASSERT_TRUE(iter->valid()); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to non-existent prefix that compares lower than the // first available prefix // expected: seek to (prefix1, aaa); iterator is valid iter->seek_to_first(prefix0); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to non-existent prefix // expected: seek to (prefix4, aaa); iterator is valid iter->seek_to_first(prefix3); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix4, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to non-existent prefix that compares greater than the // last available prefix // expected: iterator is invalid iter->seek_to_first(prefix5); ASSERT_FALSE(iter->valid()); // try seeking to the first prefix and make sure we end up in its first // position // expected: seek to (prefix1,aaa); iterator is valid iter->seek_to_first(prefix1); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to the second prefix and make sure we end up in its // first position // expected: seek to (prefix2,vvv); iterator is valid iter->seek_to_first(prefix2); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("vvv"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to the last prefix and make sure we end up in its // first position // expected: seek to (prefix4,aaa); iterator is valid iter->seek_to_first(prefix4); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("aaa"); validate_prefix(iter, prefix4, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); } void SeekToLastOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; iter->seek_to_last(); key_deque.push_back("yyy"); validate_prefix(iter, prefix4, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); } void SeekToLastWithPrefixOnWholeSpaceIterator( KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; // if the prefix is empty, we must end up seeking to last position // that has an empty prefix, or to the previous position to the first // position whose prefix compares higher than empty. // expected: iterator is invalid (because (prefix1,aaa) is the first // position that compared higher than an empty prefix) iter->seek_to_last(""); ASSERT_FALSE(iter->valid()); // try seeking to non-existent prefix that compares lower than the // first available prefix // expected: iterator is invalid (because (prefix1,aaa) is the first // position that compared higher than prefix0) iter->seek_to_last(prefix0); ASSERT_FALSE(iter->valid()); // try seeking to non-existent prefix // expected: seek to (prefix2, zzz); iterator is valid iter->seek_to_last(prefix3); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("zzz"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to non-existent prefix that compares greater than the // last available prefix // expected: iterator is in the last position of the store; // i.e., (prefix4,yyy) iter->seek_to_last(prefix5); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("yyy"); validate_prefix(iter, prefix4, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); // try seeking to the first prefix and make sure we end up in its last // position // expected: seek to (prefix1,eee); iterator is valid iter->seek_to_last(prefix1); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("eee"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to the second prefix and make sure we end up in its // last position // expected: seek to (prefix2,vvv); iterator is valid iter->seek_to_last(prefix2); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("zzz"); validate_prefix(iter, prefix2, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_TRUE(iter->valid()); // try seeking to the last prefix and make sure we end up in its // last position // expected: seek to (prefix4,aaa); iterator is valid iter->seek_to_last(prefix4); ASSERT_TRUE(iter->valid()); key_deque.clear(); key_deque.push_back("yyy"); validate_prefix(iter, prefix4, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); } }; TEST_F(SeeksTest, SeekToFirstOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Seek To First, Whole Space Iterator"); SeekToFirstOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SeeksTest, SeekToFirstOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Seek To First, Whole Space Iterator"); SeekToFirstOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SeeksTest, SeekToFirstWithPrefixOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Seek To First, With Prefix, Whole Space Iterator"); SeekToFirstWithPrefixOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SeeksTest, SeekToFirstWithPrefixOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Seek To First, With Prefix, Whole Space Iterator"); SeekToFirstWithPrefixOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SeeksTest, SeekToLastOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Seek To Last, Whole Space Iterator"); SeekToLastOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SeeksTest, SeekToLastOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Seek To Last, Whole Space Iterator"); SeekToLastOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SeeksTest, SeekToLastWithPrefixOnWholeSpaceIteratorRocksDB) { SCOPED_TRACE("RocksDB: Seek To Last, With Prefix, Whole Space Iterator"); SeekToLastWithPrefixOnWholeSpaceIterator(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(SeeksTest, SeekToLastWithPrefixOnWholeSpaceIteratorMockDB) { SCOPED_TRACE("MockDB: Seek To Last, With Prefix, Whole Space Iterator"); SeekToLastWithPrefixOnWholeSpaceIterator(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } class KeySpaceIteration : public IteratorTest { public: string prefix1; void init(KeyValueDB *store) { KeyValueDB::Transaction tx = store->get_transaction(); tx->set(prefix1, "aaa", _gen_val("aaa")); tx->set(prefix1, "vvv", _gen_val("vvv")); tx->set(prefix1, "zzz", _gen_val("zzz")); store->submit_transaction_sync(tx); } void SetUp() override { IteratorTest::SetUp(); prefix1 = "_PREFIX_1_"; clear(db.get()); ASSERT_TRUE(validate_db_clear(db.get())); clear(mock.get()); ASSERT_TRUE(validate_db_match()); init(db.get()); init(mock.get()); ASSERT_TRUE(validate_db_match()); } void TearDown() override { IteratorTest::TearDown(); } void ForwardIteration(KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; iter->seek_to_first(); key_deque.push_back("aaa"); key_deque.push_back("vvv"); key_deque.push_back("zzz"); validate_prefix(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); } void BackwardIteration(KeyValueDB::WholeSpaceIterator iter) { deque<string> key_deque; iter->seek_to_last(); key_deque.push_back("zzz"); key_deque.push_back("vvv"); key_deque.push_back("aaa"); validate_prefix_backwards(iter, prefix1, key_deque); ASSERT_FALSE(HasFatalFailure()); ASSERT_FALSE(iter->valid()); } }; TEST_F(KeySpaceIteration, ForwardIterationRocksDB) { SCOPED_TRACE("RocksDB: Forward Iteration, Whole Space Iterator"); ForwardIteration(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(KeySpaceIteration, ForwardIterationMockDB) { SCOPED_TRACE("MockDB: Forward Iteration, Whole Space Iterator"); ForwardIteration(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(KeySpaceIteration, BackwardIterationRocksDB) { SCOPED_TRACE("RocksDB: Backward Iteration, Whole Space Iterator"); BackwardIteration(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(KeySpaceIteration, BackwardIterationMockDB) { SCOPED_TRACE("MockDB: Backward Iteration, Whole Space Iterator"); BackwardIteration(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } class EmptyStore : public IteratorTest { public: void SetUp() override { IteratorTest::SetUp(); clear(db.get()); ASSERT_TRUE(validate_db_clear(db.get())); clear(mock.get()); ASSERT_TRUE(validate_db_match()); } void SeekToFirst(KeyValueDB::WholeSpaceIterator iter) { // expected: iterator is invalid iter->seek_to_first(); ASSERT_FALSE(iter->valid()); } void SeekToFirstWithPrefix(KeyValueDB::WholeSpaceIterator iter) { // expected: iterator is invalid iter->seek_to_first("prefix"); ASSERT_FALSE(iter->valid()); } void SeekToLast(KeyValueDB::WholeSpaceIterator iter) { // expected: iterator is invalid iter->seek_to_last(); ASSERT_FALSE(iter->valid()); } void SeekToLastWithPrefix(KeyValueDB::WholeSpaceIterator iter) { // expected: iterator is invalid iter->seek_to_last("prefix"); ASSERT_FALSE(iter->valid()); } void LowerBound(KeyValueDB::WholeSpaceIterator iter) { // expected: iterator is invalid iter->lower_bound("prefix", ""); ASSERT_FALSE(iter->valid()); // expected: iterator is invalid iter->lower_bound("", "key"); ASSERT_FALSE(iter->valid()); // expected: iterator is invalid iter->lower_bound("prefix", "key"); ASSERT_FALSE(iter->valid()); } void UpperBound(KeyValueDB::WholeSpaceIterator iter) { // expected: iterator is invalid iter->upper_bound("prefix", ""); ASSERT_FALSE(iter->valid()); // expected: iterator is invalid iter->upper_bound("", "key"); ASSERT_FALSE(iter->valid()); // expected: iterator is invalid iter->upper_bound("prefix", "key"); ASSERT_FALSE(iter->valid()); } }; TEST_F(EmptyStore, SeekToFirstRocksDB) { SCOPED_TRACE("RocksDB: Empty Store, Seek To First"); SeekToFirst(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, SeekToFirstMockDB) { SCOPED_TRACE("MockDB: Empty Store, Seek To First"); SeekToFirst(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, SeekToFirstWithPrefixRocksDB) { SCOPED_TRACE("RocksDB: Empty Store, Seek To First With Prefix"); SeekToFirstWithPrefix(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, SeekToFirstWithPrefixMockDB) { SCOPED_TRACE("MockDB: Empty Store, Seek To First With Prefix"); SeekToFirstWithPrefix(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, SeekToLastRocksDB) { SCOPED_TRACE("RocksDB: Empty Store, Seek To Last"); SeekToLast(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, SeekToLastMockDB) { SCOPED_TRACE("MockDB: Empty Store, Seek To Last"); SeekToLast(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, SeekToLastWithPrefixRocksDB) { SCOPED_TRACE("RocksDB: Empty Store, Seek To Last With Prefix"); SeekToLastWithPrefix(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, SeekToLastWithPrefixMockDB) { SCOPED_TRACE("MockDB: Empty Store, Seek To Last With Prefix"); SeekToLastWithPrefix(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, LowerBoundRocksDB) { SCOPED_TRACE("RocksDB: Empty Store, Lower Bound"); LowerBound(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, LowerBoundMockDB) { SCOPED_TRACE("MockDB: Empty Store, Lower Bound"); LowerBound(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, UpperBoundRocksDB) { SCOPED_TRACE("RocksDB: Empty Store, Upper Bound"); UpperBound(db->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } TEST_F(EmptyStore, UpperBoundMockDB) { SCOPED_TRACE("MockDB: Empty Store, Upper Bound"); UpperBound(mock->get_wholespace_iterator()); ASSERT_FALSE(HasFatalFailure()); } int main(int argc, char *argv[]) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); ::testing::InitGoogleTest(&argc, argv); if (argc < 2) { std::cerr << "Usage: " << argv[0] << "[ceph_options] [gtest_options] <store_path>" << std::endl; return 1; } store_path = string(argv[1]); return RUN_ALL_TESTS(); }
55,602
30.646557
123
cc
null
ceph-main/src/test/ObjectMap/test_object_map.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- #include <iterator> #include <map> #include <set> #include <boost/scoped_ptr.hpp> #include "include/buffer.h" #include "test/ObjectMap/KeyValueDBMemory.h" #include "kv/KeyValueDB.h" #include "os/DBObjectMap.h" #include <sys/types.h> #include "global/global_init.h" #include "common/ceph_argparse.h" #include <dirent.h> #include "gtest/gtest.h" #include "stdlib.h" using namespace std; template <typename T> typename T::iterator rand_choose(T &cont) { if (std::empty(cont)) { return std::end(cont); } return std::next(std::begin(cont), rand() % cont.size()); } string num_str(unsigned i) { char buf[100]; snprintf(buf, sizeof(buf), "%.10u", i); return string(buf); } class ObjectMapTester { public: ObjectMap *db; set<string> key_space; set<string> object_name_space; map<string, map<string, string> > omap; map<string, string > hmap; map<string, map<string, string> > xattrs; unsigned seq; ObjectMapTester() : db(0), seq(0) {} string val_from_key(const string &object, const string &key) { return object + "_" + key + "_" + num_str(seq++); } void set_key(const string &objname, const string &key, const string &value) { set_key(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), key, value); } void set_xattr(const string &objname, const string &key, const string &value) { set_xattr(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), key, value); } void set_key(ghobject_t hoid, string key, string value) { map<string, bufferlist> to_write; bufferptr bp(value.c_str(), value.size()); bufferlist bl; bl.append(bp); to_write.insert(make_pair(key, bl)); db->set_keys(hoid, to_write); } void set_keys(ghobject_t hoid, const map<string, string> &to_set) { map<string, bufferlist> to_write; for (auto &&i: to_set) { bufferptr bp(i.second.data(), i.second.size()); bufferlist bl; bl.append(bp); to_write.insert(make_pair(i.first, bl)); } db->set_keys(hoid, to_write); } void set_xattr(ghobject_t hoid, string key, string value) { map<string, bufferlist> to_write; bufferptr bp(value.c_str(), value.size()); bufferlist bl; bl.append(bp); to_write.insert(make_pair(key, bl)); db->set_xattrs(hoid, to_write); } void set_header(const string &objname, const string &value) { set_header(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), value); } void set_header(ghobject_t hoid, const string &value) { bufferlist header; header.append(bufferptr(value.c_str(), value.size() + 1)); db->set_header(hoid, header); } int get_header(const string &objname, string *value) { return get_header(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), value); } int get_header(ghobject_t hoid, string *value) { bufferlist header; int r = db->get_header(hoid, &header); if (r < 0) return r; if (header.length()) *value = string(header.c_str()); else *value = string(""); return 0; } int get_xattr(const string &objname, const string &key, string *value) { return get_xattr(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), key, value); } int get_xattr(ghobject_t hoid, string key, string *value) { set<string> to_get; to_get.insert(key); map<string, bufferlist> got; db->get_xattrs(hoid, to_get, &got); if (!got.empty()) { *value = string(got.begin()->second.c_str(), got.begin()->second.length()); return 1; } else { return 0; } } int get_key(const string &objname, const string &key, string *value) { return get_key(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), key, value); } int get_key(ghobject_t hoid, string key, string *value) { set<string> to_get; to_get.insert(key); map<string, bufferlist> got; db->get_values(hoid, to_get, &got); if (!got.empty()) { if (value) { *value = string(got.begin()->second.c_str(), got.begin()->second.length()); } return 1; } else { return 0; } } void remove_key(const string &objname, const string &key) { remove_key(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), key); } void remove_keys(const string &objname, const set<string> &to_remove) { remove_keys(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), to_remove); } void remove_key(ghobject_t hoid, string key) { set<string> to_remove; to_remove.insert(key); db->rm_keys(hoid, to_remove); } void remove_keys(ghobject_t hoid, const set<string> &to_remove) { db->rm_keys(hoid, to_remove); } void remove_xattr(const string &objname, const string &key) { remove_xattr(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), key); } void remove_xattr(ghobject_t hoid, string key) { set<string> to_remove; to_remove.insert(key); db->remove_xattrs(hoid, to_remove); } void clone(const string &objname, const string &target) { clone(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), ghobject_t(hobject_t(sobject_t(target, CEPH_NOSNAP)))); } void clone(ghobject_t hoid, ghobject_t hoid2) { db->clone(hoid, hoid2); } void rename(const string &objname, const string &target) { rename(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), ghobject_t(hobject_t(sobject_t(target, CEPH_NOSNAP)))); } void rename(ghobject_t hoid, ghobject_t hoid2) { db->rename(hoid, hoid2); } void clear(const string &objname) { clear(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP)))); } void legacy_clone(const string &objname, const string &target) { legacy_clone(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP))), ghobject_t(hobject_t(sobject_t(target, CEPH_NOSNAP)))); } void legacy_clone(ghobject_t hoid, ghobject_t hoid2) { db->legacy_clone(hoid, hoid2); } void clear(ghobject_t hoid) { db->clear(hoid); } void clear_omap(const string &objname) { clear_omap(ghobject_t(hobject_t(sobject_t(objname, CEPH_NOSNAP)))); } void clear_omap(const ghobject_t &objname) { db->clear_keys_header(objname); } void def_init() { for (unsigned i = 0; i < 10000; ++i) { key_space.insert("key_" + num_str(i)); } for (unsigned i = 0; i < 100; ++i) { object_name_space.insert("name_" + num_str(i)); } } void init_key_set(const set<string> &keys) { key_space = keys; } void init_object_name_space(const set<string> &onamespace) { object_name_space = onamespace; } void auto_set_xattr(ostream &out) { set<string>::iterator key = rand_choose(key_space); set<string>::iterator object = rand_choose(object_name_space); string value = val_from_key(*object, *key); xattrs[*object][*key] = value; set_xattr(*object, *key, value); out << "auto_set_xattr " << *object << ": " << *key << " -> " << value << std::endl; } void test_set_key(const string &obj, const string &key, const string &val) { omap[obj][key] = val; set_key(obj, key, val); } void test_set_keys(const string &obj, const map<string, string> &to_set) { for (auto &&i: to_set) { omap[obj][i.first] = i.second; } set_keys( ghobject_t(hobject_t(sobject_t(obj, CEPH_NOSNAP))), to_set); } void auto_set_keys(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); map<string, string> to_set; unsigned amount = (rand() % 10) + 1; for (unsigned i = 0; i < amount; ++i) { set<string>::iterator key = rand_choose(key_space); string value = val_from_key(*object, *key); out << "auto_set_key " << *object << ": " << *key << " -> " << value << std::endl; to_set.insert(make_pair(*key, value)); } test_set_keys(*object, to_set); } void xattrs_on_object(const string &object, set<string> *out) { if (!xattrs.count(object)) return; const map<string, string> &xmap = xattrs.find(object)->second; for (map<string, string>::const_iterator i = xmap.begin(); i != xmap.end(); ++i) { out->insert(i->first); } } void keys_on_object(const string &object, set<string> *out) { if (!omap.count(object)) return; const map<string, string> &kmap = omap.find(object)->second; for (map<string, string>::const_iterator i = kmap.begin(); i != kmap.end(); ++i) { out->insert(i->first); } } void xattrs_off_object(const string &object, set<string> *out) { *out = key_space; set<string> xspace; xattrs_on_object(object, &xspace); for (set<string>::iterator i = xspace.begin(); i != xspace.end(); ++i) { out->erase(*i); } } void keys_off_object(const string &object, set<string> *out) { *out = key_space; set<string> kspace; keys_on_object(object, &kspace); for (set<string>::iterator i = kspace.begin(); i != kspace.end(); ++i) { out->erase(*i); } } int auto_check_present_xattr(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); set<string> xspace; xattrs_on_object(*object, &xspace); set<string>::iterator key = rand_choose(xspace); if (key == xspace.end()) { return 1; } string result; int r = get_xattr(*object, *key, &result); if (!r) { out << "auto_check_present_key: failed to find key " << *key << " on object " << *object << std::endl; return 0; } if (result != xattrs[*object][*key]) { out << "auto_check_present_key: for key " << *key << " on object " << *object << " found value " << result << " where we should have found " << xattrs[*object][*key] << std::endl; return 0; } out << "auto_check_present_key: for key " << *key << " on object " << *object << " found value " << result << " where we should have found " << xattrs[*object][*key] << std::endl; return 1; } int auto_check_present_key(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); set<string> kspace; keys_on_object(*object, &kspace); set<string>::iterator key = rand_choose(kspace); if (key == kspace.end()) { return 1; } string result; int r = get_key(*object, *key, &result); if (!r) { out << "auto_check_present_key: failed to find key " << *key << " on object " << *object << std::endl; return 0; } if (result != omap[*object][*key]) { out << "auto_check_present_key: for key " << *key << " on object " << *object << " found value " << result << " where we should have found " << omap[*object][*key] << std::endl; return 0; } out << "auto_check_present_key: for key " << *key << " on object " << *object << " found value " << result << " where we should have found " << omap[*object][*key] << std::endl; return 1; } int auto_check_absent_xattr(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); set<string> xspace; xattrs_off_object(*object, &xspace); set<string>::iterator key = rand_choose(xspace); if (key == xspace.end()) { return 1; } string result; int r = get_xattr(*object, *key, &result); if (!r) { out << "auto_check_absent_key: did not find key " << *key << " on object " << *object << std::endl; return 1; } out << "auto_check_basent_key: for key " << *key << " on object " << *object << " found value " << result << " where we should have found nothing" << std::endl; return 0; } int auto_check_absent_key(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); set<string> kspace; keys_off_object(*object, &kspace); set<string>::iterator key = rand_choose(kspace); if (key == kspace.end()) { return 1; } string result; int r = get_key(*object, *key, &result); if (!r) { out << "auto_check_absent_key: did not find key " << *key << " on object " << *object << std::endl; return 1; } out << "auto_check_basent_key: for key " << *key << " on object " << *object << " found value " << result << " where we should have found nothing" << std::endl; return 0; } void test_clone(const string &object, const string &target, ostream &out) { clone(object, target); if (!omap.count(object)) { out << " source missing."; omap.erase(target); } else { out << " source present."; omap[target] = omap[object]; } if (!hmap.count(object)) { out << " hmap source missing." << std::endl; hmap.erase(target); } else { out << " hmap source present." << std::endl; hmap[target] = hmap[object]; } if (!xattrs.count(object)) { out << " hmap source missing." << std::endl; xattrs.erase(target); } else { out << " hmap source present." << std::endl; xattrs[target] = xattrs[object]; } } void auto_clone_key(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); set<string>::iterator target = rand_choose(object_name_space); while (target == object) { target = rand_choose(object_name_space); } out << "clone " << *object << " to " << *target; test_clone(*object, *target, out); } void test_remove_keys(const string &obj, const set<string> &to_remove) { for (auto &&k: to_remove) omap[obj].erase(k); remove_keys(obj, to_remove); } void test_remove_key(const string &obj, const string &key) { omap[obj].erase(key); remove_key(obj, key); } void auto_remove_keys(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); set<string> kspace; keys_on_object(*object, &kspace); set<string> to_remove; for (unsigned i = 0; i < 3; ++i) { set<string>::iterator key = rand_choose(kspace); if (key == kspace.end()) continue; out << "removing " << *key << " from " << *object << std::endl; to_remove.insert(*key); } test_remove_keys(*object, to_remove); } void auto_remove_xattr(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); set<string> kspace; xattrs_on_object(*object, &kspace); set<string>::iterator key = rand_choose(kspace); if (key == kspace.end()) { return; } out << "removing xattr " << *key << " from " << *object << std::endl; xattrs[*object].erase(*key); remove_xattr(*object, *key); } void auto_delete_object(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); out << "auto_delete_object " << *object << std::endl; clear(*object); omap.erase(*object); hmap.erase(*object); xattrs.erase(*object); } void test_clear(const string &obj) { clear_omap(obj); omap.erase(obj); hmap.erase(obj); } void auto_clear_omap(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); out << "auto_clear_object " << *object << std::endl; test_clear(*object); } void auto_write_header(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); string header = val_from_key(*object, "HEADER"); out << "auto_write_header: " << *object << " -> " << header << std::endl; set_header(*object, header); hmap[*object] = header; } int auto_verify_header(ostream &out) { set<string>::iterator object = rand_choose(object_name_space); out << "verify_header: " << *object << " "; string header; int r = get_header(*object, &header); if (r < 0) { ceph_abort(); } if (header.size() == 0) { if (hmap.count(*object)) { out << " failed to find header " << hmap[*object] << std::endl; return 0; } else { out << " found no header" << std::endl; return 1; } } if (!hmap.count(*object)) { out << " found header " << header << " should have been empty" << std::endl; return 0; } else if (header == hmap[*object]) { out << " found correct header " << header << std::endl; return 1; } else { out << " found incorrect header " << header << " where we should have found " << hmap[*object] << std::endl; return 0; } } void verify_keys(const std::string &obj, ostream &out) { set<string> in_db; ObjectMap::ObjectMapIterator iter = db->get_iterator( ghobject_t(hobject_t(sobject_t(obj, CEPH_NOSNAP)))); for (iter->seek_to_first(); iter->valid(); iter->next()) { in_db.insert(iter->key()); } bool err = false; for (auto &&i: omap[obj]) { if (!in_db.count(i.first)) { out << __func__ << ": obj " << obj << " missing key " << i.first << std::endl; err = true; } else { in_db.erase(i.first); } } if (!in_db.empty()) { out << __func__ << ": obj " << obj << " found extra keys " << in_db << std::endl; err = true; } ASSERT_FALSE(err); } void auto_verify_objects(ostream &out) { for (auto &&i: omap) { verify_keys(i.first, out); } } }; class ObjectMapTest : public ::testing::Test { public: boost::scoped_ptr< ObjectMap > db; ObjectMapTester tester; void SetUp() override { char *path = getenv("OBJECT_MAP_PATH"); if (!path) { db.reset(new DBObjectMap(g_ceph_context, new KeyValueDBMemory())); tester.db = db.get(); return; } string strpath(path); cerr << "using path " << strpath << std::endl; KeyValueDB *store = KeyValueDB::create(g_ceph_context, "rocksdb", strpath); ceph_assert(!store->create_and_open(cerr)); db.reset(new DBObjectMap(g_ceph_context, store)); tester.db = db.get(); } void TearDown() override { std::cerr << "Checking..." << std::endl; ASSERT_EQ(0, db->check(std::cerr)); } }; int main(int argc, char **argv) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } TEST_F(ObjectMapTest, CreateOneObject) { ghobject_t hoid(hobject_t(sobject_t("foo", CEPH_NOSNAP)), 100, shard_id_t(0)); map<string, bufferlist> to_set; string key("test"); string val("test_val"); bufferptr bp(val.c_str(), val.size()); bufferlist bl; bl.append(bp); to_set.insert(make_pair(key, bl)); ASSERT_EQ(db->set_keys(hoid, to_set), 0); map<string, bufferlist> got; set<string> to_get; to_get.insert(key); to_get.insert("not there"); db->get_values(hoid, to_get, &got); ASSERT_EQ(got.size(), (unsigned)1); ASSERT_EQ(string(got[key].c_str(), got[key].length()), val); bufferlist header; got.clear(); db->get(hoid, &header, &got); ASSERT_EQ(got.size(), (unsigned)1); ASSERT_EQ(string(got[key].c_str(), got[key].length()), val); ASSERT_EQ(header.length(), (unsigned)0); db->rm_keys(hoid, to_get); got.clear(); db->get(hoid, &header, &got); ASSERT_EQ(got.size(), (unsigned)0); map<string, bufferlist> attrs; attrs["attr1"] = bl; db->set_xattrs(hoid, attrs); db->set_header(hoid, bl); db->clear_keys_header(hoid); set<string> attrs_got; db->get_all_xattrs(hoid, &attrs_got); ASSERT_EQ(attrs_got.size(), 1U); ASSERT_EQ(*(attrs_got.begin()), "attr1"); db->get(hoid, &header, &got); ASSERT_EQ(got.size(), (unsigned)0); ASSERT_EQ(header.length(), 0U); got.clear(); db->clear(hoid); db->get(hoid, &header, &got); ASSERT_EQ(got.size(), (unsigned)0); attrs_got.clear(); db->get_all_xattrs(hoid, &attrs_got); ASSERT_EQ(attrs_got.size(), 0U); } TEST_F(ObjectMapTest, CloneOneObject) { ghobject_t hoid(hobject_t(sobject_t("foo", CEPH_NOSNAP)), 200, shard_id_t(0)); ghobject_t hoid2(hobject_t(sobject_t("foo2", CEPH_NOSNAP)), 201, shard_id_t(1)); tester.set_key(hoid, "foo", "bar"); tester.set_key(hoid, "foo2", "bar2"); string result; int r = tester.get_key(hoid, "foo", &result); ASSERT_EQ(r, 1); ASSERT_EQ(result, "bar"); db->clone(hoid, hoid2); r = tester.get_key(hoid, "foo", &result); ASSERT_EQ(r, 1); ASSERT_EQ(result, "bar"); r = tester.get_key(hoid2, "foo", &result); ASSERT_EQ(r, 1); ASSERT_EQ(result, "bar"); tester.remove_key(hoid, "foo"); r = tester.get_key(hoid2, "foo", &result); ASSERT_EQ(r, 1); ASSERT_EQ(result, "bar"); r = tester.get_key(hoid, "foo", &result); ASSERT_EQ(r, 0); r = tester.get_key(hoid, "foo2", &result); ASSERT_EQ(r, 1); ASSERT_EQ(result, "bar2"); tester.set_key(hoid, "foo", "baz"); tester.remove_key(hoid, "foo"); r = tester.get_key(hoid, "foo", &result); ASSERT_EQ(r, 0); tester.set_key(hoid, "foo2", "baz"); tester.remove_key(hoid, "foo2"); r = tester.get_key(hoid, "foo2", &result); ASSERT_EQ(r, 0); map<string, bufferlist> got; bufferlist header; got.clear(); db->clear(hoid); db->get(hoid, &header, &got); ASSERT_EQ(got.size(), (unsigned)0); got.clear(); r = db->clear(hoid2); ASSERT_EQ(0, r); db->get(hoid2, &header, &got); ASSERT_EQ(got.size(), (unsigned)0); tester.set_key(hoid, "baz", "bar"); got.clear(); db->get(hoid, &header, &got); ASSERT_EQ(got.size(), (unsigned)1); db->clear(hoid); db->clear(hoid2); } TEST_F(ObjectMapTest, OddEvenClone) { ghobject_t hoid(hobject_t(sobject_t("foo", CEPH_NOSNAP))); ghobject_t hoid2(hobject_t(sobject_t("foo2", CEPH_NOSNAP))); for (unsigned i = 0; i < 1000; ++i) { tester.set_key(hoid, "foo" + num_str(i), "bar" + num_str(i)); } db->clone(hoid, hoid2); int r = 0; for (unsigned i = 0; i < 1000; ++i) { string result; r = tester.get_key(hoid, "foo" + num_str(i), &result); ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); r = tester.get_key(hoid2, "foo" + num_str(i), &result); ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); if (i % 2) { tester.remove_key(hoid, "foo" + num_str(i)); } else { tester.remove_key(hoid2, "foo" + num_str(i)); } } for (unsigned i = 0; i < 1000; ++i) { string result; string result2; r = tester.get_key(hoid, "foo" + num_str(i), &result); int r2 = tester.get_key(hoid2, "foo" + num_str(i), &result2); if (i % 2) { ASSERT_EQ(0, r); ASSERT_EQ(1, r2); ASSERT_EQ("bar" + num_str(i), result2); } else { ASSERT_EQ(0, r2); ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); } } { ObjectMap::ObjectMapIterator iter = db->get_iterator(hoid); iter->seek_to_first(); for (unsigned i = 0; i < 1000; ++i) { if (!(i % 2)) { ASSERT_TRUE(iter->valid()); ASSERT_EQ("foo" + num_str(i), iter->key()); iter->next(); } } } { ObjectMap::ObjectMapIterator iter2 = db->get_iterator(hoid2); iter2->seek_to_first(); for (unsigned i = 0; i < 1000; ++i) { if (i % 2) { ASSERT_TRUE(iter2->valid()); ASSERT_EQ("foo" + num_str(i), iter2->key()); iter2->next(); } } } db->clear(hoid); db->clear(hoid2); } TEST_F(ObjectMapTest, Rename) { ghobject_t hoid(hobject_t(sobject_t("foo", CEPH_NOSNAP))); ghobject_t hoid2(hobject_t(sobject_t("foo2", CEPH_NOSNAP))); for (unsigned i = 0; i < 1000; ++i) { tester.set_key(hoid, "foo" + num_str(i), "bar" + num_str(i)); } db->rename(hoid, hoid2); // Verify rename where target exists db->clone(hoid2, hoid); db->rename(hoid, hoid2); int r = 0; for (unsigned i = 0; i < 1000; ++i) { string result; r = tester.get_key(hoid2, "foo" + num_str(i), &result); ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); if (i % 2) { tester.remove_key(hoid2, "foo" + num_str(i)); } } for (unsigned i = 0; i < 1000; ++i) { string result; r = tester.get_key(hoid2, "foo" + num_str(i), &result); if (i % 2) { ASSERT_EQ(0, r); } else { ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); } } { ObjectMap::ObjectMapIterator iter = db->get_iterator(hoid2); iter->seek_to_first(); for (unsigned i = 0; i < 1000; ++i) { if (!(i % 2)) { ASSERT_TRUE(iter->valid()); ASSERT_EQ("foo" + num_str(i), iter->key()); iter->next(); } } } db->clear(hoid2); } TEST_F(ObjectMapTest, OddEvenOldClone) { ghobject_t hoid(hobject_t(sobject_t("foo", CEPH_NOSNAP))); ghobject_t hoid2(hobject_t(sobject_t("foo2", CEPH_NOSNAP))); for (unsigned i = 0; i < 1000; ++i) { tester.set_key(hoid, "foo" + num_str(i), "bar" + num_str(i)); } db->legacy_clone(hoid, hoid2); int r = 0; for (unsigned i = 0; i < 1000; ++i) { string result; r = tester.get_key(hoid, "foo" + num_str(i), &result); ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); r = tester.get_key(hoid2, "foo" + num_str(i), &result); ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); if (i % 2) { tester.remove_key(hoid, "foo" + num_str(i)); } else { tester.remove_key(hoid2, "foo" + num_str(i)); } } for (unsigned i = 0; i < 1000; ++i) { string result; string result2; r = tester.get_key(hoid, "foo" + num_str(i), &result); int r2 = tester.get_key(hoid2, "foo" + num_str(i), &result2); if (i % 2) { ASSERT_EQ(0, r); ASSERT_EQ(1, r2); ASSERT_EQ("bar" + num_str(i), result2); } else { ASSERT_EQ(0, r2); ASSERT_EQ(1, r); ASSERT_EQ("bar" + num_str(i), result); } } { ObjectMap::ObjectMapIterator iter = db->get_iterator(hoid); iter->seek_to_first(); for (unsigned i = 0; i < 1000; ++i) { if (!(i % 2)) { ASSERT_TRUE(iter->valid()); ASSERT_EQ("foo" + num_str(i), iter->key()); iter->next(); } } } { ObjectMap::ObjectMapIterator iter2 = db->get_iterator(hoid2); iter2->seek_to_first(); for (unsigned i = 0; i < 1000; ++i) { if (i % 2) { ASSERT_TRUE(iter2->valid()); ASSERT_EQ("foo" + num_str(i), iter2->key()); iter2->next(); } } } db->clear(hoid); db->clear(hoid2); } TEST_F(ObjectMapTest, RandomTest) { tester.def_init(); for (unsigned i = 0; i < 5000; ++i) { unsigned val = rand(); val <<= 8; val %= 100; if (!(i%100)) std::cout << "on op " << i << " val is " << val << std::endl; if (val < 7) { tester.auto_write_header(std::cerr); } else if (val < 14) { ASSERT_TRUE(tester.auto_verify_header(std::cerr)); } else if (val < 30) { tester.auto_set_keys(std::cerr); } else if (val < 42) { tester.auto_set_xattr(std::cerr); } else if (val < 55) { ASSERT_TRUE(tester.auto_check_present_key(std::cerr)); } else if (val < 62) { ASSERT_TRUE(tester.auto_check_present_xattr(std::cerr)); } else if (val < 70) { ASSERT_TRUE(tester.auto_check_absent_key(std::cerr)); } else if (val < 72) { ASSERT_TRUE(tester.auto_check_absent_xattr(std::cerr)); } else if (val < 73) { tester.auto_clear_omap(std::cerr); } else if (val < 76) { tester.auto_delete_object(std::cerr); } else if (val < 85) { tester.auto_clone_key(std::cerr); } else if (val < 92) { tester.auto_remove_xattr(std::cerr); } else { tester.auto_remove_keys(std::cerr); } if (i % 500) { tester.auto_verify_objects(std::cerr); } } } TEST_F(ObjectMapTest, RandomTestNoDeletesXattrs) { tester.def_init(); for (unsigned i = 0; i < 5000; ++i) { unsigned val = rand(); val <<= 8; val %= 100; if (!(i%100)) std::cout << "on op " << i << " val is " << val << std::endl; if (val < 45) { tester.auto_set_keys(std::cerr); } else if (val < 90) { tester.auto_remove_keys(std::cerr); } else { tester.auto_clone_key(std::cerr); } if (i % 500) { tester.auto_verify_objects(std::cerr); } } } string num_to_key(unsigned i) { char buf[100]; int ret = snprintf(buf, sizeof(buf), "%010u", i); ceph_assert(ret > 0); return string(buf, ret); } TEST_F(ObjectMapTest, TestMergeNewCompleteContainBug) { /* This test exploits a bug in kraken and earlier where merge_new_complete * could miss complete entries fully contained by a new entry. To get this * to actually result in an incorrect return value, you need to remove at * least two values, one before a complete region, and one which occurs in * the parent after the complete region (but within 20 not yet completed * parent points of the first value). */ for (unsigned i = 10; i < 160; i+=2) { tester.test_set_key("foo", num_to_key(i), "asdf"); } tester.test_clone("foo", "foo2", std::cout); tester.test_clear("foo"); tester.test_set_key("foo2", num_to_key(15), "asdf"); tester.test_set_key("foo2", num_to_key(13), "asdf"); tester.test_set_key("foo2", num_to_key(57), "asdf"); tester.test_remove_key("foo2", num_to_key(15)); set<string> to_remove; to_remove.insert(num_to_key(13)); to_remove.insert(num_to_key(58)); to_remove.insert(num_to_key(60)); to_remove.insert(num_to_key(62)); tester.test_remove_keys("foo2", to_remove); tester.verify_keys("foo2", std::cout); ASSERT_EQ(tester.get_key("foo2", num_to_key(10), nullptr), 1); ASSERT_EQ(tester.get_key("foo2", num_to_key(1), nullptr), 0); ASSERT_EQ(tester.get_key("foo2", num_to_key(56), nullptr), 1); // this one triggers the bug ASSERT_EQ(tester.get_key("foo2", num_to_key(58), nullptr), 0); } TEST_F(ObjectMapTest, TestIterateBug18533) { /* This test starts with the one immediately above to create a pair of * complete regions where one contains the other. Then, it deletes the * key at the start of the contained region. The logic in next_parent() * skips ahead to the end of the contained region, and we start copying * values down again from the parent into the child -- including some * that had actually been deleted. I think this works for any removal * within the outer complete region after the start of the contained * region. */ for (unsigned i = 10; i < 160; i+=2) { tester.test_set_key("foo", num_to_key(i), "asdf"); } tester.test_clone("foo", "foo2", std::cout); tester.test_clear("foo"); tester.test_set_key("foo2", num_to_key(15), "asdf"); tester.test_set_key("foo2", num_to_key(13), "asdf"); tester.test_set_key("foo2", num_to_key(57), "asdf"); tester.test_set_key("foo2", num_to_key(91), "asdf"); tester.test_remove_key("foo2", num_to_key(15)); set<string> to_remove; to_remove.insert(num_to_key(13)); to_remove.insert(num_to_key(58)); to_remove.insert(num_to_key(60)); to_remove.insert(num_to_key(62)); to_remove.insert(num_to_key(82)); to_remove.insert(num_to_key(84)); tester.test_remove_keys("foo2", to_remove); //tester.test_remove_key("foo2", num_to_key(15)); also does the trick tester.test_remove_key("foo2", num_to_key(80)); // the iterator in verify_keys will return an extra value tester.verify_keys("foo2", std::cout); }
31,252
26.731145
82
cc
null
ceph-main/src/test/centos-8/install-deps.sh
../../../install-deps.sh
24
24
24
sh
null
ceph-main/src/test/ceph-erasure-code-tool/test_ceph-erasure-code-tool.sh
#!/bin/sh -ex TMPDIR=/tmp/test_ceph-erasure-code-tool.$$ mkdir $TMPDIR trap "rm -fr $TMPDIR" 0 ceph-erasure-code-tool test-plugin-exists INVALID_PLUGIN && exit 1 ceph-erasure-code-tool test-plugin-exists jerasure ceph-erasure-code-tool validate-profile \ plugin=jerasure,technique=reed_sol_van,k=2,m=1 test "$(ceph-erasure-code-tool validate-profile \ plugin=jerasure,technique=reed_sol_van,k=2,m=1 chunk_count)" = 3 test "$(ceph-erasure-code-tool calc-chunk-size \ plugin=jerasure,technique=reed_sol_van,k=2,m=1 4194304)" = 2097152 dd if="$(which ceph-erasure-code-tool)" of=$TMPDIR/data bs=770808 count=1 cp $TMPDIR/data $TMPDIR/data.orig ceph-erasure-code-tool encode \ plugin=jerasure,technique=reed_sol_van,k=2,m=1 \ 4096 \ 0,1,2 \ $TMPDIR/data test -f $TMPDIR/data.0 test -f $TMPDIR/data.1 test -f $TMPDIR/data.2 rm $TMPDIR/data ceph-erasure-code-tool decode \ plugin=jerasure,technique=reed_sol_van,k=2,m=1 \ 4096 \ 0,2 \ $TMPDIR/data size=$(stat -c '%s' $TMPDIR/data.orig) truncate -s "${size}" $TMPDIR/data # remove stripe width padding cmp $TMPDIR/data.orig $TMPDIR/data echo OK
1,327
29.181818
76
sh
null
ceph-main/src/test/client/TestClient.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2021 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "gtest/gtest.h" #include "common/async/context_pool.h" #include "global/global_context.h" #include "msg/Messenger.h" #include "mon/MonClient.h" #include "osdc/ObjectCacher.h" #include "client/MetaRequest.h" #include "client/Client.h" #include "messages/MClientReclaim.h" #include "messages/MClientSession.h" #include "common/async/blocked_completion.h" #define dout_subsys ceph_subsys_client namespace bs = boost::system; namespace ca = ceph::async; class ClientScaffold : public Client { public: ClientScaffold(Messenger *m, MonClient *mc, Objecter *objecter_) : Client(m, mc, objecter_) {} virtual ~ClientScaffold() { } int check_dummy_op(const UserPerm& perms){ RWRef_t mref_reader(mount_state, CLIENT_MOUNTING); if (!mref_reader.is_state_satisfied()) { return -CEPHFS_ENOTCONN; } std::scoped_lock l(client_lock); MetaRequest *req = new MetaRequest(CEPH_MDS_OP_DUMMY); int res = make_request(req, perms); ldout(cct, 10) << __func__ << " result=" << res << dendl; return res; } int send_unknown_session_op(int op) { RWRef_t mref_reader(mount_state, CLIENT_MOUNTING); if (!mref_reader.is_state_satisfied()) { return -CEPHFS_ENOTCONN; } std::scoped_lock l(client_lock); auto session = _get_or_open_mds_session(0); auto msg = make_message<MClientSession>(op, session->seq); int res = session->con->send_message2(std::move(msg)); ldout(cct, 10) << __func__ << " result=" << res << dendl; return res; } bool check_client_blocklisted() { RWRef_t mref_reader(mount_state, CLIENT_MOUNTING); if (!mref_reader.is_state_satisfied()) { return -CEPHFS_ENOTCONN; } std::scoped_lock l(client_lock); bs::error_code ec; ldout(cct, 20) << __func__ << ": waiting for latest osdmap" << dendl; objecter->wait_for_latest_osdmap(ca::use_blocked[ec]); ldout(cct, 20) << __func__ << ": got latest osdmap: " << ec << dendl; const auto myaddrs = messenger->get_myaddrs(); return objecter->with_osdmap([&](const OSDMap& o) {return o.is_blocklisted(myaddrs);}); } bool check_unknown_reclaim_flag(uint32_t flag) { RWRef_t mref_reader(mount_state, CLIENT_MOUNTING); if (!mref_reader.is_state_satisfied()) { return -CEPHFS_ENOTCONN; } std::scoped_lock l(client_lock); char uuid[256]; sprintf(uuid, "unknownreclaimflag:%x", getpid()); auto session = _get_or_open_mds_session(0); auto m = make_message<MClientReclaim>(uuid, flag); ceph_assert(session->con->send_message2(std::move(m)) == 0); wait_on_list(waiting_for_reclaim); return session->reclaim_state == MetaSession::RECLAIM_FAIL ? true : false; } }; class TestClient : public ::testing::Test { public: static void SetUpTestSuite() { icp.start(g_ceph_context->_conf.get_val<std::uint64_t>("client_asio_thread_count")); } static void TearDownTestSuite() { icp.stop(); } void SetUp() override { messenger = Messenger::create_client_messenger(g_ceph_context, "client"); if (messenger->start() != 0) { throw std::runtime_error("failed to start messenger"); } mc = new MonClient(g_ceph_context, icp); if (mc->build_initial_monmap() < 0) { throw std::runtime_error("build monmap"); } mc->set_messenger(messenger); mc->set_want_keys(CEPH_ENTITY_TYPE_MDS | CEPH_ENTITY_TYPE_OSD); if (mc->init() < 0) { throw std::runtime_error("init monclient"); } objecter = new Objecter(g_ceph_context, messenger, mc, icp); objecter->set_client_incarnation(0); objecter->init(); messenger->add_dispatcher_tail(objecter); objecter->start(); client = new ClientScaffold(messenger, mc, objecter); client->init(); client->mount("/", myperm, true); } void TearDown() override { if (client->is_mounted()) client->unmount(); client->shutdown(); objecter->shutdown(); mc->shutdown(); messenger->shutdown(); messenger->wait(); delete client; client = nullptr; delete objecter; objecter = nullptr; delete mc; mc = nullptr; delete messenger; messenger = nullptr; } protected: static inline ceph::async::io_context_pool icp; static inline UserPerm myperm{0,0}; MonClient* mc = nullptr; Messenger* messenger = nullptr; Objecter* objecter = nullptr; ClientScaffold* client = nullptr; };
4,990
32.05298
98
h
null
ceph-main/src/test/client/alternate_name.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2021 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <errno.h> #include <iostream> #include <string> #include <fmt/format.h> #include "test/client/TestClient.h" TEST_F(TestClient, AlternateNameRemount) { auto altname = std::string("foo"); auto dir = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); ASSERT_EQ(0, client->mkdir(dir.c_str(), 0777, myperm, altname)); client->unmount(); TearDown(); SetUp(); client->mount("/", myperm, true); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(dir.c_str(), &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname); } ASSERT_EQ(0, client->rmdir(dir.c_str(), myperm)); } TEST_F(TestClient, AlternateNameMkdir) { auto dir = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); ASSERT_EQ(0, client->mkdir(dir.c_str(), 0777, myperm, "foo")); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(dir.c_str(), &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, "foo"); } ASSERT_EQ(0, client->rmdir(dir.c_str(), myperm)); } TEST_F(TestClient, AlternateNameLong) { auto altname = std::string(4096+1024, '-'); auto dir = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); ASSERT_EQ(0, client->mkdir(dir.c_str(), 0777, myperm, altname)); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(dir.c_str(), &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname); } ASSERT_EQ(0, client->rmdir(dir.c_str(), myperm)); } TEST_F(TestClient, AlternateNameCreat) { auto altname = std::string("foo"); auto file = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); int fd = client->open(file.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(file, &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname); } } TEST_F(TestClient, AlternateNameSymlink) { auto altname = std::string("foo"); auto file = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); int fd = client->open(file.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); auto file2 = file+"2"; auto altname2 = altname+"2"; ASSERT_EQ(0, client->symlink(file.c_str(), file2.c_str(), myperm, altname2)); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(file2, &wdr, myperm, false)); ASSERT_EQ(wdr.alternate_name, altname2); ASSERT_EQ(0, client->walk(file, &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname); } } TEST_F(TestClient, AlternateNameRename) { auto altname = std::string("foo"); auto file = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); int fd = client->open(file.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); auto file2 = file+"2"; auto altname2 = altname+"2"; ASSERT_EQ(0, client->rename(file.c_str(), file2.c_str(), myperm, altname2)); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(file2, &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname2); } } TEST_F(TestClient, AlternateNameRenameExistMatch) { auto altname = std::string("foo"); auto file = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); int fd = client->open(file.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); auto file2 = file+"2"; auto altname2 = altname+"2"; fd = client->open(file2.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname2); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); ASSERT_EQ(0, client->rename(file.c_str(), file2.c_str(), myperm, altname2)); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(file2, &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname2); } } TEST_F(TestClient, AlternateNameRenameExistMisMatch) { auto altname = std::string("foo"); auto file = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); int fd = client->open(file.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); auto file2 = file+"2"; auto altname2 = altname+"2"; fd = client->open(file2.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname+"mismatch"); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); ASSERT_EQ(-EINVAL, client->rename(file.c_str(), file2.c_str(), myperm, altname2)); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(file2, &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname+"mismatch"); } } TEST_F(TestClient, AlternateNameLink) { auto altname = std::string("foo"); auto file = fmt::format("{}_{}", ::testing::UnitTest::GetInstance()->current_test_info()->name(), getpid()); int fd = client->open(file.c_str(), O_CREAT|O_WRONLY, myperm, 0777, altname); ASSERT_LE(0, fd); ASSERT_EQ(3, client->write(fd, "baz", 3, 0)); ASSERT_EQ(0, client->close(fd)); auto file2 = file+"2"; auto altname2 = altname+"2"; ASSERT_EQ(0, client->link(file.c_str(), file2.c_str(), myperm, altname2)); { Client::walk_dentry_result wdr; ASSERT_EQ(0, client->walk(file2, &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname2); ASSERT_EQ(0, client->walk(file, &wdr, myperm)); ASSERT_EQ(wdr.alternate_name, altname); } }
6,354
31.09596
110
cc
null
ceph-main/src/test/client/iozone.sh
#!/usr/bin/env bash set -e name=`echo $0 | sed 's/\//_/g'` mkdir $name cd $name iozone -c -e -s 1024M -r 16K -t 1 -F f1 -i 0 -i 1 iozone -c -e -s 1024M -r 1M -t 1 -F f2 -i 0 -i 1 iozone -c -e -s 10240M -r 1M -t 1 -F f3 -i 0 -i 1 cd ..
238
17.384615
49
sh
null
ceph-main/src/test/client/kernel_untar_build.sh
#!/usr/bin/env bash set -e name=`echo $0 | sed 's/\//_/g'` mkdir $name cd $name tar jxvf /root/linux* cd linux* make defconfig make cd .. rm -r linux*
153
10
31
sh
null
ceph-main/src/test/client/main.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * Copyright (C) 2016 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "gtest/gtest.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "global/global_context.h" int main(int argc, char **argv) { auto args = argv_to_vec(argc, argv); [[maybe_unused]] auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
820
27.310345
108
cc
null
ceph-main/src/test/client/ops.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2022 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <errno.h> #include "TestClient.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-matchers.h" TEST_F(TestClient, CheckDummyOP) { ASSERT_EQ(client->check_dummy_op(myperm), -EOPNOTSUPP); } TEST_F(TestClient, CheckUnknownSessionOp) { ASSERT_EQ(client->send_unknown_session_op(-1), 0); sleep(5); ASSERT_EQ(client->check_client_blocklisted(), true); } TEST_F(TestClient, CheckZeroReclaimFlag) { ASSERT_EQ(client->check_unknown_reclaim_flag(0), true); } TEST_F(TestClient, CheckUnknownReclaimFlag) { ASSERT_EQ(client->check_unknown_reclaim_flag(2), true); } TEST_F(TestClient, CheckNegativeReclaimFlagUnmasked) { ASSERT_EQ(client->check_unknown_reclaim_flag(-1 & ~MClientReclaim::FLAG_FINISH), true); } TEST_F(TestClient, CheckNegativeReclaimFlag) { ASSERT_EQ(client->check_unknown_reclaim_flag(-1), true); }
1,342
28.195652
89
cc
null
ceph-main/src/test/cls_2pc_queue/test_cls_2pc_queue.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "cls/2pc_queue/cls_2pc_queue_types.h" #include "cls/2pc_queue/cls_2pc_queue_client.h" #include "cls/queue/cls_queue_client.h" #include "cls/2pc_queue/cls_2pc_queue_types.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include "global/global_context.h" #include <string> #include <vector> #include <algorithm> #include <thread> #include <chrono> #include <atomic> using namespace std; class TestCls2PCQueue : public ::testing::Test { protected: librados::Rados rados; std::string pool_name; librados::IoCtx ioctx; void SetUp() override { pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); } void TearDown() override { ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } }; TEST_F(TestCls2PCQueue, GetCapacity) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 8*1024; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size; const int ret = cls_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(max_size, size); } TEST_F(TestCls2PCQueue, AsyncGetCapacity) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 8*1024; librados::ObjectWriteOperation wop; wop.create(true); cls_2pc_queue_init(wop, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &wop)); librados::ObjectReadOperation rop; bufferlist bl; int rc; cls_2pc_queue_get_capacity(rop, &bl, &rc); ASSERT_EQ(0, ioctx.operate(queue_name, &rop, nullptr)); ASSERT_EQ(0, rc); uint64_t size; ASSERT_EQ(cls_2pc_queue_get_capacity_result(bl, size), 0); ASSERT_EQ(max_size, size); } TEST_F(TestCls2PCQueue, Reserve) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024U*1024U; const auto number_of_ops = 10U; const auto number_of_elements = 23U; const auto size_to_reserve = 250U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_EQ(res_id, i+1); } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), number_of_ops); for (const auto& r : reservations) { ASSERT_NE(r.first, cls_2pc_reservation::NO_ID); ASSERT_GT(r.second.timestamp.time_since_epoch().count(), 0); } } TEST_F(TestCls2PCQueue, AsyncReserve) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024U*1024U; constexpr auto number_of_ops = 10U; constexpr auto number_of_elements = 23U; const auto size_to_reserve = 250U; librados::ObjectWriteOperation wop; wop.create(true); cls_2pc_queue_init(wop, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &wop)); for (auto i = 0U; i < number_of_ops; ++i) { bufferlist res_bl; int res_rc; cls_2pc_queue_reserve(wop, size_to_reserve, number_of_elements, &res_bl, &res_rc); ASSERT_EQ(0, ioctx.operate(queue_name, &wop, librados::OPERATION_RETURNVEC)); ASSERT_EQ(res_rc, 0); cls_2pc_reservation::id_t res_id; ASSERT_EQ(0, cls_2pc_queue_reserve_result(res_bl, res_id)); ASSERT_EQ(res_id, i+1); } bufferlist bl; int rc; librados::ObjectReadOperation rop; cls_2pc_queue_list_reservations(rop, &bl, &rc); ASSERT_EQ(0, ioctx.operate(queue_name, &rop, nullptr)); ASSERT_EQ(0, rc); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations_result(bl, reservations)); ASSERT_EQ(reservations.size(), number_of_ops); for (const auto& r : reservations) { ASSERT_NE(r.first, cls_2pc_reservation::NO_ID); ASSERT_GT(r.second.timestamp.time_since_epoch().count(), 0); } } TEST_F(TestCls2PCQueue, Commit) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024*128; const auto number_of_ops = 200U; const auto number_of_elements = 23U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); for (auto i = 0U; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); auto total_size = 0UL; std::vector<bufferlist> data(number_of_elements); // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix, &total_size] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); total_size += bl.length(); return bl; }); cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, total_size, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); cls_2pc_queue_commit(op, data, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, Abort) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024U*1024U; const auto number_of_ops = 17U; const auto number_of_elements = 23U; const auto size_to_reserve = 250U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); cls_2pc_queue_abort(op, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, ReserveError) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 256U*1024U; const auto number_of_ops = 254U; const auto number_of_elements = 1U; const auto size_to_reserve = 1024U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); cls_2pc_reservation::id_t res_id; for (auto i = 0U; i < number_of_ops-1; ++i) { ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); } res_id = cls_2pc_reservation::NO_ID; // this one is failing because it exceeds the queue size ASSERT_NE(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_EQ(res_id, cls_2pc_reservation::NO_ID); // this one is failing because it tries to reserve 0 entries ASSERT_NE(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, 0, res_id), 0); // this one is failing because it tries to reserve 0 bytes ASSERT_NE(cls_2pc_queue_reserve(ioctx, queue_name, 0, number_of_elements, res_id), 0); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), number_of_ops-1); for (const auto& r : reservations) { ASSERT_NE(r.first, cls_2pc_reservation::NO_ID); ASSERT_GT(r.second.timestamp.time_since_epoch().count(), 0); } } TEST_F(TestCls2PCQueue, CommitError) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 17U; const auto number_of_elements = 23U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); const auto invalid_reservation_op = 8; const auto invalid_elements_op = 11; std::vector<bufferlist> invalid_data(number_of_elements+3); // create vector of buffer lists std::generate(invalid_data.begin(), invalid_data.end(), [j = 0] () mutable { bufferlist bl; bl.append("invalid data is larger that regular data" + to_string(j++)); return bl; }); for (auto i = 0U; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); std::vector<bufferlist> data(number_of_elements); auto total_size = 0UL; // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix, &total_size] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); total_size += bl.length(); return bl; }); cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, total_size, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); if (i == invalid_reservation_op) { // fail on a commits with invalid reservation id cls_2pc_queue_commit(op, data, res_id+999); ASSERT_NE(0, ioctx.operate(queue_name, &op)); } else if (i == invalid_elements_op) { // fail on a commits when data size is larger than the reserved one cls_2pc_queue_commit(op, invalid_data, res_id); ASSERT_NE(0, ioctx.operate(queue_name, &op)); } else { cls_2pc_queue_commit(op, data, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); // 2 reservations were not comitted ASSERT_EQ(reservations.size(), 2); } TEST_F(TestCls2PCQueue, AbortError) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 17U; const auto number_of_elements = 23U; const auto size_to_reserve = 250U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); const auto invalid_reservation_op = 8; for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); if (i == invalid_reservation_op) { // aborting a reservation which does not exists // is a no-op, not an error cls_2pc_queue_abort(op, res_id+999); } else { cls_2pc_queue_abort(op, res_id); } ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); // 1 reservation was not aborted ASSERT_EQ(reservations.size(), 1); } TEST_F(TestCls2PCQueue, MultiReserve) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 11U; const auto number_of_elements = 23U; const auto max_producer_count = 10U; const auto size_to_reserve = 250U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); std::vector<std::thread> producers(max_producer_count); for (auto& p : producers) { p = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, 0); } }); } std::for_each(producers.begin(), producers.end(), [](auto& p) { p.join(); }); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), number_of_ops*max_producer_count); auto total_reservations = 0U; for (const auto& r : reservations) { total_reservations += r.second.size; } ASSERT_EQ(total_reservations, number_of_ops*max_producer_count*size_to_reserve); } TEST_F(TestCls2PCQueue, MultiCommit) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 11U; const auto number_of_elements = 23U; const auto max_producer_count = 10U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); std::vector<std::thread> producers(max_producer_count); for (auto& p : producers) { p = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); std::vector<bufferlist> data(number_of_elements); auto total_size = 0UL; // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix, &total_size] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); total_size += bl.length(); return bl; }); cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, total_size, number_of_elements, res_id), 0); ASSERT_NE(res_id, 0); cls_2pc_queue_commit(op, data, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); } std::for_each(producers.begin(), producers.end(), [](auto& p) { p.join(); }); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, MultiAbort) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 11U; const auto number_of_elements = 23U; const auto max_producer_count = 10U; const auto size_to_reserve = 250U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); std::vector<std::thread> producers(max_producer_count); for (auto& p : producers) { p = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, 0); cls_2pc_queue_abort(op, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); } std::for_each(producers.begin(), producers.end(), [](auto& p) { p.join(); }); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, ReserveCommit) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 11U; const auto number_of_elements = 23U; const auto max_workers = 10U; const auto size_to_reserve = 512U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); std::vector<std::thread> reservers(max_workers); for (auto& r : reservers) { r = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); } }); } auto committer = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; int remaining_ops = number_of_ops*max_workers; while (remaining_ops > 0) { const std::string element_prefix("op-" +to_string(remaining_ops) + "-element-"); std::vector<bufferlist> data(number_of_elements); // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); return bl; }); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); for (const auto& r : reservations) { cls_2pc_queue_commit(op, data, r.first); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); --remaining_ops; } } }); std::for_each(reservers.begin(), reservers.end(), [](auto& r) { r.join(); }); committer.join(); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, ReserveAbort) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 17U; const auto number_of_elements = 23U; const auto max_workers = 10U; const auto size_to_reserve = 250U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); std::vector<std::thread> reservers(max_workers); for (auto& r : reservers) { r = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); } }); } auto aborter = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; int remaining_ops = number_of_ops*max_workers; while (remaining_ops > 0) { cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); for (const auto& r : reservations) { cls_2pc_queue_abort(op, r.first); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); --remaining_ops; } } }); std::for_each(reservers.begin(), reservers.end(), [](auto& r) { r.join(); }); aborter.join(); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, ManualCleanup) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 128*1024*1024; const auto number_of_ops = 17U; const auto number_of_elements = 23U; const auto max_workers = 10U; const auto size_to_reserve = 512U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // anything older than 100ms is cosidered stale ceph::coarse_real_time stale_time = ceph::coarse_real_clock::now() + std::chrono::milliseconds(100); std::vector<std::thread> reservers(max_workers); for (auto& r : reservers) { r = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); // wait for 10ms between each reservation to make sure at least some are stale std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); } auto cleaned_reservations = 0U; auto committed_reservations = 0U; auto aborter = std::thread([this, &queue_name, &stale_time, &cleaned_reservations, &committed_reservations] { librados::ObjectWriteOperation op; int remaining_ops = number_of_ops*max_workers; while (remaining_ops > 0) { cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); for (const auto& r : reservations) { if (r.second.timestamp > stale_time) { // abort stale reservations cls_2pc_queue_abort(op, r.first); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); ++cleaned_reservations; } else { // commit good reservations const std::string element_prefix("op-" +to_string(remaining_ops) + "-element-"); std::vector<bufferlist> data(number_of_elements); // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); return bl; }); cls_2pc_queue_commit(op, data, r.first); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); ++committed_reservations; } --remaining_ops; } } }); std::for_each(reservers.begin(), reservers.end(), [](auto& r) { r.join(); }); aborter.join(); ASSERT_GT(cleaned_reservations, 0); ASSERT_EQ(committed_reservations + cleaned_reservations, number_of_ops*max_workers); cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, Cleanup) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 128*1024*1024; const auto number_of_ops = 15U; const auto number_of_elements = 23U; const auto max_workers = 10U; const auto size_to_reserve = 512U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // anything older than 100ms is cosidered stale ceph::coarse_real_time stale_time = ceph::coarse_real_clock::now() + std::chrono::milliseconds(100); std::vector<std::thread> reservers(max_workers); for (auto& r : reservers) { r = std::thread([this, &queue_name] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); // wait for 10ms between each reservation to make sure at least some are stale std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); } std::for_each(reservers.begin(), reservers.end(), [](auto& r) { r.join(); }); cls_2pc_reservations all_reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, all_reservations)); ASSERT_EQ(all_reservations.size(), number_of_ops*max_workers); cls_2pc_queue_expire_reservations(op, stale_time); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); cls_2pc_reservations good_reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, good_reservations)); for (const auto& r : all_reservations) { if (good_reservations.find(r.first) == good_reservations.end()) { // not in the "good" list ASSERT_GE(stale_time.time_since_epoch().count(), r.second.timestamp.time_since_epoch().count()); } } for (const auto& r : good_reservations) { ASSERT_LT(stale_time.time_since_epoch().count(), r.second.timestamp.time_since_epoch().count()); } } TEST_F(TestCls2PCQueue, MultiProducer) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 128*1024*1024; const auto number_of_ops = 300U; const auto number_of_elements = 23U; const auto max_producer_count = 10U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); auto producer_count = max_producer_count; std::vector<std::thread> producers(max_producer_count); for (auto& p : producers) { p = std::thread([this, &queue_name, &producer_count] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); std::vector<bufferlist> data(number_of_elements); auto total_size = 0UL; // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix, &total_size] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); total_size += bl.length(); return bl; }); cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, total_size, number_of_elements, res_id), 0); ASSERT_NE(res_id, 0); cls_2pc_queue_commit(op, data, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } --producer_count; }); } auto consume_count = 0U; std::thread consumer([this, &queue_name, &consume_count, &producer_count] { librados::ObjectWriteOperation op; const auto max_elements = 42; const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; while (producer_count > 0 || truncated) { const auto ret = cls_2pc_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); consume_count += entries.size(); cls_2pc_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); std::for_each(producers.begin(), producers.end(), [](auto& p) { p.join(); }); consumer.join(); ASSERT_EQ(consume_count, number_of_ops*number_of_elements*max_producer_count); } TEST_F(TestCls2PCQueue, AsyncConsumer) { const std::string queue_name = __PRETTY_FUNCTION__; constexpr auto max_size = 128*1024*1024; constexpr auto number_of_ops = 250U; constexpr auto number_of_elements = 23U; librados::ObjectWriteOperation wop; wop.create(true); cls_2pc_queue_init(wop, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &wop)); for (auto i = 0U; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); std::vector<bufferlist> data(number_of_elements); auto total_size = 0UL; // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix, &total_size] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); total_size += bl.length(); return bl; }); cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, total_size, number_of_elements, res_id), 0); ASSERT_NE(res_id, 0); cls_2pc_queue_commit(wop, data, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &wop)); } constexpr auto max_elements = 42; std::string marker; std::string end_marker; librados::ObjectReadOperation rop; auto consume_count = 0U; std::vector<cls_queue_entry> entries; bool truncated = true; while (truncated) { bufferlist bl; int rc; cls_2pc_queue_list_entries(rop, marker, max_elements, &bl, &rc); ASSERT_EQ(0, ioctx.operate(queue_name, &rop, nullptr)); ASSERT_EQ(rc, 0); ASSERT_EQ(cls_2pc_queue_list_entries_result(bl, entries, &truncated, end_marker), 0); consume_count += entries.size(); cls_2pc_queue_remove_entries(wop, end_marker); marker = end_marker; } ASSERT_EQ(consume_count, number_of_ops*number_of_elements); // execute all delete operations in a batch ASSERT_EQ(0, ioctx.operate(queue_name, &wop)); // make sure that queue is empty ASSERT_EQ(cls_2pc_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker), 0); ASSERT_EQ(entries.size(), 0); } TEST_F(TestCls2PCQueue, MultiProducerConsumer) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024*1024; const auto number_of_ops = 300U; const auto number_of_elements = 23U; const auto max_workers = 10U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); auto producer_count = max_workers; auto retry_happened = false; std::vector<std::thread> producers(max_workers); for (auto& p : producers) { p = std::thread([this, &queue_name, &producer_count, &retry_happened] { librados::ObjectWriteOperation op; for (auto i = 0U; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); std::vector<bufferlist> data(number_of_elements); auto total_size = 0UL; // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix, &total_size] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); total_size += bl.length(); return bl; }); cls_2pc_reservation::id_t res_id = cls_2pc_reservation::NO_ID; auto rc = cls_2pc_queue_reserve(ioctx, queue_name, total_size, number_of_elements, res_id); while (rc != 0) { // other errors should cause test to fail ASSERT_EQ(rc, -ENOSPC); ASSERT_EQ(res_id, 0); // queue is full, sleep and retry retry_happened = true; std::this_thread::sleep_for(std::chrono::milliseconds(10)); rc = cls_2pc_queue_reserve(ioctx, queue_name, total_size, number_of_elements, res_id); }; ASSERT_NE(res_id, 0); cls_2pc_queue_commit(op, data, res_id); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } --producer_count; }); } const auto max_elements = 128; std::vector<std::thread> consumers(max_workers/2); for (auto& c : consumers) { c = std::thread([this, &queue_name, &producer_count] { librados::ObjectWriteOperation op; const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; while (producer_count > 0 || truncated) { const auto ret = cls_2pc_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); if (entries.empty()) { // queue is empty, let it fill std::this_thread::sleep_for(std::chrono::milliseconds(100)); } else { cls_2pc_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } } }); } std::for_each(producers.begin(), producers.end(), [](auto& p) { p.join(); }); std::for_each(consumers.begin(), consumers.end(), [](auto& c) { c.join(); }); if (!retry_happened) { std::cerr << "Queue was never full - all reservations were sucessfull." << "Please decrease the amount of consumer threads" << std::endl; } // make sure that queue is empty and no reservations remain cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; ASSERT_EQ(0, cls_2pc_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker)); ASSERT_EQ(entries.size(), 0); } TEST_F(TestCls2PCQueue, ReserveSpillover) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024U*1024U; const auto number_of_ops = 1024U; const auto number_of_elements = 8U; const auto size_to_reserve = 64U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), number_of_ops); for (const auto& r : reservations) { ASSERT_NE(r.first, cls_2pc_reservation::NO_ID); ASSERT_GT(r.second.timestamp.time_since_epoch().count(), 0); } } TEST_F(TestCls2PCQueue, CommitSpillover) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024U*1024U; const auto number_of_ops = 1024U; const auto number_of_elements = 4U; const auto size_to_reserve = 128U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); for (const auto& r : reservations) { const std::string element_prefix("foo"); std::vector<bufferlist> data(number_of_elements); auto total_size = 0UL; // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix, &total_size] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); total_size += bl.length(); return bl; }); ASSERT_NE(r.first, cls_2pc_reservation::NO_ID); cls_2pc_queue_commit(op, data, r.first); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); } TEST_F(TestCls2PCQueue, AbortSpillover) { const std::string queue_name = __PRETTY_FUNCTION__; const auto max_size = 1024U*1024U; const auto number_of_ops = 1024U; const auto number_of_elements = 4U; const auto size_to_reserve = 128U; librados::ObjectWriteOperation op; op.create(true); cls_2pc_queue_init(op, queue_name, max_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); for (auto i = 0U; i < number_of_ops; ++i) { cls_2pc_reservation::id_t res_id; ASSERT_EQ(cls_2pc_queue_reserve(ioctx, queue_name, size_to_reserve, number_of_elements, res_id), 0); ASSERT_NE(res_id, cls_2pc_reservation::NO_ID); } cls_2pc_reservations reservations; ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); for (const auto& r : reservations) { ASSERT_NE(r.first, cls_2pc_reservation::NO_ID); cls_2pc_queue_abort(op, r.first); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } ASSERT_EQ(0, cls_2pc_queue_list_reservations(ioctx, queue_name, reservations)); ASSERT_EQ(reservations.size(), 0); }
35,982
36.134159
130
cc
null
ceph-main/src/test/cls_cas/test_cls_cas.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "include/stringify.h" #include "cls/cas/cls_cas_client.h" #include "cls/cas/cls_cas_internal.h" #include "include/utime.h" #include "common/Clock.h" #include "global/global_context.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include <errno.h> #include <string> #include <vector> using namespace std; /// creates a temporary pool and initializes an IoCtx for each test class cls_cas : public ::testing::Test { librados::Rados rados; std::string pool_name; protected: librados::IoCtx ioctx; void SetUp() { pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); } void TearDown() { /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } }; static librados::ObjectWriteOperation *new_op() { return new librados::ObjectWriteOperation(); } /* static librados::ObjectReadOperation *new_rop() { return new librados::ObjectReadOperation(); } */ TEST_F(cls_cas, get_put) { bufferlist bl; bl.append("my data"); string oid = "mychunk"; hobject_t ref1, ref2, ref3; ref1.oid.name = "foo1"; ref2.oid.name = "foo2"; ref3.oid.name = "foo3"; // initially the object does not exist bufferlist t; ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); // write { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref1, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // get x3 { auto op = new_op(); cls_cas_chunk_get_ref(*op, ref2); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // get again { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref3, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // 3x puts to remove { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref1); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref3); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref2); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); // get { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref1, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // put { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref1); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); } TEST_F(cls_cas, wrong_put) { bufferlist bl; bl.append("my data"); string oid = "mychunk"; hobject_t ref1, ref2; ref1.oid.name = "foo1"; ref2.oid.name = "foo2"; // initially the object does not exist bufferlist t; ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); // write { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref1, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // put wrong thing { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref2); ASSERT_EQ(-ENOLINK, ioctx.operate(oid, op)); } { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref1); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); } TEST_F(cls_cas, dup_get) { bufferlist bl; bl.append("my data"); string oid = "mychunk"; hobject_t ref1; ref1.oid.name = "foo1"; // initially the object does not exist bufferlist t; ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); // duplicated entries are allowed by "by_object". as it tracks refs of the same // hobject_t for snapshot support. int n_refs = 0; // write { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref1, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); n_refs++; } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // dup create_or_get_ref, get_ref will succeed but take no additional ref // only if the chunk_refs' type is not "by_object" { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref1, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); n_refs++; } { auto op = new_op(); cls_cas_chunk_get_ref(*op, ref1); ASSERT_EQ(0, ioctx.operate(oid, op)); n_refs++; } for (int i = 0; i < n_refs; i++) { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref1); ASSERT_EQ(0, ioctx.operate(oid, op)); if (i < n_refs - 1) { // should not referenced anymore, but by_object is an exception // and by_object is used by default. ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); } else { // the last reference was removed ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); } } } TEST_F(cls_cas, dup_put) { bufferlist bl; bl.append("my data"); string oid = "mychunk"; hobject_t ref1; ref1.oid.name = "foo1"; // initially the object does not exist bufferlist t; ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); // write { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref1, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref1); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref1); ASSERT_EQ(-ENOENT, ioctx.operate(oid, op)); } } TEST_F(cls_cas, get_wrong_data) { bufferlist bl, bl2; bl.append("my data"); bl2.append("my different data"); string oid = "mychunk"; hobject_t ref1, ref2; ref1.oid.name = "foo1"; ref2.oid.name = "foo2"; // initially the object does not exist bufferlist t; ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); // get { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref1, bl); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // get w/ different data // with verify { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref2, bl2, true); ASSERT_EQ(-ENOMSG, ioctx.operate(oid, op)); } // without verify { auto op = new_op(); cls_cas_chunk_create_or_get_ref(*op, ref2, bl2, false); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); // put { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref1); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(bl.length(), ioctx.read(oid, t, 0, 0)); { auto op = new_op(); cls_cas_chunk_put_ref(*op, ref2); ASSERT_EQ(0, ioctx.operate(oid, op)); } ASSERT_EQ(-ENOENT, ioctx.read(oid, t, 0, 0)); } static int count_bits(unsigned long n) { // base case if (n == 0) return 0; else return 1 + count_bits(n & (n - 1)); } TEST(chunk_refs_t, size) { chunk_refs_t r; size_t max = 1048576; // mix in pool changes as i gets bigger size_t pool_mask = 0xfff5110; // eventually add in a zillion different pools to force us to a raw count size_t pool_cutoff = max/2; for (size_t i = 1; i <= max; ++i) { hobject_t h(sobject_t(object_t("foo"s + stringify(i)), i)); h.pool = i > pool_cutoff ? i : (i & pool_mask); r.get(h); if (count_bits(i) <= 2) { bufferlist bl; r.dynamic_encode(bl, 512); if (count_bits(i) == 1) { cout << i << "\t" << bl.length() << "\t" << r.describe_encoding() << std::endl; } // verify reencoding is correct chunk_refs_t a; auto t = bl.cbegin(); decode(a, t); bufferlist bl2; encode(a, bl2); if (!bl.contents_equal(bl2)) { std::unique_ptr<Formatter> f(Formatter::create("json-pretty")); cout << "original:\n"; f->dump_object("refs", r); f->flush(cout); cout << "decoded:\n"; f->dump_object("refs", a); f->flush(cout); cout << "original encoding:\n"; bl.hexdump(cout); cout << "decoded re-encoding:\n"; bl2.hexdump(cout); ASSERT_TRUE(bl.contents_equal(bl2)); } } } ASSERT_EQ(max, r.count()); for (size_t i = 1; i <= max; ++i) { hobject_t h(sobject_t(object_t("foo"s + stringify(i)), 1)); h.pool = i > pool_cutoff ? i : (i & pool_mask); bool ret = r.put(h); ASSERT_TRUE(ret); } ASSERT_EQ(0, r.count()); }
8,706
22.596206
81
cc
null
ceph-main/src/test/cls_cmpomap/test_cls_cmpomap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #include "cls/cmpomap/client.h" #include "test/librados/test_cxx.h" #include "gtest/gtest.h" #include <optional> // create/destroy a pool that's shared by all tests in the process struct RadosEnv : public ::testing::Environment { static std::optional<std::string> pool_name; public: static librados::Rados rados; static librados::IoCtx ioctx; void SetUp() override { // create pool std::string name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(name, rados)); pool_name = name; ASSERT_EQ(rados.ioctx_create(name.c_str(), ioctx), 0); } void TearDown() override { ioctx.close(); if (pool_name) { ASSERT_EQ(destroy_one_pool_pp(*pool_name, rados), 0); } } }; std::optional<std::string> RadosEnv::pool_name; librados::Rados RadosEnv::rados; librados::IoCtx RadosEnv::ioctx; auto *const rados_env = ::testing::AddGlobalTestEnvironment(new RadosEnv); namespace cls::cmpomap { // test fixture with helper functions class CmpOmap : public ::testing::Test { protected: librados::IoCtx& ioctx = RadosEnv::ioctx; int do_cmp_vals(const std::string& oid, Mode mode, Op comparison, ComparisonMap values, std::optional<bufferlist> def = std::nullopt) { librados::ObjectReadOperation op; int ret = cmp_vals(op, mode, comparison, std::move(values), std::move(def)); if (ret < 0) { return ret; } return ioctx.operate(oid, &op, nullptr); } int do_cmp_set_vals(const std::string& oid, Mode mode, Op comparison, ComparisonMap values, std::optional<bufferlist> def = std::nullopt) { librados::ObjectWriteOperation op; int ret = cmp_set_vals(op, mode, comparison, std::move(values), std::move(def)); if (ret < 0) { return ret; } return ioctx.operate(oid, &op); } int do_cmp_rm_keys(const std::string& oid, Mode mode, Op comparison, ComparisonMap values) { librados::ObjectWriteOperation op; int ret = cmp_rm_keys(op, mode, comparison, std::move(values)); if (ret < 0) { return ret; } return ioctx.operate(oid, &op); } int get_vals(const std::string& oid, std::map<std::string, bufferlist>* vals) { std::string marker; bool more = false; do { std::map<std::string, bufferlist> tmp; int r = ioctx.omap_get_vals2(oid, marker, 1000, &tmp, &more); if (r < 0) { return r; } if (!tmp.empty()) { marker = tmp.rbegin()->first; vals->merge(std::move(tmp)); } } while (more); return 0; } }; TEST_F(CmpOmap, cmp_vals_noexist_str) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; // compare a nonempty value against a missing key with no default const bufferlist input = string_buffer("a"); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::EQ, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::NE, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GT, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GTE, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LT, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LTE, {{key, input}}), -ECANCELED); } TEST_F(CmpOmap, cmp_vals_noexist_str_default) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; // compare a nonempty value against a missing key with nonempty default const bufferlist input = string_buffer("a"); const bufferlist def = string_buffer("b"); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::EQ, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::NE, {{key, input}}, def), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GT, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GTE, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LT, {{key, input}}, def), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LTE, {{key, input}}, def), 0); } TEST_F(CmpOmap, cmp_vals_noexist_u64) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; // 0 != nullopt const bufferlist input = u64_buffer(0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, input}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, input}}), -ECANCELED); } TEST_F(CmpOmap, cmp_vals_noexist_u64_default) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; // 1 == noexist const bufferlist input = u64_buffer(1); const bufferlist def = u64_buffer(2); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, input}}, def), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, input}}, def), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, input}}, def), 0); } TEST_F(CmpOmap, cmp_vals_str) { const std::string oid = __PRETTY_FUNCTION__; const std::string key = "key"; ASSERT_EQ(ioctx.omap_set(oid, {{key, string_buffer("bbb")}}), 0); { // empty < existing const bufferlist empty; EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::EQ, {{key, empty}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::NE, {{key, empty}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GT, {{key, empty}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GTE, {{key, empty}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LT, {{key, empty}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LTE, {{key, empty}}), 0); } { // value < existing const bufferlist value = string_buffer("aaa"); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::EQ, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::NE, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GT, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GTE, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LT, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LTE, {{key, value}}), 0); } { // value > existing const bufferlist value = string_buffer("bbbb"); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::EQ, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::NE, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GT, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::GTE, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LT, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::String, Op::LTE, {{key, value}}), -ECANCELED); } } TEST_F(CmpOmap, cmp_vals_u64) { const std::string oid = __PRETTY_FUNCTION__; const std::string key = "key"; ASSERT_EQ(ioctx.omap_set(oid, {{key, u64_buffer(42)}}), 0); { // 0 < existing const bufferlist value = u64_buffer(0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, value}}), 0); } { // 42 == existing const bufferlist value = u64_buffer(42); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, value}}), 0); } { // uint64-max > existing uint64_t v = std::numeric_limits<uint64_t>::max(); const bufferlist value = u64_buffer(v); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, value}}), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, value}}), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, value}}), -ECANCELED); } } TEST_F(CmpOmap, cmp_vals_u64_invalid_input) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; const bufferlist empty; // empty buffer can't be decoded as u64 const bufferlist def = u64_buffer(0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, empty}}, def), -EINVAL); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, empty}}, def), -EINVAL); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, empty}}, def), -EINVAL); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, empty}}, def), -EINVAL); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, empty}}, def), -EINVAL); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, empty}}, def), -EINVAL); } TEST_F(CmpOmap, cmp_vals_u64_invalid_default) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; const bufferlist input = u64_buffer(0); const bufferlist def = string_buffer("bbb"); // can't be decoded as u64 EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, input}}, def), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, input}}, def), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, input}}, def), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, input}}, def), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, input}}, def), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, input}}, def), -EIO); } TEST_F(CmpOmap, cmp_vals_u64_empty_default) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; const bufferlist input = u64_buffer(1); const bufferlist def; // empty buffer defaults to 0 EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, input}}, def), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, input}}, def), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, input}}, def), 0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, input}}, def), -ECANCELED); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, input}}, def), -ECANCELED); } TEST_F(CmpOmap, cmp_vals_u64_invalid_value) { const std::string oid = __PRETTY_FUNCTION__; ASSERT_EQ(ioctx.create(oid, true), 0); const std::string key = "key"; ASSERT_EQ(ioctx.omap_set(oid, {{key, string_buffer("bbb")}}), 0); const bufferlist input = u64_buffer(0); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::EQ, {{key, input}}), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::NE, {{key, input}}), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GT, {{key, input}}), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::GTE, {{key, input}}), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LT, {{key, input}}), -EIO); EXPECT_EQ(do_cmp_vals(oid, Mode::U64, Op::LTE, {{key, input}}), -EIO); } TEST_F(CmpOmap, cmp_vals_at_max_keys) { ComparisonMap comparisons; const bufferlist empty; for (uint32_t i = 0; i < max_keys; i++) { comparisons.emplace(std::to_string(i), empty); } librados::ObjectReadOperation op; EXPECT_EQ(cmp_vals(op, Mode::String, Op::EQ, std::move(comparisons), empty), 0); } TEST_F(CmpOmap, cmp_vals_over_max_keys) { ComparisonMap comparisons; const bufferlist empty; for (uint32_t i = 0; i < max_keys + 1; i++) { comparisons.emplace(std::to_string(i), empty); } librados::ObjectReadOperation op; EXPECT_EQ(cmp_vals(op, Mode::String, Op::EQ, std::move(comparisons), empty), -E2BIG); } TEST_F(CmpOmap, cmp_set_vals_noexist_str) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value = string_buffer("bbb"); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::EQ, {{"eq", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::NE, {{"ne", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::GT, {{"gt", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::GTE, {{"gte", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::LT, {{"lt", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::LTE, {{"lte", value}}), 0); std::map<std::string, bufferlist> vals; EXPECT_EQ(get_vals(oid, &vals), -ENOENT); // never got created } TEST_F(CmpOmap, cmp_set_vals_noexist_str_default) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value = string_buffer("bbb"); const bufferlist def; EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::EQ, {{"eq", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::NE, {{"ne", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::GT, {{"gt", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::GTE, {{"gte", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::LT, {{"lt", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::String, Op::LTE, {{"lte", value}}, def), 0); std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); EXPECT_EQ(vals.count("eq"), 0); EXPECT_EQ(vals.count("ne"), 1); EXPECT_EQ(vals.count("gt"), 1); EXPECT_EQ(vals.count("gte"), 1); EXPECT_EQ(vals.count("lt"), 0); EXPECT_EQ(vals.count("lte"), 0); } TEST_F(CmpOmap, cmp_set_vals_noexist_u64) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value = u64_buffer(0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::EQ, {{"eq", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::NE, {{"ne", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::GT, {{"gt", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::GTE, {{"gte", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::LT, {{"lt", value}}), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::LTE, {{"lte", value}}), 0); std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), -ENOENT); } TEST_F(CmpOmap, cmp_set_vals_noexist_u64_default) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value = u64_buffer(0); const bufferlist def = u64_buffer(0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::EQ, {{"eq", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::NE, {{"ne", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::GT, {{"gt", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::GTE, {{"gte", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::LT, {{"lt", value}}, def), 0); EXPECT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::LTE, {{"lte", value}}, def), 0); std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); EXPECT_EQ(vals.count("eq"), 1); EXPECT_EQ(vals.count("ne"), 0); EXPECT_EQ(vals.count("gt"), 0); EXPECT_EQ(vals.count("gte"), 1); EXPECT_EQ(vals.count("lt"), 0); EXPECT_EQ(vals.count("lte"), 1); } TEST_F(CmpOmap, cmp_set_vals_str) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value1 = string_buffer("bbb"); const bufferlist value2 = string_buffer("ccc"); { std::map<std::string, bufferlist> vals = { {"eq", value1}, {"ne", value1}, {"gt", value1}, {"gte", value1}, {"lt", value1}, {"lte", value1}, }; ASSERT_EQ(ioctx.omap_set(oid, vals), 0); } ASSERT_EQ(do_cmp_set_vals(oid, Mode::String, Op::EQ, {{"eq", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::String, Op::NE, {{"ne", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::String, Op::GT, {{"gt", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::String, Op::GTE, {{"gte", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::String, Op::LT, {{"lt", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::String, Op::LTE, {{"lte", value2}}), 0); { std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); ASSERT_EQ(vals.size(), 6); EXPECT_EQ(value1, vals["eq"]); EXPECT_EQ(value2, vals["ne"]); EXPECT_EQ(value2, vals["gt"]); EXPECT_EQ(value2, vals["gte"]); EXPECT_EQ(value1, vals["lt"]); EXPECT_EQ(value1, vals["lte"]); } } TEST_F(CmpOmap, cmp_set_vals_u64) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value1 = u64_buffer(0); const bufferlist value2 = u64_buffer(42); { std::map<std::string, bufferlist> vals = { {"eq", value1}, {"ne", value1}, {"gt", value1}, {"gte", value1}, {"lt", value1}, {"lte", value1}, }; ASSERT_EQ(ioctx.omap_set(oid, vals), 0); } ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::EQ, {{"eq", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::NE, {{"ne", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::GT, {{"gt", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::GTE, {{"gte", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::LT, {{"lt", value2}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::LTE, {{"lte", value2}}), 0); { std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); ASSERT_EQ(vals.size(), 6); EXPECT_EQ(value1, vals["eq"]); EXPECT_EQ(value2, vals["ne"]); EXPECT_EQ(value2, vals["gt"]); EXPECT_EQ(value2, vals["gte"]); EXPECT_EQ(value1, vals["lt"]); EXPECT_EQ(value1, vals["lte"]); } } TEST_F(CmpOmap, cmp_set_vals_u64_einval) { const std::string oid = __PRETTY_FUNCTION__; const std::string key = "key"; const bufferlist value1 = u64_buffer(0); const bufferlist value2 = string_buffer("ccc"); ASSERT_EQ(ioctx.omap_set(oid, {{key, value1}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::EQ, {{key, value2}}), -EINVAL); } TEST_F(CmpOmap, cmp_set_vals_u64_eio) { const std::string oid = __PRETTY_FUNCTION__; const std::string key = "key"; const bufferlist value1 = string_buffer("ccc"); const bufferlist value2 = u64_buffer(0); ASSERT_EQ(ioctx.omap_set(oid, {{key, value1}}), 0); ASSERT_EQ(do_cmp_set_vals(oid, Mode::U64, Op::EQ, {{key, value2}}), 0); { std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); ASSERT_EQ(vals.size(), 1); EXPECT_EQ(value1, vals[key]); } } TEST_F(CmpOmap, cmp_set_vals_at_max_keys) { ComparisonMap comparisons; const bufferlist value = u64_buffer(0); for (uint32_t i = 0; i < max_keys; i++) { comparisons.emplace(std::to_string(i), value); } librados::ObjectWriteOperation op; EXPECT_EQ(cmp_set_vals(op, Mode::U64, Op::EQ, std::move(comparisons), std::nullopt), 0); } TEST_F(CmpOmap, cmp_set_vals_over_max_keys) { ComparisonMap comparisons; const bufferlist value = u64_buffer(0); for (uint32_t i = 0; i < max_keys + 1; i++) { comparisons.emplace(std::to_string(i), value); } librados::ObjectWriteOperation op; EXPECT_EQ(cmp_set_vals(op, Mode::U64, Op::EQ, std::move(comparisons), std::nullopt), -E2BIG); } TEST_F(CmpOmap, cmp_rm_keys_noexist_str) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist empty; ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::EQ, {{"eq", empty}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::NE, {{"ne", empty}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::GT, {{"gt", empty}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::GTE, {{"gte", empty}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::LT, {{"lt", empty}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::LTE, {{"lte", empty}}), 0); std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), -ENOENT); } TEST_F(CmpOmap, cmp_rm_keys_noexist_u64) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value = u64_buffer(0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::EQ, {{"eq", value}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::NE, {{"ne", value}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::GT, {{"gt", value}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::GTE, {{"gte", value}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::LT, {{"lt", value}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::LTE, {{"lte", value}}), 0); std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), -ENOENT); } TEST_F(CmpOmap, cmp_rm_keys_str) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value1 = string_buffer("bbb"); const bufferlist value2 = string_buffer("ccc"); { std::map<std::string, bufferlist> vals = { {"eq", value1}, {"ne", value1}, {"gt", value1}, {"gte", value1}, {"lt", value1}, {"lte", value1}, }; ASSERT_EQ(ioctx.omap_set(oid, vals), 0); } ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::EQ, {{"eq", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::NE, {{"ne", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::GT, {{"gt", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::GTE, {{"gte", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::LT, {{"lt", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::String, Op::LTE, {{"lte", value2}}), 0); { std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); EXPECT_EQ(vals.count("eq"), 1); EXPECT_EQ(vals.count("ne"), 0); EXPECT_EQ(vals.count("gt"), 0); EXPECT_EQ(vals.count("gte"), 0); EXPECT_EQ(vals.count("lt"), 1); EXPECT_EQ(vals.count("lte"), 1); } } TEST_F(CmpOmap, cmp_rm_keys_u64) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value1 = u64_buffer(0); const bufferlist value2 = u64_buffer(42); { std::map<std::string, bufferlist> vals = { {"eq", value1}, {"ne", value1}, {"gt", value1}, {"gte", value1}, {"lt", value1}, {"lte", value1}, }; ASSERT_EQ(ioctx.omap_set(oid, vals), 0); } ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::EQ, {{"eq", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::NE, {{"ne", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::GT, {{"gt", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::GTE, {{"gte", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::LT, {{"lt", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::LTE, {{"lte", value2}}), 0); { std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); EXPECT_EQ(vals.count("eq"), 1); EXPECT_EQ(vals.count("ne"), 0); EXPECT_EQ(vals.count("gt"), 0); EXPECT_EQ(vals.count("gte"), 0); EXPECT_EQ(vals.count("lt"), 1); EXPECT_EQ(vals.count("lte"), 1); } } TEST_F(CmpOmap, cmp_rm_keys_u64_einval) { const std::string oid = __PRETTY_FUNCTION__; const std::string key = "key"; const bufferlist value1 = u64_buffer(0); const bufferlist value2 = string_buffer("ccc"); ASSERT_EQ(ioctx.omap_set(oid, {{key, value1}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::EQ, {{key, value2}}), -EINVAL); } TEST_F(CmpOmap, cmp_rm_keys_u64_eio) { const std::string oid = __PRETTY_FUNCTION__; const std::string key = "key"; const bufferlist value1 = string_buffer("ccc"); const bufferlist value2 = u64_buffer(0); ASSERT_EQ(ioctx.omap_set(oid, {{key, value1}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::EQ, {{key, value2}}), 0); { std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); EXPECT_EQ(vals.count(key), 1); } } TEST_F(CmpOmap, cmp_rm_keys_at_max_keys) { ComparisonMap comparisons; const bufferlist value = u64_buffer(0); for (uint32_t i = 0; i < max_keys; i++) { comparisons.emplace(std::to_string(i), value); } librados::ObjectWriteOperation op; EXPECT_EQ(cmp_rm_keys(op, Mode::U64, Op::EQ, std::move(comparisons)), 0); } TEST_F(CmpOmap, cmp_rm_keys_over_max_keys) { ComparisonMap comparisons; const bufferlist value = u64_buffer(0); for (uint32_t i = 0; i < max_keys + 1; i++) { comparisons.emplace(std::to_string(i), value); } librados::ObjectWriteOperation op; EXPECT_EQ(cmp_rm_keys(op, Mode::U64, Op::EQ, std::move(comparisons)), -E2BIG); } // test upgrades from empty omap values to u64 TEST_F(CmpOmap, cmp_rm_keys_u64_empty) { const std::string oid = __PRETTY_FUNCTION__; const bufferlist value1; // empty buffer const bufferlist value2 = u64_buffer(42); { std::map<std::string, bufferlist> vals = { {"eq", value1}, {"ne", value1}, {"gt", value1}, {"gte", value1}, {"lt", value1}, {"lte", value1}, }; ASSERT_EQ(ioctx.omap_set(oid, vals), 0); } ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::EQ, {{"eq", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::NE, {{"ne", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::GT, {{"gt", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::GTE, {{"gte", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::LT, {{"lt", value2}}), 0); ASSERT_EQ(do_cmp_rm_keys(oid, Mode::U64, Op::LTE, {{"lte", value2}}), 0); { std::map<std::string, bufferlist> vals; ASSERT_EQ(get_vals(oid, &vals), 0); EXPECT_EQ(vals.count("eq"), 1); EXPECT_EQ(vals.count("ne"), 0); EXPECT_EQ(vals.count("gt"), 0); EXPECT_EQ(vals.count("gte"), 0); EXPECT_EQ(vals.count("lt"), 1); EXPECT_EQ(vals.count("lte"), 1); } } } // namespace cls::cmpomap
27,120
36.615811
95
cc
null
ceph-main/src/test/cls_hello/test_cls_hello.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 Inktank * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <errno.h> #include <string> #include "include/rados/librados.hpp" #include "include/encoding.h" #include "test/librados/test_cxx.h" #include "gtest/gtest.h" #include "json_spirit/json_spirit.h" using namespace librados; TEST(ClsHello, SayHello) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist in, out; ASSERT_EQ(-ENOENT, ioctx.exec("myobject", "hello", "say_hello", in, out)); ASSERT_EQ(0, ioctx.write_full("myobject", in)); ASSERT_EQ(0, ioctx.exec("myobject", "hello", "say_hello", in, out)); ASSERT_EQ(std::string("Hello, world!"), std::string(out.c_str(), out.length())); out.clear(); in.append("Tester"); ASSERT_EQ(0, ioctx.exec("myobject", "hello", "say_hello", in, out)); ASSERT_EQ(std::string("Hello, Tester!"), std::string(out.c_str(), out.length())); out.clear(); in.clear(); char buf[4096]; memset(buf, 1, sizeof(buf)); in.append(buf, sizeof(buf)); ASSERT_EQ(-EINVAL, ioctx.exec("myobject", "hello", "say_hello", in, out)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsHello, RecordHello) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist in, out; ASSERT_EQ(0, ioctx.exec("myobject", "hello", "record_hello", in, out)); ASSERT_EQ(-EEXIST, ioctx.exec("myobject", "hello", "record_hello", in, out)); in.append("Tester"); ASSERT_EQ(0, ioctx.exec("myobject2", "hello", "record_hello", in, out)); ASSERT_EQ(-EEXIST, ioctx.exec("myobject2", "hello", "record_hello", in, out)); ASSERT_EQ(0u, out.length()); in.clear(); out.clear(); ASSERT_EQ(0, ioctx.exec("myobject", "hello", "replay", in, out)); ASSERT_EQ(std::string("Hello, world!"), std::string(out.c_str(), out.length())); out.clear(); ASSERT_EQ(0, ioctx.exec("myobject2", "hello", "replay", in, out)); ASSERT_EQ(std::string("Hello, Tester!"), std::string(out.c_str(), out.length())); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } static std::string _get_required_osd_release(Rados& cluster) { bufferlist inbl; std::string cmd = std::string("{\"prefix\": \"osd dump\",\"format\":\"json\"}"); bufferlist outbl; int r = cluster.mon_command(cmd, inbl, &outbl, NULL); ceph_assert(r >= 0); std::string outstr(outbl.c_str(), outbl.length()); json_spirit::Value v; if (!json_spirit::read(outstr, v)) { std::cerr <<" unable to parse json " << outstr << std::endl; return ""; } json_spirit::Object& o = v.get_obj(); for (json_spirit::Object::size_type i=0; i<o.size(); i++) { json_spirit::Pair& p = o[i]; if (p.name_ == "require_osd_release") { std::cout << "require_osd_release = " << p.value_.get_str() << std::endl; return p.value_.get_str(); } } std::cerr << "didn't find require_osd_release in " << outstr << std::endl; return ""; } TEST(ClsHello, WriteReturnData) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); // skip test if not yet mimic if (_get_required_osd_release(cluster) < "octopus") { std::cout << "cluster is not yet octopus, skipping test" << std::endl; return; } // this will return nothing -- no flag is set bufferlist in, out; ASSERT_EQ(0, ioctx.exec("myobject", "hello", "write_return_data", in, out)); ASSERT_EQ(std::string(), std::string(out.c_str(), out.length())); // this will return an error due to unexpected input. // note that we set the RETURNVEC flag here so that we *reliably* get the // "too much input data!" return data string. do it lots of times so we are // more likely to resend a request and hit the dup op handling path. char buf[4096]; memset(buf, 1, sizeof(buf)); for (unsigned i=0; i<1000; ++i) { std::cout << i << std::endl; in.clear(); in.append(buf, sizeof(buf)); int rval; ObjectWriteOperation o; o.exec("hello", "write_return_data", in, &out, &rval); librados::AioCompletion *completion = cluster.aio_create_completion(); ASSERT_EQ(0, ioctx.aio_operate("foo", completion, &o, librados::OPERATION_RETURNVEC)); completion->wait_for_complete(); ASSERT_EQ(-EINVAL, completion->get_return_value()); ASSERT_EQ(-EINVAL, rval); ASSERT_EQ(std::string("too much input data!"), std::string(out.c_str(), out.length())); } ASSERT_EQ(-ENOENT, ioctx.getxattr("myobject2", "foo", out)); // this *will* return data due to the RETURNVEC flag // using a-sync call { in.clear(); out.clear(); int rval; ObjectWriteOperation o; o.exec("hello", "write_return_data", in, &out, &rval); librados::AioCompletion *completion = cluster.aio_create_completion(); ASSERT_EQ(0, ioctx.aio_operate("foo", completion, &o, librados::OPERATION_RETURNVEC)); completion->wait_for_complete(); ASSERT_EQ(42, completion->get_return_value()); ASSERT_EQ(42, rval); out.hexdump(std::cout); ASSERT_EQ("you might see this", std::string(out.c_str(), out.length())); } // using sync call { in.clear(); out.clear(); int rval; ObjectWriteOperation o; o.exec("hello", "write_return_data", in, &out, &rval); ASSERT_EQ(42, ioctx.operate("foo", &o, librados::OPERATION_RETURNVEC)); ASSERT_EQ(42, rval); out.hexdump(std::cout); ASSERT_EQ("you might see this", std::string(out.c_str(), out.length())); } // this will overflow because the return data is too big { in.clear(); out.clear(); int rval; ObjectWriteOperation o; o.exec("hello", "write_too_much_return_data", in, &out, &rval); librados::AioCompletion *completion = cluster.aio_create_completion(); ASSERT_EQ(0, ioctx.aio_operate("foo", completion, &o, librados::OPERATION_RETURNVEC)); completion->wait_for_complete(); ASSERT_EQ(-EOVERFLOW, completion->get_return_value()); ASSERT_EQ(-EOVERFLOW, rval); ASSERT_EQ("", std::string(out.c_str(), out.length())); } ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsHello, Loud) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist in, out; ASSERT_EQ(0, ioctx.exec("myobject", "hello", "record_hello", in, out)); ASSERT_EQ(0, ioctx.exec("myobject", "hello", "replay", in, out)); ASSERT_EQ(std::string("Hello, world!"), std::string(out.c_str(), out.length())); ASSERT_EQ(0, ioctx.exec("myobject", "hello", "turn_it_to_11", in, out)); ASSERT_EQ(0, ioctx.exec("myobject", "hello", "replay", in, out)); ASSERT_EQ(std::string("HELLO, WORLD!"), std::string(out.c_str(), out.length())); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsHello, BadMethods) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist in, out; ASSERT_EQ(0, ioctx.write_full("myobject", in)); ASSERT_EQ(-EIO, ioctx.exec("myobject", "hello", "bad_reader", in, out)); ASSERT_EQ(-EIO, ioctx.exec("myobject", "hello", "bad_writer", in, out)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsHello, Filter) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist obj_content; obj_content.append(buf, sizeof(buf)); std::string target_str = "content"; // Write xattr bare, no ::encod'ing bufferlist target_val; target_val.append(target_str); bufferlist nontarget_val; nontarget_val.append("rhubarb"); ASSERT_EQ(0, ioctx.write("has_xattr", obj_content, obj_content.length(), 0)); ASSERT_EQ(0, ioctx.write("has_wrong_xattr", obj_content, obj_content.length(), 0)); ASSERT_EQ(0, ioctx.write("no_xattr", obj_content, obj_content.length(), 0)); ASSERT_EQ(0, ioctx.setxattr("has_xattr", "theattr", target_val)); ASSERT_EQ(0, ioctx.setxattr("has_wrong_xattr", "theattr", nontarget_val)); bufferlist filter_bl; std::string filter_name = "hello.hello"; encode(filter_name, filter_bl); encode("_theattr", filter_bl); encode(target_str, filter_bl); NObjectIterator iter(ioctx.nobjects_begin(filter_bl)); bool foundit = false; int k = 0; while (iter != ioctx.nobjects_end()) { foundit = true; // We should only see the object that matches the filter ASSERT_EQ((*iter).get_oid(), "has_xattr"); // We should only see it once ASSERT_EQ(k, 0); ++iter; ++k; } ASSERT_TRUE(foundit); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); }
9,493
32.429577
91
cc
null
ceph-main/src/test/cls_journal/test_cls_journal.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "cls/journal/cls_journal_client.h" #include "include/stringify.h" #include "common/Cond.h" #include "test/librados/test_cxx.h" #include "gtest/gtest.h" #include <errno.h> #include <set> #include <string> using namespace cls::journal; static bool is_sparse_read_supported(librados::IoCtx &ioctx, const std::string &oid) { EXPECT_EQ(0, ioctx.create(oid, true)); bufferlist inbl; inbl.append(std::string(1, 'X')); EXPECT_EQ(0, ioctx.write(oid, inbl, inbl.length(), 1)); EXPECT_EQ(0, ioctx.write(oid, inbl, inbl.length(), 3)); std::map<uint64_t, uint64_t> m; bufferlist outbl; int r = ioctx.sparse_read(oid, m, outbl, 4, 0); ioctx.remove(oid); int expected_r = 2; std::map<uint64_t, uint64_t> expected_m = {{1, 1}, {3, 1}}; bufferlist expected_outbl; expected_outbl.append(std::string(2, 'X')); return (r == expected_r && m == expected_m && outbl.contents_equal(expected_outbl)); } class TestClsJournal : public ::testing::Test { public: static void SetUpTestCase() { _pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(_pool_name, _rados)); } static void TearDownTestCase() { ASSERT_EQ(0, destroy_one_pool_pp(_pool_name, _rados)); } std::string get_temp_image_name() { ++_image_number; return "image" + stringify(_image_number); } static std::string _pool_name; static librados::Rados _rados; static uint64_t _image_number; }; std::string TestClsJournal::_pool_name; librados::Rados TestClsJournal::_rados; uint64_t TestClsJournal::_image_number = 0; TEST_F(TestClsJournal, Create) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); uint8_t order = 1; uint8_t splay_width = 2; int64_t pool_id = ioctx.get_id(); ASSERT_EQ(0, client::create(ioctx, oid, order, splay_width, pool_id)); uint8_t read_order; uint8_t read_splay_width; int64_t read_pool_id; C_SaferCond cond; client::get_immutable_metadata(ioctx, oid, &read_order, &read_splay_width, &read_pool_id, &cond); ASSERT_EQ(0, cond.wait()); ASSERT_EQ(order, read_order); ASSERT_EQ(splay_width, read_splay_width); ASSERT_EQ(pool_id, read_pool_id); } TEST_F(TestClsJournal, MinimumSet) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); librados::ObjectWriteOperation op1; client::set_active_set(&op1, 300); ASSERT_EQ(0, ioctx.operate(oid, &op1)); uint64_t minimum_set = 123; librados::ObjectWriteOperation op2; client::set_minimum_set(&op2, minimum_set); ASSERT_EQ(0, ioctx.operate(oid, &op2)); C_SaferCond cond; uint64_t read_minimum_set; uint64_t read_active_set; std::set<cls::journal::Client> read_clients; client::get_mutable_metadata(ioctx, oid, &read_minimum_set, &read_active_set, &read_clients, &cond); ASSERT_EQ(0, cond.wait()); ASSERT_EQ(minimum_set, read_minimum_set); } TEST_F(TestClsJournal, MinimumSetStale) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); librados::ObjectWriteOperation op1; client::set_active_set(&op1, 300); ASSERT_EQ(0, ioctx.operate(oid, &op1)); uint64_t minimum_set = 123; librados::ObjectWriteOperation op2; client::set_minimum_set(&op2, minimum_set); ASSERT_EQ(0, ioctx.operate(oid, &op2)); librados::ObjectWriteOperation op3; client::set_minimum_set(&op3, 1); ASSERT_EQ(-ESTALE, ioctx.operate(oid, &op3)); C_SaferCond cond; uint64_t read_minimum_set; uint64_t read_active_set; std::set<cls::journal::Client> read_clients; client::get_mutable_metadata(ioctx, oid, &read_minimum_set, &read_active_set, &read_clients, &cond); ASSERT_EQ(0, cond.wait()); ASSERT_EQ(minimum_set, read_minimum_set); } TEST_F(TestClsJournal, MinimumSetOrderConstraint) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); librados::ObjectWriteOperation op1; client::set_minimum_set(&op1, 123); ASSERT_EQ(-EINVAL, ioctx.operate(oid, &op1)); C_SaferCond cond; uint64_t read_minimum_set; uint64_t read_active_set; std::set<cls::journal::Client> read_clients; client::get_mutable_metadata(ioctx, oid, &read_minimum_set, &read_active_set, &read_clients, &cond); ASSERT_EQ(0, cond.wait()); ASSERT_EQ(0U, read_minimum_set); } TEST_F(TestClsJournal, ActiveSet) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); uint64_t active_set = 234; librados::ObjectWriteOperation op1; client::set_active_set(&op1, active_set); ASSERT_EQ(0, ioctx.operate(oid, &op1)); C_SaferCond cond; uint64_t read_minimum_set; uint64_t read_active_set; std::set<cls::journal::Client> read_clients; client::get_mutable_metadata(ioctx, oid, &read_minimum_set, &read_active_set, &read_clients, &cond); ASSERT_EQ(0, cond.wait()); ASSERT_EQ(active_set, read_active_set); } TEST_F(TestClsJournal, ActiveSetStale) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); librados::ObjectWriteOperation op1; client::set_active_set(&op1, 345); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; client::set_active_set(&op2, 3); ASSERT_EQ(-ESTALE, ioctx.operate(oid, &op2)); } TEST_F(TestClsJournal, CreateDuplicate) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); ASSERT_EQ(-EEXIST, client::create(ioctx, oid, 3, 5, ioctx.get_id())); } TEST_F(TestClsJournal, GetClient) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); Client client; ASSERT_EQ(-ENOENT, client::get_client(ioctx, oid, "id", &client)); bufferlist data; data.append(std::string(128, '1')); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", data)); ASSERT_EQ(0, client::get_client(ioctx, oid, "id1", &client)); Client expected_client("id1", data); ASSERT_EQ(expected_client, client); } TEST_F(TestClsJournal, ClientRegister) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); std::set<Client> clients; ASSERT_EQ(0, client::client_list(ioctx, oid, &clients)); std::set<Client> expected_clients = {Client("id1", bufferlist())}; ASSERT_EQ(expected_clients, clients); } TEST_F(TestClsJournal, ClientRegisterDuplicate) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(-EEXIST, client::client_register(ioctx, oid, "id1", bufferlist())); } TEST_F(TestClsJournal, ClientUpdateData) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); ASSERT_EQ(-ENOENT, client::client_update_data(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); bufferlist data; data.append(std::string(128, '1')); ASSERT_EQ(0, client::client_update_data(ioctx, oid, "id1", data)); Client client; ASSERT_EQ(0, client::get_client(ioctx, oid, "id1", &client)); Client expected_client("id1", data); ASSERT_EQ(expected_client, client); } TEST_F(TestClsJournal, ClientUpdateState) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); ASSERT_EQ(-ENOENT, client::client_update_state(ioctx, oid, "id1", CLIENT_STATE_DISCONNECTED)); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); bufferlist data; data.append(std::string(128, '1')); ASSERT_EQ(0, client::client_update_state(ioctx, oid, "id1", CLIENT_STATE_DISCONNECTED)); Client client; ASSERT_EQ(0, client::get_client(ioctx, oid, "id1", &client)); Client expected_client; expected_client.id = "id1"; expected_client.state = CLIENT_STATE_DISCONNECTED; ASSERT_EQ(expected_client, client); } TEST_F(TestClsJournal, ClientUnregister) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(0, client::client_unregister(ioctx, oid, "id1")); } TEST_F(TestClsJournal, ClientUnregisterDNE) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 4, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(0, client::client_unregister(ioctx, oid, "id1")); ASSERT_EQ(-ENOENT, client::client_unregister(ioctx, oid, "id1")); } TEST_F(TestClsJournal, ClientUnregisterPruneTags) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 2, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id2", bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 0, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 1, Tag::TAG_CLASS_NEW, bufferlist())); for (uint32_t i = 2; i <= 96; ++i) { ASSERT_EQ(0, client::tag_create(ioctx, oid, i, 1, bufferlist())); } librados::ObjectWriteOperation op1; client::client_commit(&op1, "id1", {{{1, 32, 120}}}); ASSERT_EQ(0, ioctx.operate(oid, &op1)); ASSERT_EQ(0, client::client_unregister(ioctx, oid, "id2")); std::set<Tag> expected_tags = {{0, 0, {}}}; for (uint32_t i = 32; i <= 96; ++i) { expected_tags.insert({i, 1, {}}); } std::set<Tag> tags; ASSERT_EQ(0, client::tag_list(ioctx, oid, "id1", boost::optional<uint64_t>(), &tags)); ASSERT_EQ(expected_tags, tags); } TEST_F(TestClsJournal, ClientCommit) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 2, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); cls::journal::ObjectPositions object_positions; object_positions = { cls::journal::ObjectPosition(0, 234, 120), cls::journal::ObjectPosition(3, 235, 121)}; cls::journal::ObjectSetPosition object_set_position( object_positions); librados::ObjectWriteOperation op2; client::client_commit(&op2, "id1", object_set_position); ASSERT_EQ(0, ioctx.operate(oid, &op2)); std::set<Client> clients; ASSERT_EQ(0, client::client_list(ioctx, oid, &clients)); std::set<Client> expected_clients = { Client("id1", bufferlist(), object_set_position)}; ASSERT_EQ(expected_clients, clients); } TEST_F(TestClsJournal, ClientCommitInvalid) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 2, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); cls::journal::ObjectPositions object_positions; object_positions = { cls::journal::ObjectPosition(0, 234, 120), cls::journal::ObjectPosition(4, 234, 121), cls::journal::ObjectPosition(5, 235, 121)}; cls::journal::ObjectSetPosition object_set_position( object_positions); librados::ObjectWriteOperation op2; client::client_commit(&op2, "id1", object_set_position); ASSERT_EQ(-EINVAL, ioctx.operate(oid, &op2)); } TEST_F(TestClsJournal, ClientCommitDNE) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); cls::journal::ObjectSetPosition object_set_position; librados::ObjectWriteOperation op1; client::client_commit(&op1, "id1", object_set_position); ASSERT_EQ(-ENOENT, ioctx.operate(oid, &op1)); } TEST_F(TestClsJournal, ClientList) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 12, 5, ioctx.get_id())); std::set<Client> expected_clients; librados::ObjectWriteOperation op1; for (uint32_t i = 0; i < 512; ++i) { std::string id = "id" + stringify(i + 1); expected_clients.insert(Client(id, bufferlist())); client::client_register(&op1, id, bufferlist()); } ASSERT_EQ(0, ioctx.operate(oid, &op1)); std::set<Client> clients; ASSERT_EQ(0, client::client_list(ioctx, oid, &clients)); ASSERT_EQ(expected_clients, clients); C_SaferCond cond; uint64_t read_minimum_set; uint64_t read_active_set; std::set<cls::journal::Client> read_clients; client::get_mutable_metadata(ioctx, oid, &read_minimum_set, &read_active_set, &read_clients, &cond); ASSERT_EQ(0, cond.wait()); ASSERT_EQ(expected_clients, read_clients); } TEST_F(TestClsJournal, GetNextTagTid) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); uint64_t tag_tid; ASSERT_EQ(-ENOENT, client::get_next_tag_tid(ioctx, oid, &tag_tid)); ASSERT_EQ(0, client::create(ioctx, oid, 2, 2, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(0, client::get_next_tag_tid(ioctx, oid, &tag_tid)); ASSERT_EQ(0U, tag_tid); ASSERT_EQ(0, client::tag_create(ioctx, oid, 0, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(0, client::get_next_tag_tid(ioctx, oid, &tag_tid)); ASSERT_EQ(1U, tag_tid); } TEST_F(TestClsJournal, TagCreate) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(-ENOENT, client::tag_create(ioctx, oid, 0, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(0, client::create(ioctx, oid, 2, 2, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(-ESTALE, client::tag_create(ioctx, oid, 1, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(-EINVAL, client::tag_create(ioctx, oid, 0, 1, bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 0, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(-EEXIST, client::tag_create(ioctx, oid, 0, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 1, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 2, 1, bufferlist())); std::set<Tag> expected_tags = { {0, 0, {}}, {1, 1, {}}, {2, 1, {}}}; std::set<Tag> tags; ASSERT_EQ(0, client::tag_list(ioctx, oid, "id1", boost::optional<uint64_t>(), &tags)); ASSERT_EQ(expected_tags, tags); } TEST_F(TestClsJournal, TagCreatePrunesTags) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 2, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 0, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 1, Tag::TAG_CLASS_NEW, bufferlist())); ASSERT_EQ(0, client::tag_create(ioctx, oid, 2, 1, bufferlist())); librados::ObjectWriteOperation op1; client::client_commit(&op1, "id1", {{{1, 2, 120}}}); ASSERT_EQ(0, ioctx.operate(oid, &op1)); ASSERT_EQ(0, client::tag_create(ioctx, oid, 3, 0, bufferlist())); std::set<Tag> expected_tags = { {0, 0, {}}, {2, 1, {}}, {3, 0, {}}}; std::set<Tag> tags; ASSERT_EQ(0, client::tag_list(ioctx, oid, "id1", boost::optional<uint64_t>(), &tags)); ASSERT_EQ(expected_tags, tags); } TEST_F(TestClsJournal, TagList) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ASSERT_EQ(0, client::create(ioctx, oid, 2, 2, ioctx.get_id())); ASSERT_EQ(0, client::client_register(ioctx, oid, "id1", bufferlist())); std::set<Tag> expected_all_tags; std::set<Tag> expected_filtered_tags; for (uint32_t i = 0; i < 96; ++i) { uint64_t tag_class = Tag::TAG_CLASS_NEW; if (i > 1) { tag_class = i % 2 == 0 ? 0 : 1; } Tag tag(i, i % 2 == 0 ? 0 : 1, bufferlist()); expected_all_tags.insert(tag); if (i % 2 == 0) { expected_filtered_tags.insert(tag); } ASSERT_EQ(0, client::tag_create(ioctx, oid, i, tag_class, bufferlist())); } std::set<Tag> tags; ASSERT_EQ(0, client::tag_list(ioctx, oid, "id1", boost::optional<uint64_t>(), &tags)); ASSERT_EQ(expected_all_tags, tags); ASSERT_EQ(0, client::tag_list(ioctx, oid, "id1", boost::optional<uint64_t>(0), &tags)); ASSERT_EQ(expected_filtered_tags, tags); librados::ObjectWriteOperation op1; client::client_commit(&op1, "id1", {{{96, 0, 120}}}); ASSERT_EQ(0, ioctx.operate(oid, &op1)); ASSERT_EQ(0, client::tag_list(ioctx, oid, "id1", boost::optional<uint64_t>(), &tags)); ASSERT_EQ(expected_all_tags, tags); } TEST_F(TestClsJournal, GuardAppend) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); bufferlist bl; bl.append("journal entry!"); librados::ObjectWriteOperation op1; op1.append(bl); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; client::guard_append(&op2, 1024); ASSERT_EQ(0, ioctx.operate(oid, &op2)); } TEST_F(TestClsJournal, GuardAppendDNE) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); librados::ObjectWriteOperation op2; client::guard_append(&op2, 1024); ASSERT_EQ(0, ioctx.operate(oid, &op2)); } TEST_F(TestClsJournal, GuardAppendOverflow) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); bufferlist bl; bl.append("journal entry!"); librados::ObjectWriteOperation op1; op1.append(bl); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; client::guard_append(&op2, 1); ASSERT_EQ(-EOVERFLOW, ioctx.operate(oid, &op2)); } TEST_F(TestClsJournal, Append) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); ioctx.remove(oid); bool sparse_read_supported = is_sparse_read_supported(ioctx, oid); bufferlist bl; bl.append("journal entry!"); librados::ObjectWriteOperation op1; client::append(&op1, 1, bl); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; client::append(&op2, 1, bl); ASSERT_EQ(-EOVERFLOW, ioctx.operate(oid, &op2)); bufferlist outbl; ASSERT_LE(bl.length(), ioctx.read(oid, outbl, 0, 0)); bufferlist tmpbl; tmpbl.substr_of(outbl, 0, bl.length()); ASSERT_TRUE(bl.contents_equal(tmpbl)); if (outbl.length() == bl.length()) { std::cout << "padding is not enabled" << std::endl; return; } tmpbl.clear(); tmpbl.substr_of(outbl, bl.length(), outbl.length() - bl.length()); ASSERT_TRUE(tmpbl.is_zero()); if (!sparse_read_supported) { std::cout << "sparse_read is not supported" << std::endl; return; } librados::ObjectWriteOperation op3; client::append(&op3, 1 << 24, bl); ASSERT_EQ(0, ioctx.operate(oid, &op3)); std::map<uint64_t, uint64_t> m; uint64_t pad_len = outbl.length(); outbl.clear(); std::map<uint64_t, uint64_t> expected_m = {{0, bl.length()}, {pad_len, bl.length()}}; ASSERT_EQ(expected_m.size(), ioctx.sparse_read(oid, m, outbl, 2 * pad_len, 0)); ASSERT_EQ(m, expected_m); uint64_t buffer_offset = 0; for (auto &it : m) { tmpbl.clear(); tmpbl.substr_of(outbl, buffer_offset, it.second); ASSERT_TRUE(bl.contents_equal(tmpbl)); buffer_offset += it.second; } }
22,225
30.933908
81
cc
null
ceph-main/src/test/cls_lock/test_cls_lock.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <errno.h> #include "include/types.h" #include "common/Clock.h" #include "msg/msg_types.h" #include "include/rados/librados.hpp" #include "test/librados/test_cxx.h" #include "gtest/gtest.h" #include "cls/lock/cls_lock_client.h" #include "cls/lock/cls_lock_ops.h" using namespace std; using namespace librados; using namespace rados::cls::lock; void lock_info(IoCtx *ioctx, string& oid, string& name, map<locker_id_t, locker_info_t>& lockers, ClsLockType *assert_type, string *assert_tag) { ClsLockType lock_type = ClsLockType::NONE; string tag; lockers.clear(); ASSERT_EQ(0, get_lock_info(ioctx, oid, name, &lockers, &lock_type, &tag)); cout << "lock: " << name << std::endl; cout << " lock_type: " << cls_lock_type_str(lock_type) << std::endl; cout << " tag: " << tag << std::endl; cout << " lockers:" << std::endl; if (assert_type) { ASSERT_EQ(*assert_type, lock_type); } if (assert_tag) { ASSERT_EQ(*assert_tag, tag); } map<locker_id_t, locker_info_t>::iterator liter; for (liter = lockers.begin(); liter != lockers.end(); ++liter) { const locker_id_t& locker = liter->first; cout << " " << locker.locker << " expiration=" << liter->second.expiration << " addr=" << liter->second.addr << " cookie=" << locker.cookie << std::endl; } } void lock_info(IoCtx *ioctx, string& oid, string& name, map<locker_id_t, locker_info_t>& lockers) { lock_info(ioctx, oid, name, lockers, NULL, NULL); } bool lock_expired(IoCtx *ioctx, string& oid, string& name) { ClsLockType lock_type = ClsLockType::NONE; string tag; map<locker_id_t, locker_info_t> lockers; if (0 == get_lock_info(ioctx, oid, name, &lockers, &lock_type, &tag)) return false; utime_t now = ceph_clock_now(); map<locker_id_t, locker_info_t>::iterator liter; for (liter = lockers.begin(); liter != lockers.end(); ++liter) { if (liter->second.expiration > now) return false; } return true; } TEST(ClsLock, TestMultiLocking) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); ClsLockType lock_type_shared = ClsLockType::SHARED; ClsLockType lock_type_exclusive = ClsLockType::EXCLUSIVE; Rados cluster2; IoCtx ioctx2; ASSERT_EQ("", connect_cluster_pp(cluster2)); cluster2.ioctx_create(pool_name.c_str(), ioctx2); string oid = "foo"; bufferlist bl; string lock_name = "mylock"; ASSERT_EQ(0, ioctx.write(oid, bl, bl.length(), 0)); Lock l(lock_name); // we set the duration, so the log output contains a locker with a // non-zero expiration time l.set_duration(utime_t(120, 0)); /* test lock object */ ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); /* test exclusive lock */ ASSERT_EQ(-EEXIST, l.lock_exclusive(&ioctx, oid)); /* test idempotency */ l.set_may_renew(true); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); l.set_may_renew(false); /* test second client */ Lock l2(lock_name); ASSERT_EQ(-EBUSY, l2.lock_exclusive(&ioctx2, oid)); ASSERT_EQ(-EBUSY, l2.lock_shared(&ioctx2, oid)); list<string> locks; ASSERT_EQ(0, list_locks(&ioctx, oid, &locks)); ASSERT_EQ(1, (int)locks.size()); list<string>::iterator iter = locks.begin(); map<locker_id_t, locker_info_t> lockers; lock_info(&ioctx, oid, *iter, lockers, &lock_type_exclusive, NULL); ASSERT_EQ(1, (int)lockers.size()); /* test unlock */ ASSERT_EQ(0, l.unlock(&ioctx, oid)); locks.clear(); ASSERT_EQ(0, list_locks(&ioctx, oid, &locks)); /* test shared lock */ ASSERT_EQ(0, l2.lock_shared(&ioctx2, oid)); ASSERT_EQ(0, l.lock_shared(&ioctx, oid)); locks.clear(); ASSERT_EQ(0, list_locks(&ioctx, oid, &locks)); ASSERT_EQ(1, (int)locks.size()); iter = locks.begin(); lock_info(&ioctx, oid, *iter, lockers, &lock_type_shared, NULL); ASSERT_EQ(2, (int)lockers.size()); /* test break locks */ entity_name_t name = entity_name_t::CLIENT(cluster.get_instance_id()); entity_name_t name2 = entity_name_t::CLIENT(cluster2.get_instance_id()); l2.break_lock(&ioctx2, oid, name); lock_info(&ioctx, oid, *iter, lockers); ASSERT_EQ(1, (int)lockers.size()); map<locker_id_t, locker_info_t>::iterator liter = lockers.begin(); const locker_id_t& id = liter->first; ASSERT_EQ(name2, id.locker); /* test lock tag */ Lock l_tag(lock_name); l_tag.set_tag("non-default tag"); ASSERT_EQ(-EBUSY, l_tag.lock_shared(&ioctx, oid)); /* test modify description */ string description = "new description"; l.set_description(description); ASSERT_EQ(0, l.lock_shared(&ioctx, oid)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestMeta) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); Rados cluster2; IoCtx ioctx2; ASSERT_EQ("", connect_cluster_pp(cluster2)); cluster2.ioctx_create(pool_name.c_str(), ioctx2); string oid = "foo"; bufferlist bl; string lock_name = "mylock"; ASSERT_EQ(0, ioctx.write(oid, bl, bl.length(), 0)); Lock l(lock_name); ASSERT_EQ(0, l.lock_shared(&ioctx, oid)); /* test lock tag */ Lock l_tag(lock_name); l_tag.set_tag("non-default tag"); ASSERT_EQ(-EBUSY, l_tag.lock_shared(&ioctx2, oid)); ASSERT_EQ(0, l.unlock(&ioctx, oid)); /* test description */ Lock l2(lock_name); string description = "new description"; l2.set_description(description); ASSERT_EQ(0, l2.lock_shared(&ioctx2, oid)); map<locker_id_t, locker_info_t> lockers; lock_info(&ioctx, oid, lock_name, lockers, NULL, NULL); ASSERT_EQ(1, (int)lockers.size()); map<locker_id_t, locker_info_t>::iterator iter = lockers.begin(); locker_info_t locker = iter->second; ASSERT_EQ("new description", locker.description); ASSERT_EQ(0, l2.unlock(&ioctx2, oid)); /* check new tag */ string new_tag = "new_tag"; l.set_tag(new_tag); l.set_may_renew(true); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); lock_info(&ioctx, oid, lock_name, lockers, NULL, &new_tag); ASSERT_EQ(1, (int)lockers.size()); l.set_tag(""); ASSERT_EQ(-EBUSY, l.lock_exclusive(&ioctx, oid)); l.set_tag(new_tag); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestCookie) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); string oid = "foo"; string lock_name = "mylock"; Lock l(lock_name); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); /* new cookie */ string cookie = "new cookie"; l.set_cookie(cookie); ASSERT_EQ(-EBUSY, l.lock_exclusive(&ioctx, oid)); ASSERT_EQ(-ENOENT, l.unlock(&ioctx, oid)); l.set_cookie(""); ASSERT_EQ(0, l.unlock(&ioctx, oid)); map<locker_id_t, locker_info_t> lockers; lock_info(&ioctx, oid, lock_name, lockers); ASSERT_EQ(0, (int)lockers.size()); l.set_cookie(cookie); ASSERT_EQ(0, l.lock_shared(&ioctx, oid)); l.set_cookie(""); ASSERT_EQ(0, l.lock_shared(&ioctx, oid)); lock_info(&ioctx, oid, lock_name, lockers); ASSERT_EQ(2, (int)lockers.size()); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestMultipleLocks) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); string oid = "foo"; Lock l("lock1"); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); Lock l2("lock2"); ASSERT_EQ(0, l2.lock_exclusive(&ioctx, oid)); list<string> locks; ASSERT_EQ(0, list_locks(&ioctx, oid, &locks)); ASSERT_EQ(2, (int)locks.size()); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestLockDuration) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); string oid = "foo"; Lock l("lock"); utime_t dur(5, 0); l.set_duration(dur); utime_t start = ceph_clock_now(); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); int r = l.lock_exclusive(&ioctx, oid); if (r == 0) { // it's possible to get success if we were just really slow... ASSERT_TRUE(ceph_clock_now() > start + dur); } else { ASSERT_EQ(-EEXIST, r); } sleep(dur.sec()); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestAssertLocked) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); string oid = "foo"; Lock l("lock1"); ASSERT_EQ(0, l.lock_exclusive(&ioctx, oid)); librados::ObjectWriteOperation op1; l.assert_locked_exclusive(&op1); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; l.assert_locked_shared(&op2); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op2)); l.set_tag("tag"); librados::ObjectWriteOperation op3; l.assert_locked_exclusive(&op3); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op3)); l.set_tag(""); l.set_cookie("cookie"); librados::ObjectWriteOperation op4; l.assert_locked_exclusive(&op4); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op4)); l.set_cookie(""); ASSERT_EQ(0, l.unlock(&ioctx, oid)); librados::ObjectWriteOperation op5; l.assert_locked_exclusive(&op5); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op5)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestSetCookie) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); string oid = "foo"; string name = "name"; string tag = "tag"; string cookie = "cookie"; string new_cookie = "new cookie"; librados::ObjectWriteOperation op1; set_cookie(&op1, name, ClsLockType::SHARED, cookie, tag, new_cookie); ASSERT_EQ(-ENOENT, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; lock(&op2, name, ClsLockType::SHARED, cookie, tag, "", utime_t{}, 0); ASSERT_EQ(0, ioctx.operate(oid, &op2)); librados::ObjectWriteOperation op3; lock(&op3, name, ClsLockType::SHARED, "cookie 2", tag, "", utime_t{}, 0); ASSERT_EQ(0, ioctx.operate(oid, &op3)); librados::ObjectWriteOperation op4; set_cookie(&op4, name, ClsLockType::SHARED, cookie, tag, cookie); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op4)); librados::ObjectWriteOperation op5; set_cookie(&op5, name, ClsLockType::SHARED, cookie, "wrong tag", new_cookie); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op5)); librados::ObjectWriteOperation op6; set_cookie(&op6, name, ClsLockType::SHARED, "wrong cookie", tag, new_cookie); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op6)); librados::ObjectWriteOperation op7; set_cookie(&op7, name, ClsLockType::EXCLUSIVE, cookie, tag, new_cookie); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op7)); librados::ObjectWriteOperation op8; set_cookie(&op8, name, ClsLockType::SHARED, cookie, tag, "cookie 2"); ASSERT_EQ(-EBUSY, ioctx.operate(oid, &op8)); librados::ObjectWriteOperation op9; set_cookie(&op9, name, ClsLockType::SHARED, cookie, tag, new_cookie); ASSERT_EQ(0, ioctx.operate(oid, &op9)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestRenew) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist bl; string oid1 = "foo1"; string lock_name1 = "mylock1"; ASSERT_EQ(0, ioctx.write(oid1, bl, bl.length(), 0)); Lock l1(lock_name1); utime_t lock_duration1(5, 0); l1.set_duration(lock_duration1); ASSERT_EQ(0, l1.lock_exclusive(&ioctx, oid1)); l1.set_may_renew(true); sleep(2); ASSERT_EQ(0, l1.lock_exclusive(&ioctx, oid1)); sleep(7); ASSERT_EQ(0, l1.lock_exclusive(&ioctx, oid1)) << "when a cls_lock is set to may_renew, a relock after expiration " "should still work"; ASSERT_EQ(0, l1.unlock(&ioctx, oid1)); // *********************************************** string oid2 = "foo2"; string lock_name2 = "mylock2"; ASSERT_EQ(0, ioctx.write(oid2, bl, bl.length(), 0)); Lock l2(lock_name2); utime_t lock_duration2(5, 0); l2.set_duration(lock_duration2); ASSERT_EQ(0, l2.lock_exclusive(&ioctx, oid2)); l2.set_must_renew(true); sleep(2); ASSERT_EQ(0, l2.lock_exclusive(&ioctx, oid2)); sleep(7); ASSERT_EQ(-ENOENT, l2.lock_exclusive(&ioctx, oid2)) << "when a cls_lock is set to must_renew, a relock after expiration " "should fail"; ASSERT_EQ(-ENOENT, l2.unlock(&ioctx, oid2)); // *********************************************** string oid3 = "foo3"; string lock_name3 = "mylock3"; ASSERT_EQ(0, ioctx.write(oid3, bl, bl.length(), 0)); Lock l3(lock_name3); l3.set_duration(utime_t(5, 0)); l3.set_must_renew(true); ASSERT_EQ(-ENOENT, l3.lock_exclusive(&ioctx, oid3)) << "unable to create a lock with must_renew"; ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestExclusiveEphemeralBasic) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist bl; string oid1 = "foo1"; string oid2 = "foo2"; string lock_name1 = "mylock1"; string lock_name2 = "mylock2"; Lock l1(lock_name1); l1.set_duration(utime_t(5, 0)); uint64_t size; time_t mod_time; l1.set_may_renew(true); ASSERT_EQ(0, l1.lock_exclusive_ephemeral(&ioctx, oid1)); ASSERT_EQ(0, ioctx.stat(oid1, &size, &mod_time)); sleep(2); int r1 = l1.unlock(&ioctx, oid1); EXPECT_TRUE(r1 == 0 || ((r1 == -ENOENT) && (lock_expired(&ioctx, oid1, lock_name1)))) << "unlock should return 0 or -ENOENT return: " << r1; ASSERT_EQ(-ENOENT, ioctx.stat(oid1, &size, &mod_time)); // *********************************************** Lock l2(lock_name2); utime_t lock_duration2(5, 0); l2.set_duration(utime_t(5, 0)); ASSERT_EQ(0, l2.lock_exclusive(&ioctx, oid2)); ASSERT_EQ(0, ioctx.stat(oid2, &size, &mod_time)); sleep(2); int r2 = l2.unlock(&ioctx, oid2); EXPECT_TRUE(r2 == 0 || ((r2 == -ENOENT) && (lock_expired(&ioctx, oid2, lock_name2)))) << "unlock should return 0 or -ENOENT return: " << r2; ASSERT_EQ(0, ioctx.stat(oid2, &size, &mod_time)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestExclusiveEphemeralStealEphemeral) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist bl; string oid1 = "foo1"; string lock_name1 = "mylock1"; Lock l1(lock_name1); l1.set_duration(utime_t(3, 0)); ASSERT_EQ(0, l1.lock_exclusive_ephemeral(&ioctx, oid1)); sleep(4); // l1 is expired, l2 can take; l2 is also exclusive_ephemeral Lock l2(lock_name1); l2.set_duration(utime_t(3, 0)); ASSERT_EQ(0, l2.lock_exclusive_ephemeral(&ioctx, oid1)); sleep(1); ASSERT_EQ(0, l2.unlock(&ioctx, oid1)); // l2 cannot unlock its expired lock ASSERT_EQ(-ENOENT, l1.unlock(&ioctx, oid1)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsLock, TestExclusiveEphemeralStealExclusive) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist bl; string oid1 = "foo1"; string lock_name1 = "mylock1"; Lock l1(lock_name1); l1.set_duration(utime_t(3, 0)); ASSERT_EQ(0, l1.lock_exclusive_ephemeral(&ioctx, oid1)); sleep(4); // l1 is expired, l2 can take; l2 is exclusive (but not ephemeral) Lock l2(lock_name1); l2.set_duration(utime_t(3, 0)); ASSERT_EQ(0, l2.lock_exclusive(&ioctx, oid1)); sleep(1); ASSERT_EQ(0, l2.unlock(&ioctx, oid1)); // l2 cannot unlock its expired lock ASSERT_EQ(-ENOENT, l1.unlock(&ioctx, oid1)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); }
16,880
27.611864
97
cc
null
ceph-main/src/test/cls_log/test_cls_log.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "cls/log/cls_log_types.h" #include "cls/log/cls_log_client.h" #include "include/utime.h" #include "common/Clock.h" #include "global/global_context.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include <errno.h> #include <string> #include <vector> using namespace std; /// creates a temporary pool and initializes an IoCtx for each test class cls_log : public ::testing::Test { librados::Rados rados; std::string pool_name; protected: librados::IoCtx ioctx; void SetUp() { pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); } void TearDown() { /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } }; static int read_bl(bufferlist& bl, int *i) { auto iter = bl.cbegin(); try { decode(*i, iter); } catch (buffer::error& err) { std::cout << "failed to decode buffer" << std::endl; return -EIO; } return 0; } void add_log(librados::ObjectWriteOperation *op, utime_t& timestamp, string& section, string&name, int i) { bufferlist bl; encode(i, bl); cls_log_add(*op, timestamp, section, name, bl); } string get_name(int i) { string name_prefix = "data-source"; char buf[16]; snprintf(buf, sizeof(buf), "%d", i); return name_prefix + buf; } void generate_log(librados::IoCtx& ioctx, string& oid, int max, utime_t& start_time, bool modify_time) { string section = "global"; librados::ObjectWriteOperation op; int i; for (i = 0; i < max; i++) { uint32_t secs = start_time.sec(); if (modify_time) secs += i; utime_t ts(secs, start_time.nsec()); string name = get_name(i); add_log(&op, ts, section, name, i); } ASSERT_EQ(0, ioctx.operate(oid, &op)); } utime_t get_time(utime_t& start_time, int i, bool modify_time) { uint32_t secs = start_time.sec(); if (modify_time) secs += i; return utime_t(secs, start_time.nsec()); } void check_entry(cls_log_entry& entry, utime_t& start_time, int i, bool modified_time) { string section = "global"; string name = get_name(i); utime_t ts = get_time(start_time, i, modified_time); ASSERT_EQ(section, entry.section); ASSERT_EQ(name, entry.name); ASSERT_EQ(ts, entry.timestamp); } static int log_list(librados::IoCtx& ioctx, const std::string& oid, utime_t& from, utime_t& to, const string& in_marker, int max_entries, list<cls_log_entry>& entries, string *out_marker, bool *truncated) { librados::ObjectReadOperation rop; cls_log_list(rop, from, to, in_marker, max_entries, entries, out_marker, truncated); bufferlist obl; return ioctx.operate(oid, &rop, &obl); } static int log_list(librados::IoCtx& ioctx, const std::string& oid, utime_t& from, utime_t& to, int max_entries, list<cls_log_entry>& entries, bool *truncated) { std::string marker; return log_list(ioctx, oid, from, to, marker, max_entries, entries, &marker, truncated); } static int log_list(librados::IoCtx& ioctx, const std::string& oid, list<cls_log_entry>& entries) { utime_t from, to; bool truncated{false}; return log_list(ioctx, oid, from, to, 0, entries, &truncated); } TEST_F(cls_log, test_log_add_same_time) { /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* generate log */ utime_t start_time = ceph_clock_now(); utime_t to_time = get_time(start_time, 1, true); generate_log(ioctx, oid, 10, start_time, false); list<cls_log_entry> entries; bool truncated; /* check list */ { ASSERT_EQ(0, log_list(ioctx, oid, start_time, to_time, 0, entries, &truncated)); ASSERT_EQ(10, (int)entries.size()); ASSERT_EQ(0, (int)truncated); } list<cls_log_entry>::iterator iter; /* need to sort returned entries, all were using the same time as key */ map<int, cls_log_entry> check_ents; for (iter = entries.begin(); iter != entries.end(); ++iter) { cls_log_entry& entry = *iter; int num; ASSERT_EQ(0, read_bl(entry.data, &num)); check_ents[num] = entry; } ASSERT_EQ(10, (int)check_ents.size()); map<int, cls_log_entry>::iterator ei; /* verify entries are as expected */ int i; for (i = 0, ei = check_ents.begin(); i < 10; i++, ++ei) { cls_log_entry& entry = ei->second; ASSERT_EQ(i, ei->first); check_entry(entry, start_time, i, false); } /* check list again, now want to be truncated*/ { ASSERT_EQ(0, log_list(ioctx, oid, start_time, to_time, 1, entries, &truncated)); ASSERT_EQ(1, (int)entries.size()); ASSERT_EQ(1, (int)truncated); } } TEST_F(cls_log, test_log_add_different_time) { /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* generate log */ utime_t start_time = ceph_clock_now(); generate_log(ioctx, oid, 10, start_time, true); list<cls_log_entry> entries; bool truncated; utime_t to_time = utime_t(start_time.sec() + 10, start_time.nsec()); { /* check list */ ASSERT_EQ(0, log_list(ioctx, oid, start_time, to_time, 0, entries, &truncated)); ASSERT_EQ(10, (int)entries.size()); ASSERT_EQ(0, (int)truncated); } list<cls_log_entry>::iterator iter; /* returned entries should be sorted by time */ map<int, cls_log_entry> check_ents; int i; for (i = 0, iter = entries.begin(); iter != entries.end(); ++iter, ++i) { cls_log_entry& entry = *iter; int num; ASSERT_EQ(0, read_bl(entry.data, &num)); ASSERT_EQ(i, num); check_entry(entry, start_time, i, true); } /* check list again with shifted time */ { utime_t next_time = get_time(start_time, 1, true); ASSERT_EQ(0, log_list(ioctx, oid, next_time, to_time, 0, entries, &truncated)); ASSERT_EQ(9u, entries.size()); ASSERT_FALSE(truncated); } string marker; i = 0; do { string old_marker = std::move(marker); ASSERT_EQ(0, log_list(ioctx, oid, start_time, to_time, old_marker, 1, entries, &marker, &truncated)); ASSERT_NE(old_marker, marker); ASSERT_EQ(1, (int)entries.size()); ++i; ASSERT_GE(10, i); } while (truncated); ASSERT_EQ(10, i); } int do_log_trim(librados::IoCtx& ioctx, const std::string& oid, const std::string& from_marker, const std::string& to_marker) { librados::ObjectWriteOperation op; cls_log_trim(op, {}, {}, from_marker, to_marker); return ioctx.operate(oid, &op); } int do_log_trim(librados::IoCtx& ioctx, const std::string& oid, const utime_t& from_time, const utime_t& to_time) { librados::ObjectWriteOperation op; cls_log_trim(op, from_time, to_time, "", ""); return ioctx.operate(oid, &op); } TEST_F(cls_log, trim_by_time) { /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* generate log */ utime_t start_time = ceph_clock_now(); generate_log(ioctx, oid, 10, start_time, true); list<cls_log_entry> entries; bool truncated; /* check list */ /* trim */ utime_t to_time = get_time(start_time, 10, true); for (int i = 0; i < 10; i++) { utime_t trim_time = get_time(start_time, i, true); utime_t zero_time; ASSERT_EQ(0, do_log_trim(ioctx, oid, zero_time, trim_time)); ASSERT_EQ(-ENODATA, do_log_trim(ioctx, oid, zero_time, trim_time)); ASSERT_EQ(0, log_list(ioctx, oid, start_time, to_time, 0, entries, &truncated)); ASSERT_EQ(9u - i, entries.size()); ASSERT_FALSE(truncated); } } TEST_F(cls_log, trim_by_marker) { string oid = "obj"; ASSERT_EQ(0, ioctx.create(oid, true)); utime_t start_time = ceph_clock_now(); generate_log(ioctx, oid, 10, start_time, true); utime_t zero_time; std::vector<cls_log_entry> log1; { list<cls_log_entry> entries; ASSERT_EQ(0, log_list(ioctx, oid, entries)); ASSERT_EQ(10u, entries.size()); log1.assign(std::make_move_iterator(entries.begin()), std::make_move_iterator(entries.end())); } // trim front of log { const std::string from = ""; const std::string to = log1[0].id; ASSERT_EQ(0, do_log_trim(ioctx, oid, from, to)); list<cls_log_entry> entries; ASSERT_EQ(0, log_list(ioctx, oid, entries)); ASSERT_EQ(9u, entries.size()); EXPECT_EQ(log1[1].id, entries.begin()->id); ASSERT_EQ(-ENODATA, do_log_trim(ioctx, oid, from, to)); } // trim back of log { const std::string from = log1[8].id; const std::string to = "9"; ASSERT_EQ(0, do_log_trim(ioctx, oid, from, to)); list<cls_log_entry> entries; ASSERT_EQ(0, log_list(ioctx, oid, entries)); ASSERT_EQ(8u, entries.size()); EXPECT_EQ(log1[8].id, entries.rbegin()->id); ASSERT_EQ(-ENODATA, do_log_trim(ioctx, oid, from, to)); } // trim a key from the middle { const std::string from = log1[3].id; const std::string to = log1[4].id; ASSERT_EQ(0, do_log_trim(ioctx, oid, from, to)); list<cls_log_entry> entries; ASSERT_EQ(0, log_list(ioctx, oid, entries)); ASSERT_EQ(7u, entries.size()); ASSERT_EQ(-ENODATA, do_log_trim(ioctx, oid, from, to)); } // trim full log { const std::string from = ""; const std::string to = "9"; ASSERT_EQ(0, do_log_trim(ioctx, oid, from, to)); list<cls_log_entry> entries; ASSERT_EQ(0, log_list(ioctx, oid, entries)); ASSERT_EQ(0u, entries.size()); ASSERT_EQ(-ENODATA, do_log_trim(ioctx, oid, from, to)); } }
9,906
24.665803
105
cc
null
ceph-main/src/test/cls_lua/test_cls_lua.cc
#include <errno.h> #include <lua.hpp> #include "include/types.h" #include "include/rados/librados.hpp" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include "cls/lua/cls_lua_client.h" #include "cls/lua/cls_lua.h" using namespace std; /* * JSON script to test JSON I/O protocol with cls_lua */ const std::string json_test_script = R"jsonscript( { "script": "function json_echo(input, output) output:append(input:str()); end objclass.register(json_echo)", "handler": "json_echo", "input": "omg it works", } )jsonscript"; /* * Lua test script thanks to the magical c++11 string literal syntax */ const std::string test_script = R"luascript( -- -- This Lua script file contains all of the handlers used in the cls_lua unit -- tests (src/test/cls_lua/test_cls_lua.cc). Each section header corresponds -- to the ClsLua.XYZ test. -- -- -- Read -- function read(input, output) size = objclass.stat() bl = objclass.read(0, size) output:append(bl:str()) end objclass.register(read) -- -- Write -- function write(input, output) objclass.write(0, #input, input) end objclass.register(write) -- -- MapGetVal -- function map_get_val_foo(input, output) bl = objclass.map_get_val('foo') output:append(bl:str()) end function map_get_val_dne() bl = objclass.map_get_val('dne') end objclass.register(map_get_val_foo) objclass.register(map_get_val_dne) -- -- Stat -- function stat_ret(input, output) size, mtime = objclass.stat() output:append(size .. "," .. mtime) end function stat_sdne() size, mtime = objclass.stat() end function stat_sdne_pcall() ok, ret, size, mtime = pcall(objclass.stat, o) assert(ok == false) assert(ret == -objclass.ENOENT) return ret end objclass.register(stat_ret) objclass.register(stat_sdne) objclass.register(stat_sdne_pcall) -- -- RetVal -- function rv_h() end function rv_h1() return 1; end function rv_h0() return 0; end function rv_hn1() return -1; end function rv_hs1() return '1'; end function rv_hs0() return '0'; end function rv_hsn1() return '-1'; end function rv_hnil() return nil; end function rv_ht() return {}; end function rv_hstr() return 'asdf'; end objclass.register(rv_h) objclass.register(rv_h1) objclass.register(rv_h0) objclass.register(rv_hn1) objclass.register(rv_hs1) objclass.register(rv_hs0) objclass.register(rv_hsn1) objclass.register(rv_hnil) objclass.register(rv_ht) objclass.register(rv_hstr) -- -- Create -- function create_c() objclass.create(true); end function create_cne() objclass.create(false); end objclass.register(create_c) objclass.register(create_cne) -- -- Pcall -- function pcall_c() objclass.create(true); end function pcall_pc() ok, ret = pcall(objclass.create, true) assert(ok == false) assert(ret == -objclass.EEXIST) end function pcall_pcr() ok, ret = pcall(objclass.create, true) assert(ok == false) assert(ret == -objclass.EEXIST) return ret end function pcall_pcr2() ok, ret = pcall(objclass.create, true) assert(ok == false) assert(ret == -objclass.EEXIST) ok, ret = pcall(objclass.create, true) assert(ok == false) assert(ret == -objclass.EEXIST) return -9999 end objclass.register(pcall_c) objclass.register(pcall_pc) objclass.register(pcall_pcr) objclass.register(pcall_pcr2) -- -- Remove -- function remove_c() objclass.create(true); end function remove_r() objclass.remove(); end objclass.register(remove_c) objclass.register(remove_r) -- -- MapSetVal -- function map_set_val(input, output) objclass.map_set_val('foo', input) end objclass.register(map_set_val) -- -- MapClear -- function map_clear() objclass.map_clear() end objclass.register(map_clear) -- -- BufferlistEquality -- function bl_eq_empty_equal(input, output) bl1 = bufferlist.new() bl2 = bufferlist.new() assert(bl1 == bl2) end function bl_eq_empty_selfequal() bl1 = bufferlist.new() assert(bl1 == bl1) end function bl_eq_selfequal() bl1 = bufferlist.new() bl1:append('asdf') assert(bl1 == bl1) end function bl_eq_equal() bl1 = bufferlist.new() bl2 = bufferlist.new() bl1:append('abc') bl2:append('abc') assert(bl1 == bl2) end function bl_eq_notequal() bl1 = bufferlist.new() bl2 = bufferlist.new() bl1:append('abc') bl2:append('abcd') assert(bl1 ~= bl2) end objclass.register(bl_eq_empty_equal) objclass.register(bl_eq_empty_selfequal) objclass.register(bl_eq_selfequal) objclass.register(bl_eq_equal) objclass.register(bl_eq_notequal) -- -- Bufferlist Compare -- function bl_lt() local a = bufferlist.new() local b = bufferlist.new() a:append('A') b:append('B') assert(a < b) end function bl_le() local a = bufferlist.new() local b = bufferlist.new() a:append('A') b:append('B') assert(a <= b) end objclass.register(bl_lt) objclass.register(bl_le) -- -- Bufferlist concat -- function bl_concat_eq() local a = bufferlist.new() local b = bufferlist.new() local ab = bufferlist.new() a:append('A') b:append('B') ab:append('AB') assert(a .. b == ab) end function bl_concat_ne() local a = bufferlist.new() local b = bufferlist.new() local ab = bufferlist.new() a:append('A') b:append('B') ab:append('AB') assert(b .. a ~= ab) end function bl_concat_immut() local a = bufferlist.new() local b = bufferlist.new() local ab = bufferlist.new() a:append('A') b:append('B') ab:append('AB') x = a .. b assert(x == ab) b:append('C') assert(x == ab) local bc = bufferlist.new() bc:append('BC') assert(b == bc) end objclass.register(bl_concat_eq) objclass.register(bl_concat_ne) objclass.register(bl_concat_immut) -- -- RunError -- function runerr_a() error('error_a') end function runerr_b() runerr_a() end function runerr_c() runerr_b() end -- only runerr_c is called objclass.register(runerr_c) -- -- GetXattr -- function getxattr(input, output) bl = objclass.getxattr("fooz") output:append(bl:str()) end objclass.register(getxattr) -- -- SetXattr -- function setxattr(input, output) objclass.setxattr("fooz2", input) end objclass.register(setxattr) -- -- WriteFull -- function write_full(input, output) objclass.write_full(input) end objclass.register(write_full) -- -- GetXattrs -- function getxattrs(input, output) -- result xattrs = objclass.getxattrs() -- sort for determisitic test arr = {} for n in pairs(xattrs) do table.insert(arr, n) end table.sort(arr) output_str = "" for i,key in ipairs(arr) do output_str = output_str .. key .. "/" .. xattrs[key]:str() .. "/" end output:append(output_str) end objclass.register(getxattrs) -- -- MapGetKeys -- function map_get_keys(input, output) -- result keys = objclass.map_get_keys("", 5) -- sort for determisitic test arr = {} for n in pairs(keys) do table.insert(arr, n) end table.sort(arr) output_str = "" for i,key in ipairs(arr) do output_str = output_str .. key .. "/" end output:append(output_str) end objclass.register(map_get_keys) -- -- MapGetVals -- function map_get_vals(input, output) -- result kvs = objclass.map_get_vals("", "", 10) -- sort for determisitic test arr = {} for n in pairs(kvs) do table.insert(arr, n) end table.sort(arr) output_str = "" for i,key in ipairs(arr) do output_str = output_str .. key .. "/" .. kvs[key]:str() .. "/" end output:append(output_str) end objclass.register(map_get_vals) -- -- MapHeader (write) -- function map_write_header(input, output) objclass.map_write_header(input) end objclass.register(map_write_header) -- -- MapHeader (read) -- function map_read_header(input, output) hdr = objclass.map_read_header() output:append(hdr:str()) end objclass.register(map_read_header) -- -- MapSetVals -- function map_set_vals_empty(input, output) record = {} objclass.map_set_vals(record) end function map_set_vals_one(input, output) record = { a = "a_val" } objclass.map_set_vals(record) end function map_set_vals_two(input, output) record = { a = "a_val", b = "b_val" } objclass.map_set_vals(record) end function map_set_vals_three(input, output) record = { a = "a_val", b = "b_val", c = "c_val" } objclass.map_set_vals(record) end function map_set_vals_array(input, output) array = {} array[1] = "1_val" array[2] = "2_val" objclass.map_set_vals(array) end function map_set_vals_mixed(input, output) record = { a = "a_val", b = "b_val" } record[1] = "1_val" record[2] = "2_val" objclass.map_set_vals(record) end function map_set_vals_bad_val(input, output) record = { a = {} } objclass.map_set_vals(record) end objclass.register(map_set_vals_empty) objclass.register(map_set_vals_one) objclass.register(map_set_vals_two) objclass.register(map_set_vals_three) objclass.register(map_set_vals_array) objclass.register(map_set_vals_mixed) objclass.register(map_set_vals_bad_val) -- -- MapRemoveKey -- function map_remove_key(input, output) objclass.map_remove_key("a") end objclass.register(map_remove_key) -- -- Version/Subop -- function current_version(input, output) ret = objclass.current_version() output:append("" .. ret) objclass.log(0, ret) end function current_subop_num(input, output) ret = objclass.current_subop_num() output:append("" .. ret) objclass.log(0, ret) end function current_subop_version(input, output) ret = objclass.current_subop_version() output:append("" .. ret) objclass.log(0, ret) end objclass.register(current_version) objclass.register(current_subop_num) objclass.register(current_subop_version) )luascript"; /* * Test harness uses single pool for the entire test case, and generates * unique object names for each test. */ class ClsLua : public ::testing::Test { protected: static void SetUpTestCase() { pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); } static void TearDownTestCase() { ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } void SetUp() override { /* Grab test names to build unique objects */ const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); /* Create unique string using test/testname/pid */ std::stringstream ss_oid; ss_oid << test_info->test_case_name() << "_" << test_info->name() << "_" << getpid(); /* Unique object for test to use */ oid = ss_oid.str(); } void TearDown() override { } /* * Helper function. This functionality should eventually make its way into * a clslua client library of some sort. */ int __clslua_exec(const string& oid, const string& script, librados::bufferlist *input = NULL, const string& funcname = "") { bufferlist inbl; if (input) inbl = *input; reply_output.clear(); return cls_lua_client::exec(ioctx, oid, script, funcname, inbl, reply_output); } int clslua_exec(const string& script, librados::bufferlist *input = NULL, const string& funcname = "") { return __clslua_exec(oid, script, input, funcname); } static librados::Rados rados; static librados::IoCtx ioctx; static string pool_name; string oid; bufferlist reply_output; }; librados::Rados ClsLua::rados; librados::IoCtx ClsLua::ioctx; string ClsLua::pool_name; TEST_F(ClsLua, Write) { /* write some data into object */ string written = "Hello World"; bufferlist inbl; encode(written, inbl); ASSERT_EQ(0, clslua_exec(test_script, &inbl, "write")); /* have Lua read out of the object */ uint64_t size; bufferlist outbl; ASSERT_EQ(0, ioctx.stat(oid, &size, NULL)); ASSERT_EQ(size, (uint64_t)ioctx.read(oid, outbl, size, 0) ); /* compare what Lua read to what we wrote */ string read; decode(read, outbl); ASSERT_EQ(read, written); } TEST_F(ClsLua, SyntaxError) { ASSERT_EQ(-EIO, clslua_exec("-")); } TEST_F(ClsLua, EmptyScript) { ASSERT_EQ(0, clslua_exec("")); } TEST_F(ClsLua, RetVal) { /* handlers can return numeric values */ ASSERT_EQ(1, clslua_exec(test_script, NULL, "rv_h1")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "rv_h0")); ASSERT_EQ(-1, clslua_exec(test_script, NULL, "rv_hn1")); ASSERT_EQ(1, clslua_exec(test_script, NULL, "rv_hs1")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "rv_hs0")); ASSERT_EQ(-1, clslua_exec(test_script, NULL, "rv_hsn1")); /* no return value is success */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "rv_h")); /* non-numeric return values are errors */ ASSERT_EQ(-EIO, clslua_exec(test_script, NULL, "rv_hnil")); ASSERT_EQ(-EIO, clslua_exec(test_script, NULL, "rv_ht")); ASSERT_EQ(-EIO, clslua_exec(test_script, NULL, "rv_hstr")); } TEST_F(ClsLua, Create) { /* create works */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "create_c")); /* exclusive works */ ASSERT_EQ(-EEXIST, clslua_exec(test_script, NULL, "create_c")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "create_cne")); } TEST_F(ClsLua, Pcall) { /* create and error works */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "pcall_c")); ASSERT_EQ(-EEXIST, clslua_exec(test_script, NULL, "pcall_c")); /* pcall masks the error */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "pcall_pc")); /* pcall lets us get the failed return value */ ASSERT_EQ(-EEXIST, clslua_exec(test_script, NULL, "pcall_pcr")); /* * the first call in pcr2 will fail (check ret != 0), and the second pcall * should also fail (we check with a bogus return value to mask real * errors). This is also an important check for our error handling because * we need a case where two functions in the same handler fail to exercise * our internal error book keeping. */ ASSERT_EQ(-9999, clslua_exec(test_script, NULL, "pcall_pcr2")); } TEST_F(ClsLua, Remove) { /* object doesn't exist */ ASSERT_EQ(-ENOENT, clslua_exec(test_script, NULL, "remove_r")); /* can remove */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "remove_c")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "remove_r")); ASSERT_EQ(-ENOENT, clslua_exec(test_script, NULL, "remove_r")); } TEST_F(ClsLua, Stat) { /* build object and stat */ char buf[1024] = {}; bufferlist bl; bl.append(buf, sizeof(buf)); ASSERT_EQ(0, ioctx.write_full(oid, bl)); uint64_t size; time_t mtime; ASSERT_EQ(0, ioctx.stat(oid, &size, &mtime)); /* test stat success */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "stat_ret")); // size,mtime from ioctx call std::stringstream s1; s1 << size << "," << mtime; // lua constructed size,mtime string std::string s2(reply_output.c_str(), reply_output.length()); ASSERT_EQ(s1.str(), s2); /* test object dne */ ASSERT_EQ(-ENOENT, __clslua_exec("dne", test_script, NULL, "stat_sdne")); /* can capture error with pcall */ ASSERT_EQ(-ENOENT, __clslua_exec("dne", test_script, NULL, "stat_sdne_pcall")); } TEST_F(ClsLua, MapClear) { /* write some data into a key */ string msg = "This is a test message"; bufferlist val; val.append(msg.c_str(), msg.size()); map<string, bufferlist> map; map["foo"] = val; ASSERT_EQ(0, ioctx.omap_set(oid, map)); /* test we can get it back out */ set<string> keys; keys.insert("foo"); map.clear(); ASSERT_EQ(0, (int)map.count("foo")); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys(oid, keys, &map)); ASSERT_EQ(1, (int)map.count("foo")); /* now clear it */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_clear")); /* test that the map we get back is empty now */ map.clear(); ASSERT_EQ(0, (int)map.count("foo")); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys(oid, keys, &map)); ASSERT_EQ(0, (int)map.count("foo")); } TEST_F(ClsLua, MapSetVal) { /* build some input value */ bufferlist orig_val; encode("this is the original value yay", orig_val); /* have the lua script stuff the data into a map value */ ASSERT_EQ(0, clslua_exec(test_script, &orig_val, "map_set_val")); /* grap the key now and compare to orig */ map<string, bufferlist> out_map; set<string> out_keys; out_keys.insert("foo"); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys(oid, out_keys, &out_map)); bufferlist out_bl = out_map["foo"]; string out_val; decode(out_val, out_bl); ASSERT_EQ(out_val, "this is the original value yay"); } TEST_F(ClsLua, MapGetVal) { /* write some data into a key */ string msg = "This is a test message"; bufferlist orig_val; orig_val.append(msg.c_str(), msg.size()); map<string, bufferlist> orig_map; orig_map["foo"] = orig_val; ASSERT_EQ(0, ioctx.omap_set(oid, orig_map)); /* now compare to what we put it */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_val_foo")); /* check return */ string ret_val; ret_val.assign(reply_output.c_str(), reply_output.length()); ASSERT_EQ(ret_val, msg); /* error case */ ASSERT_EQ(-ENOENT, clslua_exec(test_script, NULL, "map_get_val_dne")); } TEST_F(ClsLua, Read) { /* put data into object */ string msg = "This is a test message"; bufferlist bl; bl.append(msg.c_str(), msg.size()); ASSERT_EQ(0, ioctx.write_full(oid, bl)); /* get lua to read it and send it back */ ASSERT_EQ(0, clslua_exec(test_script, NULL, "read")); /* check return */ string ret_val; ret_val.assign(reply_output.c_str(), reply_output.length()); ASSERT_EQ(ret_val, msg); } TEST_F(ClsLua, Log) { ASSERT_EQ(0, clslua_exec("objclass.log()")); ASSERT_EQ(0, clslua_exec("s = objclass.log(); objclass.log(s);")); ASSERT_EQ(0, clslua_exec("objclass.log(1)")); ASSERT_EQ(0, clslua_exec("objclass.log(-1)")); ASSERT_EQ(0, clslua_exec("objclass.log('x')")); ASSERT_EQ(0, clslua_exec("objclass.log(0, 0)")); ASSERT_EQ(0, clslua_exec("objclass.log(1, 1)")); ASSERT_EQ(0, clslua_exec("objclass.log(-10, -10)")); ASSERT_EQ(0, clslua_exec("objclass.log('x', 'y')")); ASSERT_EQ(0, clslua_exec("objclass.log(1, 'one')")); ASSERT_EQ(0, clslua_exec("objclass.log(1, 'one', 'two')")); ASSERT_EQ(0, clslua_exec("objclass.log('one', 'two', 'three')")); ASSERT_EQ(0, clslua_exec("s = objclass.log('one', 'two', 'three'); objclass.log(s);")); } TEST_F(ClsLua, BufferlistEquality) { ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_eq_empty_equal")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_eq_empty_selfequal")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_eq_selfequal")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_eq_equal")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_eq_notequal")); } TEST_F(ClsLua, RunError) { ASSERT_EQ(-EIO, clslua_exec(test_script, NULL, "runerr_c")); } TEST_F(ClsLua, HandleNotFunc) { string script = "x = 1;"; ASSERT_EQ(-EOPNOTSUPP, clslua_exec(script, NULL, "x")); } TEST_F(ClsLua, Register) { /* normal cases: register and maybe call the handler */ string script = "function h() end; objclass.register(h);"; ASSERT_EQ(0, clslua_exec(script, NULL, "")); ASSERT_EQ(0, clslua_exec(script, NULL, "h")); /* can register and call multiple handlers */ script = "function h1() end; function h2() end;" "objclass.register(h1); objclass.register(h2);"; ASSERT_EQ(0, clslua_exec(script, NULL, "")); ASSERT_EQ(0, clslua_exec(script, NULL, "h1")); ASSERT_EQ(0, clslua_exec(script, NULL, "h2")); /* normal cases: register before function is defined */ script = "objclass.register(h); function h() end;"; ASSERT_EQ(-EIO, clslua_exec(script, NULL, "")); ASSERT_EQ(-EIO, clslua_exec(script, NULL, "h")); /* cannot call handler that isn't registered */ script = "function h() end;"; ASSERT_EQ(-EIO, clslua_exec(script, NULL, "h")); /* handler doesn't exist */ script = "objclass.register(lalala);"; ASSERT_EQ(-EIO, clslua_exec(script, NULL, "")); /* handler isn't a function */ script = "objclass.register('some string');"; ASSERT_EQ(-EIO, clslua_exec(script, NULL, "")); /* cannot register handler multiple times */ script = "function h() end; objclass.register(h); objclass.register(h);"; ASSERT_EQ(-EIO, clslua_exec(script, NULL, "")); } TEST_F(ClsLua, BufferlistCompare) { ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_lt")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_le")); } TEST_F(ClsLua, BufferlistConcat) { ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_concat_eq")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_concat_ne")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "bl_concat_immut")); } TEST_F(ClsLua, GetXattr) { bufferlist bl; bl.append("blahblahblahblahblah"); ASSERT_EQ(0, ioctx.setxattr(oid, "fooz", bl)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "getxattr")); ASSERT_TRUE(reply_output == bl); } TEST_F(ClsLua, SetXattr) { bufferlist inbl; inbl.append("blahblahblahblahblah"); ASSERT_EQ(0, clslua_exec(test_script, &inbl, "setxattr")); bufferlist outbl; ASSERT_EQ((int)inbl.length(), ioctx.getxattr(oid, "fooz2", outbl)); ASSERT_TRUE(outbl == inbl); } TEST_F(ClsLua, WriteFull) { // write some data char buf[1024] = {}; bufferlist blin; blin.append(buf, sizeof(buf)); ASSERT_EQ(0, ioctx.write(oid, blin, blin.length(), 0)); bufferlist blout; ASSERT_EQ((int)blin.length(), ioctx.read(oid, blout, 0, 0)); ASSERT_EQ(blin, blout); // execute write_full from lua blin.clear(); char buf2[200]; sprintf(buf2, "%s", "data replacing content"); blin.append(buf2, sizeof(buf2)); ASSERT_EQ(0, clslua_exec(test_script, &blin, "write_full")); // read it back blout.clear(); ASSERT_EQ((int)blin.length(), ioctx.read(oid, blout, 0, 0)); ASSERT_EQ(blin, blout); } TEST_F(ClsLua, GetXattrs) { ASSERT_EQ(0, ioctx.create(oid, false)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "getxattrs")); ASSERT_EQ(0, (int)reply_output.length()); string key1str("key1str"); bufferlist key1bl; key1bl.append(key1str); ASSERT_EQ(0, ioctx.setxattr(oid, "key1", key1bl)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "getxattrs")); string out1(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out1.c_str(), "key1/key1str/"); string key2str("key2str"); bufferlist key2bl; key2bl.append(key2str); ASSERT_EQ(0, ioctx.setxattr(oid, "key2", key2bl)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "getxattrs")); string out2(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out2.c_str(), "key1/key1str/key2/key2str/"); string key3str("key3str"); bufferlist key3bl; key3bl.append(key3str); ASSERT_EQ(0, ioctx.setxattr(oid, "key3", key3bl)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "getxattrs")); string out3(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out3.c_str(), "key1/key1str/key2/key2str/key3/key3str/"); } TEST_F(ClsLua, MapGetKeys) { ASSERT_EQ(0, ioctx.create(oid, false)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_keys")); ASSERT_EQ(0, (int)reply_output.length()); map<string, bufferlist> kvpairs; kvpairs["k1"] = bufferlist(); ASSERT_EQ(0, ioctx.omap_set(oid, kvpairs)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_keys")); string out1(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out1.c_str(), "k1/"); kvpairs["k2"] = bufferlist(); ASSERT_EQ(0, ioctx.omap_set(oid, kvpairs)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_keys")); string out2(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out2.c_str(), "k1/k2/"); kvpairs["xxx"] = bufferlist(); ASSERT_EQ(0, ioctx.omap_set(oid, kvpairs)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_keys")); string out3(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out3.c_str(), "k1/k2/xxx/"); } TEST_F(ClsLua, MapGetVals) { ASSERT_EQ(0, ioctx.create(oid, false)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_vals")); ASSERT_EQ(0, (int)reply_output.length()); map<string, bufferlist> kvpairs; kvpairs["key1"] = bufferlist(); kvpairs["key1"].append(string("key1str")); ASSERT_EQ(0, ioctx.omap_set(oid, kvpairs)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_vals")); string out1(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out1.c_str(), "key1/key1str/"); kvpairs["key2"] = bufferlist(); kvpairs["key2"].append(string("key2str")); ASSERT_EQ(0, ioctx.omap_set(oid, kvpairs)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_vals")); string out2(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out2.c_str(), "key1/key1str/key2/key2str/"); kvpairs["key3"] = bufferlist(); kvpairs["key3"].append(string("key3str")); ASSERT_EQ(0, ioctx.omap_set(oid, kvpairs)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_get_vals")); string out3(reply_output.c_str(), reply_output.length()); // add the trailing \0 ASSERT_STREQ(out3.c_str(), "key1/key1str/key2/key2str/key3/key3str/"); } TEST_F(ClsLua, MapHeader) { ASSERT_EQ(0, ioctx.create(oid, false)); bufferlist bl_out; ASSERT_EQ(0, ioctx.omap_get_header(oid, &bl_out)); ASSERT_EQ(0, (int)bl_out.length()); std::string val("this is a value"); bufferlist hdr; hdr.append(val); ASSERT_EQ(0, clslua_exec(test_script, &hdr, "map_write_header")); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_read_header")); ASSERT_EQ(reply_output, hdr); } TEST_F(ClsLua, MapSetVals) { ASSERT_EQ(0, ioctx.create(oid, false)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_set_vals_empty")); std::map<string, bufferlist> out_vals; ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_set_vals_one")); ASSERT_EQ(0, ioctx.omap_get_vals(oid, "", 100, &out_vals)); ASSERT_EQ(1, (int)out_vals.size()); ASSERT_STREQ("a_val", std::string(out_vals["a"].c_str(), out_vals["a"].length()).c_str()); out_vals.clear(); ASSERT_EQ(0, ioctx.omap_clear(oid)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_set_vals_two")); ASSERT_EQ(0, ioctx.omap_get_vals(oid, "", 100, &out_vals)); ASSERT_EQ(2, (int)out_vals.size()); ASSERT_STREQ("a_val", std::string(out_vals["a"].c_str(), out_vals["a"].length()).c_str()); ASSERT_STREQ("b_val", std::string(out_vals["b"].c_str(), out_vals["b"].length()).c_str()); out_vals.clear(); ASSERT_EQ(0, ioctx.omap_clear(oid)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_set_vals_three")); ASSERT_EQ(0, ioctx.omap_get_vals(oid, "", 100, &out_vals)); ASSERT_EQ(3, (int)out_vals.size()); ASSERT_STREQ("a_val", std::string(out_vals["a"].c_str(), out_vals["a"].length()).c_str()); ASSERT_STREQ("b_val", std::string(out_vals["b"].c_str(), out_vals["b"].length()).c_str()); ASSERT_STREQ("c_val", std::string(out_vals["c"].c_str(), out_vals["c"].length()).c_str()); out_vals.clear(); ASSERT_EQ(0, ioctx.omap_clear(oid)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_set_vals_array")); ASSERT_EQ(0, ioctx.omap_get_vals(oid, "", 100, &out_vals)); ASSERT_EQ(2, (int)out_vals.size()); ASSERT_STREQ("1_val", std::string(out_vals["1"].c_str(), out_vals["1"].length()).c_str()); ASSERT_STREQ("2_val", std::string(out_vals["2"].c_str(), out_vals["2"].length()).c_str()); out_vals.clear(); ASSERT_EQ(0, ioctx.omap_clear(oid)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_set_vals_mixed")); ASSERT_EQ(0, ioctx.omap_get_vals(oid, "", 100, &out_vals)); ASSERT_EQ(4, (int)out_vals.size()); ASSERT_STREQ("a_val", std::string(out_vals["a"].c_str(), out_vals["a"].length()).c_str()); ASSERT_STREQ("b_val", std::string(out_vals["b"].c_str(), out_vals["b"].length()).c_str()); ASSERT_STREQ("1_val", std::string(out_vals["1"].c_str(), out_vals["1"].length()).c_str()); ASSERT_STREQ("2_val", std::string(out_vals["2"].c_str(), out_vals["2"].length()).c_str()); ASSERT_EQ(-EINVAL, clslua_exec(test_script, NULL, "map_set_vals_bad_val")); } TEST_F(ClsLua, MapRemoveKey) { ASSERT_EQ(0, ioctx.create(oid, false)); std::map<string, bufferlist> out_vals; ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_set_vals_two")); ASSERT_EQ(0, ioctx.omap_get_vals(oid, "", 100, &out_vals)); ASSERT_EQ(2, (int)out_vals.size()); ASSERT_STREQ("a_val", std::string(out_vals["a"].c_str(), out_vals["a"].length()).c_str()); ASSERT_STREQ("b_val", std::string(out_vals["b"].c_str(), out_vals["b"].length()).c_str()); out_vals.clear(); ASSERT_EQ(0, clslua_exec(test_script, NULL, "map_remove_key")); ASSERT_EQ(0, ioctx.omap_get_vals(oid, "", 100, &out_vals)); ASSERT_EQ(1, (int)out_vals.size()); ASSERT_STREQ("b_val", std::string(out_vals["b"].c_str(), out_vals["b"].length()).c_str()); } TEST_F(ClsLua, VersionSubop) { ASSERT_EQ(0, ioctx.create(oid, false)); ASSERT_EQ(0, clslua_exec(test_script, NULL, "current_version")); ASSERT_GT((int)reply_output.length(), 0); ASSERT_EQ(0, clslua_exec(test_script, NULL, "current_subop_num")); ASSERT_GT((int)reply_output.length(), 0); ASSERT_EQ(0, clslua_exec(test_script, NULL, "current_subop_version")); ASSERT_GT((int)reply_output.length(), 0); } TEST_F(ClsLua, Json) { ASSERT_EQ(0, ioctx.create(oid, false)); bufferlist inbl, outbl; inbl.append(json_test_script); int ret = ioctx.exec(oid, "lua", "eval_json", inbl, outbl); ASSERT_EQ(ret, 0); std::string out(outbl.c_str(), outbl.length()); ASSERT_STREQ(out.c_str(), "omg it works"); }
29,635
25.723174
109
cc
null
ceph-main/src/test/cls_numops/test_cls_numops.cc
/* * Ceph - scalable distributed file system * * Copyright (C) 2015 CERN * * Author: Joaquim Rocha <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * */ #include <iostream> #include <errno.h> #include <set> #include <sstream> #include <string> #include "cls/numops/cls_numops_client.h" #include "gtest/gtest.h" #include "include/rados/librados.hpp" #include "test/librados/test_cxx.h" using namespace librados; TEST(ClsNumOps, Add) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); // exec numops add method with an empty bufferlist bufferlist in, out; ASSERT_EQ(-EINVAL, ioctx.exec("myobject", "numops", "add", in, out)); // add a number to a non-existing key std::string key = "my-key"; double value_in = 0.5; std::stringstream stream; stream << value_in; ASSERT_EQ(0, rados::cls::numops::add(&ioctx, "myobject", key, value_in)); // check that the omap entry was set and the value matches std::set<std::string> keys; std::map<std::string, bufferlist> omap; keys.insert(key); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); std::map<std::string, bufferlist>::iterator it = omap.find(key); ASSERT_NE(omap.end(), it); bufferlist bl = (*it).second; std::string value_out(bl.c_str(), bl.length()); EXPECT_EQ(stream.str(), value_out); // add another value to the existing one double new_value_in = 3.001; ASSERT_EQ(0, rados::cls::numops::add(&ioctx, "myobject", key, new_value_in)); // check that the omap entry's value matches omap.clear(); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); stream.str(""); stream << (value_in + new_value_in); EXPECT_EQ(stream.str(), value_out); // set the omap entry with some non-numeric value omap.clear(); std::string non_numeric_value("some-non-numeric-text"); omap[key].append(non_numeric_value); ASSERT_EQ(0, ioctx.omap_set("myobject", omap)); // check that adding a number does not succeed omap.clear(); ASSERT_EQ(-EBADMSG, rados::cls::numops::add(&ioctx, "myobject", key, 2.0)); // check that the omap entry was not changed ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); EXPECT_EQ(non_numeric_value, value_out); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsNumOps, Sub) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); // subtract a number from a non-existing key std::string key = "my-key"; double value_in = 0.5; std::stringstream stream; stream << value_in; ASSERT_EQ(0, rados::cls::numops::sub(&ioctx, "myobject", key, value_in)); // check that the omap entry was set and the value matches std::set<std::string> keys; std::map<std::string, bufferlist> omap; keys.insert(key); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); std::map<std::string, bufferlist>::iterator it = omap.find(key); ASSERT_NE(omap.end(), it); bufferlist bl = (*it).second; std::string value_out(bl.c_str(), bl.length()); EXPECT_EQ("-" + stream.str(), value_out); // subtract another value to the existing one double new_value_in = 3.001; ASSERT_EQ(0, rados::cls::numops::sub(&ioctx, "myobject", key, new_value_in)); // check that the omap entry's value matches omap.clear(); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); stream.str(""); stream << -(value_in + new_value_in); EXPECT_EQ(stream.str(), value_out); // set the omap entry with some non-numeric value omap.clear(); std::string non_numeric_value("some-non-numeric-text"); omap[key].append(non_numeric_value); ASSERT_EQ(0, ioctx.omap_set("myobject", omap)); // check that subtracting a number does not succeed omap.clear(); ASSERT_EQ(-EBADMSG, rados::cls::numops::sub(&ioctx, "myobject", key, 2.0)); // check that the omap entry was not changed ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); EXPECT_EQ(non_numeric_value, value_out); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsNumOps, Mul) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); // exec numops mul method with an empty bufferlist bufferlist in, out; ASSERT_EQ(-EINVAL, ioctx.exec("myobject", "numops", "mul", in, out)); // multiply a number to a non-existing key std::string key = "my-key"; double value_in = 0.5; std::stringstream stream; stream << value_in; ASSERT_EQ(0, rados::cls::numops::mul(&ioctx, "myobject", key, value_in)); // check that the omap entry was set and the value is zero std::set<std::string> keys; std::map<std::string, bufferlist> omap; keys.insert(key); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); std::map<std::string, bufferlist>::iterator it = omap.find(key); ASSERT_NE(omap.end(), it); bufferlist bl = (*it).second; std::string value_out(bl.c_str(), bl.length()); EXPECT_EQ("0", value_out); // set a non-zero value so we can effectively test multiplications omap.clear(); omap[key].append(stream.str()); ASSERT_EQ(0, ioctx.omap_set("myobject", omap)); // multiply another value to the existing one double new_value_in = 3.001; ASSERT_EQ(0, rados::cls::numops::mul(&ioctx, "myobject", key, new_value_in)); // check that the omap entry's value matches omap.clear(); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); stream.str(""); stream << (value_in * new_value_in); EXPECT_EQ(stream.str(), value_out); // set the omap entry with some non-numeric value omap.clear(); std::string non_numeric_value("some-non-numeric-text"); omap[key].append(non_numeric_value); ASSERT_EQ(0, ioctx.omap_set("myobject", omap)); // check that adding a number does not succeed ASSERT_EQ(-EBADMSG, rados::cls::numops::mul(&ioctx, "myobject", key, 2.0)); // check that the omap entry was not changed omap.clear(); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); EXPECT_EQ(non_numeric_value, value_out); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsNumOps, Div) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); // divide a non-existing key by a number std::string key = "my-key"; double value_in = 0.5; std::stringstream stream; stream << value_in; ASSERT_EQ(0, rados::cls::numops::div(&ioctx, "myobject", key, value_in)); // check that the omap entry was set and the value is zero std::set<std::string> keys; std::map<std::string, bufferlist> omap; keys.insert(key); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); std::map<std::string, bufferlist>::iterator it = omap.find(key); ASSERT_NE(omap.end(), it); bufferlist bl = (*it).second; std::string value_out(bl.c_str(), bl.length()); EXPECT_EQ("0", value_out); // check that division by zero is not allowed ASSERT_EQ(-EINVAL, rados::cls::numops::div(&ioctx, "myobject", key, 0)); // set a non-zero value so we can effectively test divisions omap.clear(); omap[key].append(stream.str()); ASSERT_EQ(0, ioctx.omap_set("myobject", omap)); // divide another value to the existing one double new_value_in = 3.001; ASSERT_EQ(0, rados::cls::numops::div(&ioctx, "myobject", key, new_value_in)); // check that the omap entry's value matches omap.clear(); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); stream.str(""); stream << (value_in / new_value_in); EXPECT_EQ(stream.str(), value_out); omap.clear(); // set the omap entry with some non-numeric value std::string non_numeric_value("some-non-numeric-text"); omap[key].append(non_numeric_value); ASSERT_EQ(0, ioctx.omap_set("myobject", omap)); // check that adding a number does not succeed ASSERT_EQ(-EBADMSG, rados::cls::numops::div(&ioctx, "myobject", key, 2.0)); // check that the omap entry was not changed omap.clear(); ASSERT_EQ(0, ioctx.omap_get_vals_by_keys("myobject", keys, &omap)); it = omap.find(key); ASSERT_NE(omap.end(), it); bl = (*it).second; value_out.assign(bl.c_str(), bl.length()); EXPECT_EQ(non_numeric_value, value_out); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); }
9,859
22.759036
79
cc
null
ceph-main/src/test/cls_queue/test_cls_queue.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "cls/queue/cls_queue_types.h" #include "cls/queue/cls_queue_client.h" #include "cls/queue/cls_queue_ops.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include "global/global_context.h" #include <string> #include <vector> #include <algorithm> #include <thread> #include <chrono> #include <atomic> using namespace std; class TestClsQueue : public ::testing::Test { protected: librados::Rados rados; std::string pool_name; librados::IoCtx ioctx; void SetUp() override { pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); } void TearDown() override { ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } void test_enqueue(const std::string& queue_name, int number_of_ops, int number_of_elements, int expected_rc) { librados::ObjectWriteOperation op; // test multiple enqueues for (auto i = 0; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); std::vector<bufferlist> data(number_of_elements); // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); return bl; }); // enqueue vector cls_queue_enqueue(op, 0, data); ASSERT_EQ(expected_rc, ioctx.operate(queue_name, &op)); } } }; TEST_F(TestClsQueue, GetCapacity) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size; const int ret = cls_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(queue_size, size); } TEST_F(TestClsQueue, Enqueue) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // test multiple enqueues // 10 iterations, 100 elelemts each // expect 0 (OK) test_enqueue(queue_name, 10, 100, 0); } TEST_F(TestClsQueue, QueueFull) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // 8 iterations, 5 elelemts each // expect 0 (OK) test_enqueue(queue_name, 8, 5, 0); // 2 iterations, 5 elelemts each // expect -28 (Q FULL) test_enqueue(queue_name, 2, 5, -28); } TEST_F(TestClsQueue, List) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); const auto number_of_ops = 10; const auto number_of_elements = 100; // test multiple enqueues test_enqueue(queue_name, number_of_ops, number_of_elements, 0); const auto max_elements = 42; std::string marker; bool truncated = false; std::string next_marker; auto total_elements = 0; do { std::vector<cls_queue_entry> entries; const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, next_marker); ASSERT_EQ(0, ret); marker = next_marker; total_elements += entries.size(); } while (truncated); ASSERT_EQ(total_elements, number_of_ops*number_of_elements); } TEST_F(TestClsQueue, Dequeue) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // test multiple enqueues test_enqueue(queue_name, 10, 100, 0); // get the end marker for 42 elements const auto remove_elements = 42; const std::string marker; bool truncated; std::string end_marker; std::vector<cls_queue_entry> entries; const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, remove_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); ASSERT_EQ(truncated, true); // remove up to end marker cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } TEST_F(TestClsQueue, DequeueMarker) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // test multiple enqueues test_enqueue(queue_name, 10, 1000, 0); const auto remove_elements = 1024; const std::string marker; bool truncated; std::string end_marker; std::vector<cls_queue_entry> entries; auto ret = cls_queue_list_entries(ioctx, queue_name, marker, remove_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); ASSERT_EQ(truncated, true); cls_queue_marker after_deleted_marker; // remove specific markers for (const auto& entry : entries) { cls_queue_marker marker; marker.from_str(entry.marker.c_str()); ASSERT_EQ(marker.from_str(entry.marker.c_str()), 0); if (marker.offset > 0 && marker.offset % 2 == 0) { after_deleted_marker = marker; cls_queue_remove_entries(op, marker.to_str()); } } ASSERT_EQ(0, ioctx.operate(queue_name, &op)); entries.clear(); ret = cls_queue_list_entries(ioctx, queue_name, marker, remove_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); for (const auto& entry : entries) { cls_queue_marker marker; marker.from_str(entry.marker.c_str()); ASSERT_EQ(marker.from_str(entry.marker.c_str()), 0); ASSERT_GE(marker.gen, after_deleted_marker.gen); ASSERT_GE(marker.offset, after_deleted_marker.offset); } } TEST_F(TestClsQueue, ListEmpty) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); const auto max_elements = 50; const std::string marker; bool truncated; std::string next_marker; std::vector<cls_queue_entry> entries; const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, next_marker); ASSERT_EQ(0, ret); ASSERT_EQ(truncated, false); ASSERT_EQ(entries.size(), 0); } TEST_F(TestClsQueue, DequeueEmpty) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); const auto max_elements = 50; const std::string marker; bool truncated; std::string end_marker; std::vector<cls_queue_entry> entries; const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } TEST_F(TestClsQueue, ListAll) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // test multiple enqueues test_enqueue(queue_name, 10, 100, 0); const auto total_elements = 10*100; std::string marker; bool truncated; std::string next_marker; std::vector<cls_queue_entry> entries; const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, total_elements, entries, &truncated, next_marker); ASSERT_EQ(0, ret); ASSERT_EQ(entries.size(), total_elements); ASSERT_EQ(truncated, false); } TEST_F(TestClsQueue, DeleteAll) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // test multiple enqueues test_enqueue(queue_name, 10, 100, 0); const auto total_elements = 10*100; const std::string marker; bool truncated; std::string end_marker; std::vector<cls_queue_entry> entries; auto ret = cls_queue_list_entries(ioctx, queue_name, marker, total_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // list again to make sure that queue is empty ret = cls_queue_list_entries(ioctx, queue_name, marker, 10, entries, &truncated, end_marker); ASSERT_EQ(0, ret); ASSERT_EQ(truncated, false); ASSERT_EQ(entries.size(), 0); } TEST_F(TestClsQueue, EnqueueDequeue) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); bool done = false; const int number_of_ops = 10; const int number_of_elements = 100; std::thread producer([this, &queue_name, &done] { test_enqueue(queue_name, number_of_ops, number_of_elements, 0); done = true; }); auto consume_count = 0U; std::thread consumer([this, &queue_name, &consume_count, &done] { librados::ObjectWriteOperation op; const auto max_elements = 42; const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; while (!done || truncated) { const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); consume_count += entries.size(); cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); producer.join(); consumer.join(); ASSERT_EQ(consume_count, number_of_ops*number_of_elements); } TEST_F(TestClsQueue, QueueFullDequeue) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 4096; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); bool done = false; const auto number_of_ops = 100; const auto number_of_elements = 50; std::thread producer([this, &queue_name, &done] { librados::ObjectWriteOperation op; // test multiple enqueues for (auto i = 0; i < number_of_ops; ++i) { const std::string element_prefix("op-" +to_string(i) + "-element-"); std::vector<bufferlist> data(number_of_elements); // create vector of buffer lists std::generate(data.begin(), data.end(), [j = 0, &element_prefix] () mutable { bufferlist bl; bl.append(element_prefix + to_string(j++)); return bl; }); // enqueue vector cls_queue_enqueue(op, 0, data); if (ioctx.operate(queue_name, &op) == -28) { // queue is full - wait and retry --i; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } done = true; }); auto consume_count = 0; std::thread consumer([this, &queue_name, &consume_count, &done] { librados::ObjectWriteOperation op; const auto max_elements = 42; std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; while (!done || truncated) { auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); consume_count += entries.size(); cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); producer.join(); consumer.join(); ASSERT_EQ(consume_count, number_of_ops*number_of_elements); } TEST_F(TestClsQueue, MultiProducer) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); const int max_producer_count = 10; int producer_count = max_producer_count; const int number_of_ops = 10; const int number_of_elements = 100; std::vector<std::thread> producers(max_producer_count); for (auto& p : producers) { p = std::thread([this, &queue_name, &producer_count] { test_enqueue(queue_name, number_of_ops, number_of_elements, 0); --producer_count; }); } auto consume_count = 0U; std::thread consumer([this, &queue_name, &consume_count, &producer_count] { librados::ObjectWriteOperation op; const auto max_elements = 42; const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; while (producer_count > 0 || truncated) { const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); consume_count += entries.size(); cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); for (auto& p : producers) { p.join(); } consumer.join(); ASSERT_EQ(consume_count, number_of_ops*number_of_elements*max_producer_count); } TEST_F(TestClsQueue, MultiConsumer) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); bool done = false; const int number_of_ops = 10; const int number_of_elements = 100; std::thread producer([this, &queue_name, &done] { test_enqueue(queue_name, number_of_ops, number_of_elements, 0); done = true; }); int consume_count = 0; std::mutex list_and_remove_lock; std::vector<std::thread> consumers(10); for (auto& c : consumers) { c = std::thread([this, &queue_name, &consume_count, &done, &list_and_remove_lock] { librados::ObjectWriteOperation op; const auto max_elements = 42; const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; while (!done || truncated) { std::lock_guard lock(list_and_remove_lock); const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); consume_count += entries.size(); cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); } producer.join(); for (auto& c : consumers) { c.join(); } ASSERT_EQ(consume_count, number_of_ops*number_of_elements); } TEST_F(TestClsQueue, NoLockMultiConsumer) { const std::string queue_name = "my-queue"; const uint64_t queue_size = 1024*1024; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); bool done = false; const int number_of_ops = 10; const int number_of_elements = 100; std::thread producer([this, &queue_name, &done] { test_enqueue(queue_name, number_of_ops, number_of_elements, 0); done = true; }); std::vector<std::thread> consumers(5); for (auto& c : consumers) { c = std::thread([this, &queue_name, &done] { librados::ObjectWriteOperation op; const auto max_elements = 42; const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; while (!done || truncated) { const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } }); } producer.join(); for (auto& c : consumers) { c.join(); } // make sure queue is empty const auto max_elements = 1000; const std::string marker; bool truncated = false; std::string end_marker; std::vector<cls_queue_entry> entries; const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); ASSERT_EQ(entries.size(), 0); ASSERT_EQ(truncated, false); } TEST_F(TestClsQueue, WrapAround) { const std::string queue_name = "my-queue"; const auto number_of_entries = 10U; const auto max_entry_size = 2000; const auto min_entry_size = 1000; const uint64_t queue_size = number_of_entries*max_entry_size; const auto entry_overhead = 10; librados::ObjectWriteOperation op; op.create(true); cls_queue_init(op, queue_name, queue_size); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); std::list<bufferlist> total_bl; // fill up the queue for (auto i = 0U; i < number_of_entries; ++i) { const auto entry_size = rand()%(max_entry_size - min_entry_size + 1) + min_entry_size; std::string entry_str(entry_size-entry_overhead, 0); std::generate_n(entry_str.begin(), entry_str.size(), [](){return (char)(rand());}); bufferlist entry_bl; entry_bl.append(entry_str); std::vector<bufferlist> data{{entry_bl}}; // enqueue vector cls_queue_enqueue(op, 0, data); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); total_bl.push_back(entry_bl); } std::string marker; for (auto j = 0; j < 10; ++j) { // empty half+1 of the queue const auto max_elements = number_of_entries/2 + 1; bool truncated; std::string end_marker; std::vector<cls_queue_entry> entries; const auto ret = cls_queue_list_entries(ioctx, queue_name, marker, max_elements, entries, &truncated, end_marker); ASSERT_EQ(0, ret); for (auto& entry : entries) { ASSERT_EQ(entry.data, total_bl.front()); total_bl.pop_front(); } marker = end_marker; cls_queue_remove_entries(op, end_marker); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); // fill half+1 of the queue for (auto i = 0U; i < number_of_entries/2 + 1; ++i) { const auto entry_size = rand()%(max_entry_size - min_entry_size + 1) + min_entry_size; std::string entry_str(entry_size-entry_overhead, 0); std::generate_n(entry_str.begin(), entry_str.size(), [](){return (char)(rand());}); bufferlist entry_bl; entry_bl.append(entry_str); std::vector<bufferlist> data{{entry_bl}}; cls_queue_enqueue(op, 0, data); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); total_bl.push_back(entry_bl); } } }
19,661
31.338816
126
cc
null
ceph-main/src/test/cls_rbd/test_cls_rbd.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/compat.h" #include "common/ceph_context.h" #include "common/config.h" #include "common/snap_types.h" #include "common/Clock.h" #include "common/bit_vector.hpp" #include "include/encoding.h" #include "include/types.h" #include "include/rados/librados.h" #include "include/rbd/object_map_types.h" #include "include/rbd_types.h" #include "include/stringify.h" #include "cls/rbd/cls_rbd.h" #include "cls/rbd/cls_rbd_client.h" #include "cls/rbd/cls_rbd_types.h" #include "librbd/Types.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include <errno.h> #include <string> #include <vector> using namespace std; using namespace librbd::cls_client; using cls::rbd::MIRROR_PEER_DIRECTION_RX; using cls::rbd::MIRROR_PEER_DIRECTION_TX; using cls::rbd::MIRROR_PEER_DIRECTION_RX_TX; using ::librbd::ParentImageInfo; using ceph::encode; using ceph::decode; static int snapshot_add(librados::IoCtx *ioctx, const std::string &oid, uint64_t snap_id, const std::string &snap_name) { librados::ObjectWriteOperation op; ::librbd::cls_client::snapshot_add(&op, snap_id, snap_name, cls::rbd::UserSnapshotNamespace()); return ioctx->operate(oid, &op); } static int snapshot_remove(librados::IoCtx *ioctx, const std::string &oid, uint64_t snap_id) { librados::ObjectWriteOperation op; ::librbd::cls_client::snapshot_remove(&op, snap_id); return ioctx->operate(oid, &op); } static int snapshot_rename(librados::IoCtx *ioctx, const std::string &oid, uint64_t snap_id, const std::string &snap_name) { librados::ObjectWriteOperation op; ::librbd::cls_client::snapshot_rename(&op, snap_id, snap_name); return ioctx->operate(oid, &op); } static int old_snapshot_add(librados::IoCtx *ioctx, const std::string &oid, uint64_t snap_id, const std::string &snap_name) { librados::ObjectWriteOperation op; ::librbd::cls_client::old_snapshot_add(&op, snap_id, snap_name); return ioctx->operate(oid, &op); } static char *random_buf(size_t len) { char *b = new char[len]; for (size_t i = 0; i < len; i++) b[i] = (rand() % (128 - 32)) + 32; return b; } static bool is_sparse_read_supported(librados::IoCtx &ioctx, const std::string &oid) { EXPECT_EQ(0, ioctx.create(oid, true)); bufferlist inbl; inbl.append(std::string(1, 'X')); EXPECT_EQ(0, ioctx.write(oid, inbl, inbl.length(), 1)); EXPECT_EQ(0, ioctx.write(oid, inbl, inbl.length(), 3)); std::map<uint64_t, uint64_t> m; bufferlist outbl; int r = ioctx.sparse_read(oid, m, outbl, 4, 0); ioctx.remove(oid); int expected_r = 2; std::map<uint64_t, uint64_t> expected_m = {{1, 1}, {3, 1}}; bufferlist expected_outbl; expected_outbl.append(std::string(2, 'X')); return (r == expected_r && m == expected_m && outbl.contents_equal(expected_outbl)); } class TestClsRbd : public ::testing::Test { public: static void SetUpTestCase() { _pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(_pool_name, _rados)); } static void TearDownTestCase() { ASSERT_EQ(0, destroy_one_pool_pp(_pool_name, _rados)); } std::string get_temp_image_name() { ++_image_number; return "image" + stringify(_image_number); } static std::string _pool_name; static librados::Rados _rados; static uint64_t _image_number; }; std::string TestClsRbd::_pool_name; librados::Rados TestClsRbd::_rados; uint64_t TestClsRbd::_image_number = 0; TEST_F(TestClsRbd, get_all_features) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, ioctx.create(oid, false)); uint64_t all_features = 0; ASSERT_EQ(0, get_all_features(&ioctx, oid, &all_features)); ASSERT_EQ(static_cast<uint64_t>(RBD_FEATURES_ALL), static_cast<uint64_t>(all_features & RBD_FEATURES_ALL)); ioctx.close(); } TEST_F(TestClsRbd, copyup) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); bufferlist inbl, outbl; // copyup of 0-len nonexistent object should create new 0-len object ioctx.remove(oid); ASSERT_EQ(0, copyup(&ioctx, oid, inbl)); uint64_t size; ASSERT_EQ(0, ioctx.stat(oid, &size, NULL)); ASSERT_EQ(0U, size); // create some random data to write size_t l = 4 << 20; char *b = random_buf(l); inbl.append(b, l); delete [] b; ASSERT_EQ(l, inbl.length()); // copyup to nonexistent object should create new object ioctx.remove(oid); ASSERT_EQ(-ENOENT, ioctx.remove(oid)); ASSERT_EQ(0, copyup(&ioctx, oid, inbl)); // and its contents should match ASSERT_EQ(l, (size_t)ioctx.read(oid, outbl, l, 0)); ASSERT_TRUE(outbl.contents_equal(inbl)); // now send different data, but with a preexisting object bufferlist inbl2; b = random_buf(l); inbl2.append(b, l); delete [] b; ASSERT_EQ(l, inbl2.length()); // should still succeed ASSERT_EQ(0, copyup(&ioctx, oid, inbl)); ASSERT_EQ(l, (size_t)ioctx.read(oid, outbl, l, 0)); // but contents should not have changed ASSERT_FALSE(outbl.contents_equal(inbl2)); ASSERT_TRUE(outbl.contents_equal(inbl)); ASSERT_EQ(0, ioctx.remove(oid)); ioctx.close(); } TEST_F(TestClsRbd, sparse_copyup) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ioctx.remove(oid); bool sparse_read_supported = is_sparse_read_supported(ioctx, oid); // copyup of 0-len nonexistent object should create new 0-len object uint64_t size; ASSERT_EQ(-ENOENT, ioctx.stat(oid, &size, nullptr)); std::map<uint64_t, uint64_t> m; bufferlist inbl; ASSERT_EQ(0, sparse_copyup(&ioctx, oid, m, inbl)); ASSERT_EQ(0, ioctx.stat(oid, &size, nullptr)); ASSERT_EQ(0U, size); // create some data to write inbl.append(std::string(4096, '1')); inbl.append(std::string(4096, '2')); m = {{1024, 4096}, {8192, 4096}}; // copyup to nonexistent object should create new object ioctx.remove(oid); ASSERT_EQ(-ENOENT, ioctx.remove(oid)); ASSERT_EQ(0, sparse_copyup(&ioctx, oid, m, inbl)); // and its contents should match bufferlist outbl; bufferlist expected_outbl; expected_outbl.append(std::string(1024, '\0')); expected_outbl.append(std::string(4096, '1')); expected_outbl.append(std::string(8192 - 4096 - 1024, '\0')); expected_outbl.append(std::string(4096, '2')); ASSERT_EQ((int)expected_outbl.length(), ioctx.read(oid, outbl, expected_outbl.length() + 1, 0)); ASSERT_TRUE(outbl.contents_equal(expected_outbl)); std::map<uint64_t, uint64_t> expected_m; if (sparse_read_supported) { expected_m = m; expected_outbl = inbl; } else { expected_m = {{0, expected_outbl.length()}}; } m.clear(); outbl.clear(); ASSERT_EQ((int)expected_m.size(), ioctx.sparse_read(oid, m, outbl, 65536, 0)); ASSERT_EQ(m, expected_m); ASSERT_TRUE(outbl.contents_equal(expected_outbl)); // now send different data, but with a preexisting object bufferlist inbl2; inbl2.append(std::string(1024, 'X')); // should still succeed ASSERT_EQ(0, sparse_copyup(&ioctx, oid, {{0, 1024}}, inbl2)); // but contents should not have changed m.clear(); outbl.clear(); ASSERT_EQ((int)expected_m.size(), ioctx.sparse_read(oid, m, outbl, 65536, 0)); ASSERT_EQ(m, expected_m); ASSERT_TRUE(outbl.contents_equal(expected_outbl)); ASSERT_EQ(0, ioctx.remove(oid)); ioctx.close(); } TEST_F(TestClsRbd, get_and_set_id) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); string id; string valid_id = "0123abcxyzZYXCBA"; string invalid_id = ".abc"; string empty_id; ASSERT_EQ(-ENOENT, get_id(&ioctx, oid, &id)); ASSERT_EQ(-ENOENT, set_id(&ioctx, oid, valid_id)); ASSERT_EQ(0, ioctx.create(oid, true)); ASSERT_EQ(-EINVAL, set_id(&ioctx, oid, invalid_id)); ASSERT_EQ(-EINVAL, set_id(&ioctx, oid, empty_id)); ASSERT_EQ(-ENOENT, get_id(&ioctx, oid, &id)); ASSERT_EQ(0, set_id(&ioctx, oid, valid_id)); ASSERT_EQ(-EEXIST, set_id(&ioctx, oid, valid_id)); ASSERT_EQ(-EEXIST, set_id(&ioctx, oid, valid_id + valid_id)); ASSERT_EQ(0, get_id(&ioctx, oid, &id)); ASSERT_EQ(id, valid_id); ioctx.close(); } TEST_F(TestClsRbd, add_remove_child) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, ioctx.create(oid, true)); string snapname = "parent_snap"; snapid_t snapid(10); string parent_image = "parent_id"; set<string>children; cls::rbd::ParentImageSpec pspec(ioctx.get_id(), "", parent_image, snapid); // nonexistent children cannot be listed or removed ASSERT_EQ(-ENOENT, get_children(&ioctx, oid, pspec, children)); ASSERT_EQ(-ENOENT, remove_child(&ioctx, oid, pspec, "child1")); // create the parent and snapshot ASSERT_EQ(0, create_image(&ioctx, parent_image, 2<<20, 0, RBD_FEATURE_LAYERING, parent_image, -1)); ASSERT_EQ(0, snapshot_add(&ioctx, parent_image, snapid, snapname)); // add child to it, verify it showed up ASSERT_EQ(0, add_child(&ioctx, oid, pspec, "child1")); ASSERT_EQ(0, get_children(&ioctx, oid, pspec, children)); ASSERT_TRUE(children.find("child1") != children.end()); // add another child to it, verify it showed up ASSERT_EQ(0, add_child(&ioctx, oid, pspec, "child2")); ASSERT_EQ(0, get_children(&ioctx, oid, pspec, children)); ASSERT_TRUE(children.find("child2") != children.end()); // add child2 again, expect -EEXIST ASSERT_EQ(-EEXIST, add_child(&ioctx, oid, pspec, "child2")); // remove first, verify it's gone ASSERT_EQ(0, remove_child(&ioctx, oid, pspec, "child1")); ASSERT_EQ(0, get_children(&ioctx, oid, pspec, children)); ASSERT_FALSE(children.find("child1") != children.end()); // remove second, verify list empty ASSERT_EQ(0, remove_child(&ioctx, oid, pspec, "child2")); ASSERT_EQ(-ENOENT, get_children(&ioctx, oid, pspec, children)); // try to remove again, validate -ENOENT to that as well ASSERT_EQ(-ENOENT, remove_child(&ioctx, oid, pspec, "child2")); ioctx.close(); } TEST_F(TestClsRbd, directory_methods) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); string id, name; string imgname = get_temp_image_name(); string imgname2 = get_temp_image_name(); string imgname3 = get_temp_image_name(); string valid_id = "0123abcxyzZYXCBA"; string valid_id2 = "5"; string invalid_id = ".abc"; string empty; ASSERT_EQ(-ENOENT, dir_state_assert(&ioctx, oid, cls::rbd::DIRECTORY_STATE_READY)); ASSERT_EQ(-ENOENT, dir_state_set(&ioctx, oid, cls::rbd::DIRECTORY_STATE_ADD_DISABLED)); ASSERT_EQ(-ENOENT, dir_get_id(&ioctx, oid, imgname, &id)); ASSERT_EQ(-ENOENT, dir_get_name(&ioctx, oid, valid_id, &name)); ASSERT_EQ(-ENOENT, dir_remove_image(&ioctx, oid, imgname, valid_id)); ASSERT_EQ(-EINVAL, dir_add_image(&ioctx, oid, imgname, invalid_id)); ASSERT_EQ(-EINVAL, dir_add_image(&ioctx, oid, imgname, empty)); ASSERT_EQ(-EINVAL, dir_add_image(&ioctx, oid, empty, valid_id)); map<string, string> images; ASSERT_EQ(-ENOENT, dir_list(&ioctx, oid, "", 30, &images)); ASSERT_EQ(0, ioctx.create(oid, true)); ASSERT_EQ(0, dir_list(&ioctx, oid, "", 30, &images)); ASSERT_EQ(0u, images.size()); ASSERT_EQ(0, ioctx.remove(oid)); ASSERT_EQ(0, dir_state_set(&ioctx, oid, cls::rbd::DIRECTORY_STATE_READY)); ASSERT_EQ(0, dir_state_assert(&ioctx, oid, cls::rbd::DIRECTORY_STATE_READY)); ASSERT_EQ(0, dir_add_image(&ioctx, oid, imgname, valid_id)); ASSERT_EQ(-EBUSY, dir_state_set(&ioctx, oid, cls::rbd::DIRECTORY_STATE_ADD_DISABLED)); ASSERT_EQ(-EEXIST, dir_add_image(&ioctx, oid, imgname, valid_id2)); ASSERT_EQ(-EBADF, dir_add_image(&ioctx, oid, imgname2, valid_id)); ASSERT_EQ(0, dir_list(&ioctx, oid, "", 30, &images)); ASSERT_EQ(1u, images.size()); ASSERT_EQ(valid_id, images[imgname]); ASSERT_EQ(0, dir_list(&ioctx, oid, "", 0, &images)); ASSERT_EQ(0u, images.size()); ASSERT_EQ(0, dir_get_name(&ioctx, oid, valid_id, &name)); ASSERT_EQ(imgname, name); ASSERT_EQ(0, dir_get_id(&ioctx, oid, imgname, &id)); ASSERT_EQ(valid_id, id); ASSERT_EQ(0, dir_add_image(&ioctx, oid, imgname2, valid_id2)); ASSERT_EQ(0, dir_list(&ioctx, oid, "", 30, &images)); ASSERT_EQ(2u, images.size()); ASSERT_EQ(valid_id, images[imgname]); ASSERT_EQ(valid_id2, images[imgname2]); ASSERT_EQ(0, dir_list(&ioctx, oid, imgname, 0, &images)); ASSERT_EQ(0u, images.size()); ASSERT_EQ(0, dir_list(&ioctx, oid, imgname, 2, &images)); ASSERT_EQ(1u, images.size()); ASSERT_EQ(valid_id2, images[imgname2]); ASSERT_EQ(0, dir_get_name(&ioctx, oid, valid_id2, &name)); ASSERT_EQ(imgname2, name); ASSERT_EQ(0, dir_get_id(&ioctx, oid, imgname2, &id)); ASSERT_EQ(valid_id2, id); librados::ObjectWriteOperation op1; dir_rename_image(&op1, imgname, imgname2, valid_id2); ASSERT_EQ(-ESTALE, ioctx.operate(oid, &op1)); ASSERT_EQ(-ESTALE, dir_remove_image(&ioctx, oid, imgname, valid_id2)); librados::ObjectWriteOperation op2; dir_rename_image(&op2, imgname, imgname2, valid_id); ASSERT_EQ(-EEXIST, ioctx.operate(oid, &op2)); ASSERT_EQ(0, dir_get_id(&ioctx, oid, imgname, &id)); ASSERT_EQ(valid_id, id); ASSERT_EQ(0, dir_get_name(&ioctx, oid, valid_id2, &name)); ASSERT_EQ(imgname2, name); librados::ObjectWriteOperation op3; dir_rename_image(&op3, imgname, imgname3, valid_id); ASSERT_EQ(0, ioctx.operate(oid, &op3)); ASSERT_EQ(0, dir_get_id(&ioctx, oid, imgname3, &id)); ASSERT_EQ(valid_id, id); ASSERT_EQ(0, dir_get_name(&ioctx, oid, valid_id, &name)); ASSERT_EQ(imgname3, name); librados::ObjectWriteOperation op4; dir_rename_image(&op4, imgname3, imgname, valid_id); ASSERT_EQ(0, ioctx.operate(oid, &op4)); ASSERT_EQ(0, dir_remove_image(&ioctx, oid, imgname, valid_id)); ASSERT_EQ(0, dir_list(&ioctx, oid, "", 30, &images)); ASSERT_EQ(1u, images.size()); ASSERT_EQ(valid_id2, images[imgname2]); ASSERT_EQ(0, dir_list(&ioctx, oid, imgname2, 30, &images)); ASSERT_EQ(0u, images.size()); ASSERT_EQ(0, dir_get_name(&ioctx, oid, valid_id2, &name)); ASSERT_EQ(imgname2, name); ASSERT_EQ(0, dir_get_id(&ioctx, oid, imgname2, &id)); ASSERT_EQ(valid_id2, id); ASSERT_EQ(-ENOENT, dir_get_name(&ioctx, oid, valid_id, &name)); ASSERT_EQ(-ENOENT, dir_get_id(&ioctx, oid, imgname, &id)); ASSERT_EQ(0, dir_add_image(&ioctx, oid, imgname, valid_id)); ASSERT_EQ(0, dir_list(&ioctx, oid, "", 30, &images)); ASSERT_EQ(2u, images.size()); ASSERT_EQ(valid_id, images[imgname]); ASSERT_EQ(valid_id2, images[imgname2]); ASSERT_EQ(0, dir_remove_image(&ioctx, oid, imgname, valid_id)); ASSERT_EQ(-ENOENT, dir_remove_image(&ioctx, oid, imgname, valid_id)); ASSERT_EQ(0, dir_remove_image(&ioctx, oid, imgname2, valid_id2)); ASSERT_EQ(0, dir_list(&ioctx, oid, "", 30, &images)); ASSERT_EQ(0u, images.size()); ioctx.close(); } TEST_F(TestClsRbd, create) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); uint64_t size = 20ULL << 30; uint64_t features = 0; uint8_t order = 22; string object_prefix = oid; ASSERT_EQ(0, create_image(&ioctx, oid, size, order, features, object_prefix, -1)); ASSERT_EQ(-EEXIST, create_image(&ioctx, oid, size, order, features, object_prefix, -1)); ASSERT_EQ(0, ioctx.remove(oid)); ASSERT_EQ(-EINVAL, create_image(&ioctx, oid, size, order, features, "", -1)); ASSERT_EQ(-ENOENT, ioctx.remove(oid)); ASSERT_EQ(0, create_image(&ioctx, oid, 0, order, features, object_prefix, -1)); ASSERT_EQ(0, ioctx.remove(oid)); ASSERT_EQ(-ENOSYS, create_image(&ioctx, oid, size, order, -1, object_prefix, -1)); ASSERT_EQ(-ENOENT, ioctx.remove(oid)); ASSERT_EQ(0, create_image(&ioctx, oid, size, order, RBD_FEATURE_DATA_POOL, object_prefix, 123)); ASSERT_EQ(0, ioctx.remove(oid)); ASSERT_EQ(-EINVAL, create_image(&ioctx, oid, size, order, RBD_FEATURE_OPERATIONS, object_prefix, -1)); ASSERT_EQ(-EINVAL, create_image(&ioctx, oid, size, order, RBD_FEATURE_DATA_POOL, object_prefix, -1)); ASSERT_EQ(-EINVAL, create_image(&ioctx, oid, size, order, 0, object_prefix, 123)); bufferlist inbl, outbl; ASSERT_EQ(-EINVAL, ioctx.exec(oid, "rbd", "create", inbl, outbl)); ioctx.close(); } TEST_F(TestClsRbd, get_features) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); uint64_t features; uint64_t incompatible_features; ASSERT_EQ(-ENOENT, get_features(&ioctx, oid, false, &features, &incompatible_features)); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); ASSERT_EQ(0, get_features(&ioctx, oid, false, &features, &incompatible_features)); ASSERT_EQ(0u, features); ioctx.close(); } TEST_F(TestClsRbd, get_object_prefix) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); string object_prefix; ASSERT_EQ(-ENOENT, get_object_prefix(&ioctx, oid, &object_prefix)); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); ASSERT_EQ(0, get_object_prefix(&ioctx, oid, &object_prefix)); ASSERT_EQ(oid, object_prefix); ioctx.close(); } TEST_F(TestClsRbd, get_create_timestamp) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); utime_t timestamp; ASSERT_EQ(0, get_create_timestamp(&ioctx, oid, &timestamp)); ASSERT_LT(0U, timestamp.tv.tv_sec); ioctx.close(); } TEST_F(TestClsRbd, get_access_timestamp) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); utime_t timestamp; ASSERT_EQ(0, get_access_timestamp(&ioctx, oid, &timestamp)); ASSERT_LT(0U, timestamp.tv.tv_sec); ioctx.close(); } TEST_F(TestClsRbd, get_modify_timestamp) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); utime_t timestamp; ASSERT_EQ(0, get_modify_timestamp(&ioctx, oid, &timestamp)); ASSERT_LT(0U, timestamp.tv.tv_sec); ioctx.close(); } TEST_F(TestClsRbd, get_data_pool) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); int64_t data_pool_id; ASSERT_EQ(0, ioctx.create(oid, true)); ASSERT_EQ(0, get_data_pool(&ioctx, oid, &data_pool_id)); ASSERT_EQ(-1, data_pool_id); ASSERT_EQ(0, ioctx.remove(oid)); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, RBD_FEATURE_DATA_POOL, oid, 12)); ASSERT_EQ(0, get_data_pool(&ioctx, oid, &data_pool_id)); ASSERT_EQ(12, data_pool_id); } TEST_F(TestClsRbd, get_size) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); uint64_t size; uint8_t order; ASSERT_EQ(-ENOENT, get_size(&ioctx, oid, CEPH_NOSNAP, &size, &order)); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); ASSERT_EQ(0, get_size(&ioctx, oid, CEPH_NOSNAP, &size, &order)); ASSERT_EQ(0u, size); ASSERT_EQ(22, order); ASSERT_EQ(0, ioctx.remove(oid)); ASSERT_EQ(0, create_image(&ioctx, oid, 2 << 22, 0, 0, oid, -1)); ASSERT_EQ(0, get_size(&ioctx, oid, CEPH_NOSNAP, &size, &order)); ASSERT_EQ(2u << 22, size); ASSERT_EQ(0, order); ASSERT_EQ(-ENOENT, get_size(&ioctx, oid, 1, &size, &order)); ioctx.close(); } TEST_F(TestClsRbd, set_size) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(-ENOENT, set_size(&ioctx, oid, 5)); uint64_t size; uint8_t order; ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); ASSERT_EQ(0, get_size(&ioctx, oid, CEPH_NOSNAP, &size, &order)); ASSERT_EQ(0u, size); ASSERT_EQ(22, order); ASSERT_EQ(0, set_size(&ioctx, oid, 0)); ASSERT_EQ(0, get_size(&ioctx, oid, CEPH_NOSNAP, &size, &order)); ASSERT_EQ(0u, size); ASSERT_EQ(22, order); ASSERT_EQ(0, set_size(&ioctx, oid, 3 << 22)); ASSERT_EQ(0, get_size(&ioctx, oid, CEPH_NOSNAP, &size, &order)); ASSERT_EQ(3u << 22, size); ASSERT_EQ(22, order); ioctx.close(); } TEST_F(TestClsRbd, protection_status) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); string oid2 = get_temp_image_name(); uint8_t status = RBD_PROTECTION_STATUS_UNPROTECTED; ASSERT_EQ(-ENOENT, get_protection_status(&ioctx, oid, CEPH_NOSNAP, &status)); ASSERT_EQ(-ENOENT, set_protection_status(&ioctx, oid, CEPH_NOSNAP, status)); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, RBD_FEATURE_LAYERING, oid, -1)); ASSERT_EQ(0, create_image(&ioctx, oid2, 0, 22, 0, oid, -1)); ASSERT_EQ(-EINVAL, get_protection_status(&ioctx, oid2, CEPH_NOSNAP, &status)); ASSERT_EQ(-ENOEXEC, set_protection_status(&ioctx, oid2, CEPH_NOSNAP, status)); ASSERT_EQ(-EINVAL, get_protection_status(&ioctx, oid, CEPH_NOSNAP, &status)); ASSERT_EQ(-EINVAL, set_protection_status(&ioctx, oid, CEPH_NOSNAP, status)); ASSERT_EQ(-ENOENT, get_protection_status(&ioctx, oid, 2, &status)); ASSERT_EQ(-ENOENT, set_protection_status(&ioctx, oid, 2, status)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 10, "snap1")); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 10, &status)); ASSERT_EQ(+RBD_PROTECTION_STATUS_UNPROTECTED, status); ASSERT_EQ(0, set_protection_status(&ioctx, oid, 10, RBD_PROTECTION_STATUS_PROTECTED)); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 10, &status)); ASSERT_EQ(+RBD_PROTECTION_STATUS_PROTECTED, status); ASSERT_EQ(-EBUSY, snapshot_remove(&ioctx, oid, 10)); ASSERT_EQ(0, set_protection_status(&ioctx, oid, 10, RBD_PROTECTION_STATUS_UNPROTECTING)); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 10, &status)); ASSERT_EQ(+RBD_PROTECTION_STATUS_UNPROTECTING, status); ASSERT_EQ(-EBUSY, snapshot_remove(&ioctx, oid, 10)); ASSERT_EQ(-EINVAL, set_protection_status(&ioctx, oid, 10, RBD_PROTECTION_STATUS_LAST)); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 10, &status)); ASSERT_EQ(+RBD_PROTECTION_STATUS_UNPROTECTING, status); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 20, "snap2")); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 20, &status)); ASSERT_EQ(+RBD_PROTECTION_STATUS_UNPROTECTED, status); ASSERT_EQ(0, set_protection_status(&ioctx, oid, 10, RBD_PROTECTION_STATUS_UNPROTECTED)); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 10, &status)); ASSERT_EQ(+RBD_PROTECTION_STATUS_UNPROTECTED, status); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 10)); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 20)); ioctx.close(); } TEST_F(TestClsRbd, snapshot_limits) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); librados::ObjectWriteOperation op; string oid = get_temp_image_name(); uint64_t limit; ASSERT_EQ(-ENOENT, snapshot_get_limit(&ioctx, oid, &limit)); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, RBD_FEATURE_LAYERING, oid, -1)); // if snapshot doesn't set limit, the limit is UINT64_MAX ASSERT_EQ(0, snapshot_get_limit(&ioctx, oid, &limit)); ASSERT_EQ(UINT64_MAX, limit); snapshot_set_limit(&op, 2); ASSERT_EQ(0, ioctx.operate(oid, &op)); ASSERT_EQ(0, snapshot_get_limit(&ioctx, oid, &limit)); ASSERT_EQ(2U, limit); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 10, "snap1")); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 20, "snap2")); ASSERT_EQ(-EDQUOT, snapshot_add(&ioctx, oid, 30, "snap3")); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 10)); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 20)); ioctx.close(); } TEST_F(TestClsRbd, parents_v1) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); cls::rbd::ParentImageSpec pspec; uint64_t size; ASSERT_EQ(-ENOENT, get_parent(&ioctx, "doesnotexist", CEPH_NOSNAP, &pspec, &size)); // old image should fail std::string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 33<<20, 22, 0, "old_blk.", -1)); // get nonexistent parent: succeed, return (-1, "", CEPH_NOSNAP), overlap 0 ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(pspec.pool_id, -1); ASSERT_STREQ("", pspec.image_id.c_str()); ASSERT_EQ(pspec.snap_id, CEPH_NOSNAP); ASSERT_EQ(size, 0ULL); pspec = {-1, "", "parent", 3}; ASSERT_EQ(-ENOEXEC, set_parent(&ioctx, oid, {-1, "", "parent", 3}, 10<<20)); ASSERT_EQ(-ENOEXEC, remove_parent(&ioctx, oid)); // new image will work oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 33<<20, 22, RBD_FEATURE_LAYERING, "foo.", -1)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(-1, pspec.pool_id); ASSERT_EQ(0, get_parent(&ioctx, oid, 123, &pspec, &size)); ASSERT_EQ(-1, pspec.pool_id); ASSERT_EQ(-EINVAL, set_parent(&ioctx, oid, {-1, "", "parent", 3}, 10<<20)); ASSERT_EQ(-EINVAL, set_parent(&ioctx, oid, {1, "", "", 3}, 10<<20)); ASSERT_EQ(-EINVAL, set_parent(&ioctx, oid, {1, "", "parent", CEPH_NOSNAP}, 10<<20)); ASSERT_EQ(-EINVAL, set_parent(&ioctx, oid, {1, "", "parent", 3}, 0)); pspec = {1, "", "parent", 3}; ASSERT_EQ(0, set_parent(&ioctx, oid, pspec, 10<<20)); ASSERT_EQ(-EEXIST, set_parent(&ioctx, oid, pspec, 10<<20)); ASSERT_EQ(-EEXIST, set_parent(&ioctx, oid, {2, "", "parent", 34}, 10<<20)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(0, remove_parent(&ioctx, oid)); ASSERT_EQ(-ENOENT, remove_parent(&ioctx, oid)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(-1, pspec.pool_id); // snapshots ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 3}, 10<<20)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 10, "snap1")); ASSERT_EQ(0, get_parent(&ioctx, oid, 10, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 10ull<<20); ASSERT_EQ(0, remove_parent(&ioctx, oid)); ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 3}, 5<<20)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 11, "snap2")); ASSERT_EQ(0, get_parent(&ioctx, oid, 10, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 10ull<<20); ASSERT_EQ(0, get_parent(&ioctx, oid, 11, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 5ull<<20); ASSERT_EQ(0, remove_parent(&ioctx, oid)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 12, "snap3")); ASSERT_EQ(0, get_parent(&ioctx, oid, 10, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 10ull<<20); ASSERT_EQ(0, get_parent(&ioctx, oid, 11, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 5ull<<20); ASSERT_EQ(0, get_parent(&ioctx, oid, 12, &pspec, &size)); ASSERT_EQ(-1, pspec.pool_id); // make sure set_parent takes min of our size and parent's size ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 3}, 1<<20)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 1ull<<20); ASSERT_EQ(0, remove_parent(&ioctx, oid)); ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 3}, 100<<20)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 33ull<<20); ASSERT_EQ(0, remove_parent(&ioctx, oid)); // make sure resize adjust parent overlap ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 3}, 10<<20)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 14, "snap4")); ASSERT_EQ(0, set_size(&ioctx, oid, 3 << 20)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 3ull<<20); ASSERT_EQ(0, get_parent(&ioctx, oid, 14, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 10ull<<20); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 15, "snap5")); ASSERT_EQ(0, set_size(&ioctx, oid, 30 << 20)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 3ull<<20); ASSERT_EQ(0, get_parent(&ioctx, oid, 14, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 10ull<<20); ASSERT_EQ(0, get_parent(&ioctx, oid, 15, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 3ull<<20); ASSERT_EQ(0, set_size(&ioctx, oid, 2 << 20)); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 2ull<<20); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 16, "snap6")); ASSERT_EQ(0, get_parent(&ioctx, oid, 16, &pspec, &size)); ASSERT_EQ(pspec.pool_id, 1); ASSERT_EQ(pspec.image_id, "parent"); ASSERT_EQ(pspec.snap_id, snapid_t(3)); ASSERT_EQ(size, 2ull<<20); ASSERT_EQ(0, ioctx.remove(oid)); ASSERT_EQ(0, create_image(&ioctx, oid, 33<<20, 22, RBD_FEATURE_LAYERING | RBD_FEATURE_DEEP_FLATTEN, "foo.", -1)); ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 3}, 100<<20)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 1, "snap1")); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 2, "snap2")); ASSERT_EQ(0, remove_parent(&ioctx, oid)); ASSERT_EQ(0, get_parent(&ioctx, oid, 1, &pspec, &size)); ASSERT_EQ(-1, pspec.pool_id); ASSERT_EQ(0, get_parent(&ioctx, oid, 2, &pspec, &size)); ASSERT_EQ(-1, pspec.pool_id); ASSERT_EQ(0, get_parent(&ioctx, oid, CEPH_NOSNAP, &pspec, &size)); ASSERT_EQ(-1, pspec.pool_id); ioctx.close(); } TEST_F(TestClsRbd, parents_v2) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); std::string oid = get_temp_image_name(); cls::rbd::ParentImageSpec parent_image_spec; std::optional<uint64_t> parent_overlap; ASSERT_EQ(-ENOENT, parent_get(&ioctx, oid, &parent_image_spec)); ASSERT_EQ(-ENOENT, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &parent_overlap)); ASSERT_EQ(-ENOENT, parent_attach(&ioctx, oid, parent_image_spec, 0ULL, false)); ASSERT_EQ(-ENOENT, parent_detach(&ioctx, oid)); // no layering support should fail oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 33<<20, 22, 0, "old_blk.", -1)); ASSERT_EQ(0, parent_get(&ioctx, oid, &parent_image_spec)); ASSERT_FALSE(parent_image_spec.exists()); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &parent_overlap)); ASSERT_EQ(std::nullopt, parent_overlap); ASSERT_EQ(-ENOEXEC, parent_attach(&ioctx, oid, parent_image_spec, 0ULL, false)); ASSERT_EQ(-ENOEXEC, parent_detach(&ioctx, oid)); // layering support available -- no pool namespaces oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 33<<20, 22, RBD_FEATURE_LAYERING, "foo.", -1)); ASSERT_EQ(0, parent_get(&ioctx, oid, &parent_image_spec)); ASSERT_FALSE(parent_image_spec.exists()); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &parent_overlap)); ASSERT_EQ(std::nullopt, parent_overlap); ASSERT_EQ(-EINVAL, parent_attach(&ioctx, oid, parent_image_spec, 0ULL, false)); ASSERT_EQ(-ENOENT, parent_detach(&ioctx, oid)); parent_image_spec = {1, "", "parent", 2}; parent_overlap = (33 << 20) + 1; ASSERT_EQ(0, parent_attach(&ioctx, oid, parent_image_spec, *parent_overlap, false)); ASSERT_EQ(-EEXIST, parent_attach(&ioctx, oid, parent_image_spec, *parent_overlap, false)); ASSERT_EQ(0, parent_attach(&ioctx, oid, parent_image_spec, *parent_overlap, true)); --(*parent_overlap); cls::rbd::ParentImageSpec on_disk_parent_image_spec; std::optional<uint64_t> on_disk_parent_overlap; ASSERT_EQ(0, parent_get(&ioctx, oid, &on_disk_parent_image_spec)); ASSERT_EQ(parent_image_spec, on_disk_parent_image_spec); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &on_disk_parent_overlap)); ASSERT_EQ(parent_overlap, on_disk_parent_overlap); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 10, "snap1")); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, 10, &on_disk_parent_overlap)); std::optional<uint64_t> snap_1_parent_overlap = parent_overlap; ASSERT_EQ(snap_1_parent_overlap, on_disk_parent_overlap); parent_overlap = (32 << 20); ASSERT_EQ(0, set_size(&ioctx, oid, *parent_overlap)); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &on_disk_parent_overlap)); ASSERT_EQ(parent_overlap, on_disk_parent_overlap); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, 10, &on_disk_parent_overlap)); ASSERT_EQ(snap_1_parent_overlap, on_disk_parent_overlap); ASSERT_EQ(0, parent_detach(&ioctx, oid)); ASSERT_EQ(-ENOENT, parent_detach(&ioctx, oid)); ASSERT_EQ(0, parent_get(&ioctx, oid, &on_disk_parent_image_spec)); ASSERT_EQ(parent_image_spec, on_disk_parent_image_spec); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &on_disk_parent_overlap)); ASSERT_EQ(std::nullopt, on_disk_parent_overlap); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 10)); ASSERT_EQ(0, parent_get(&ioctx, oid, &on_disk_parent_image_spec)); ASSERT_FALSE(on_disk_parent_image_spec.exists()); // clone across pool namespaces parent_image_spec.pool_namespace = "ns"; parent_overlap = 31 << 20; ASSERT_EQ(0, parent_attach(&ioctx, oid, parent_image_spec, *parent_overlap, false)); ASSERT_EQ(-EEXIST, parent_attach(&ioctx, oid, parent_image_spec, *parent_overlap, false)); ASSERT_EQ(0, parent_attach(&ioctx, oid, parent_image_spec, *parent_overlap, true)); ASSERT_EQ(0, parent_get(&ioctx, oid, &on_disk_parent_image_spec)); ASSERT_EQ(parent_image_spec, on_disk_parent_image_spec); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &on_disk_parent_overlap)); ASSERT_EQ(parent_overlap, on_disk_parent_overlap); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 10, "snap1")); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, 10, &on_disk_parent_overlap)); snap_1_parent_overlap = parent_overlap; ASSERT_EQ(snap_1_parent_overlap, on_disk_parent_overlap); parent_overlap = (30 << 20); ASSERT_EQ(0, set_size(&ioctx, oid, *parent_overlap)); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &on_disk_parent_overlap)); ASSERT_EQ(parent_overlap, on_disk_parent_overlap); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, 10, &on_disk_parent_overlap)); ASSERT_EQ(snap_1_parent_overlap, on_disk_parent_overlap); ASSERT_EQ(-EXDEV, remove_parent(&ioctx, oid)); ASSERT_EQ(0, parent_detach(&ioctx, oid)); ASSERT_EQ(-ENOENT, parent_detach(&ioctx, oid)); cls::rbd::ParentImageSpec on_disk_parent_spec; uint64_t legacy_parent_overlap; ASSERT_EQ(-EXDEV, get_parent(&ioctx, oid, CEPH_NOSNAP, &on_disk_parent_spec, &legacy_parent_overlap)); ASSERT_EQ(-EXDEV, get_parent(&ioctx, oid, 10, &on_disk_parent_spec, &legacy_parent_overlap)); ASSERT_EQ(0, parent_get(&ioctx, oid, &on_disk_parent_image_spec)); ASSERT_EQ(parent_image_spec, on_disk_parent_image_spec); ASSERT_EQ(0, parent_overlap_get(&ioctx, oid, CEPH_NOSNAP, &on_disk_parent_overlap)); ASSERT_EQ(std::nullopt, on_disk_parent_overlap); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 10)); ASSERT_EQ(0, parent_get(&ioctx, oid, &on_disk_parent_image_spec)); ASSERT_FALSE(on_disk_parent_image_spec.exists()); } TEST_F(TestClsRbd, snapshots) { cls::rbd::SnapshotNamespace userSnapNamespace = cls::rbd::UserSnapshotNamespace(); librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(-ENOENT, snapshot_add(&ioctx, oid, 0, "snap1")); ASSERT_EQ(0, create_image(&ioctx, oid, 10, 22, 0, oid, -1)); SnapContext snapc; cls::rbd::SnapshotInfo snap; std::string snap_name; uint64_t snap_size; uint8_t snap_order; ParentImageInfo parent; uint8_t protection_status; utime_t snap_timestamp; ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(0u, snapc.snaps.size()); ASSERT_EQ(0u, snapc.seq); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 0, "snap1")); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(1u, snapc.snaps.size()); ASSERT_EQ(0u, snapc.snaps[0]); ASSERT_EQ(0u, snapc.seq); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 0, &snap)); ASSERT_EQ("snap1", snap.name); ASSERT_EQ(userSnapNamespace, snap.snapshot_namespace); ASSERT_EQ(0, get_snapshot_name(&ioctx, oid, 0, &snap_name)); ASSERT_EQ("snap1", snap_name); ASSERT_EQ(0, get_size(&ioctx, oid, 0, &snap_size, &snap_order)); ASSERT_EQ(10U, snap_size); ASSERT_EQ(0, get_parent(&ioctx, oid, 0, &parent.spec, &parent.overlap)); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 0, &protection_status)); ASSERT_EQ(0, get_snapshot_timestamp(&ioctx, oid, 0, &snap_timestamp)); // snap with same id and name ASSERT_EQ(-EEXIST, snapshot_add(&ioctx, oid, 0, "snap1")); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(1u, snapc.snaps.size()); ASSERT_EQ(0u, snapc.snaps[0]); ASSERT_EQ(0u, snapc.seq); // snap with same id, different name ASSERT_EQ(-EEXIST, snapshot_add(&ioctx, oid, 0, "snap2")); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(1u, snapc.snaps.size()); ASSERT_EQ(0u, snapc.snaps[0]); ASSERT_EQ(0u, snapc.seq); // snap with different id, same name ASSERT_EQ(-EEXIST, snapshot_add(&ioctx, oid, 1, "snap1")); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(1u, snapc.snaps.size()); ASSERT_EQ(0u, snapc.snaps[0]); ASSERT_EQ(0u, snapc.seq); // snap with different id, different name ASSERT_EQ(0, snapshot_add(&ioctx, oid, 1, "snap2")); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(2u, snapc.snaps.size()); ASSERT_EQ(1u, snapc.snaps[0]); ASSERT_EQ(0u, snapc.snaps[1]); ASSERT_EQ(1u, snapc.seq); // snap id less than current snap seq ASSERT_EQ(-ESTALE, snapshot_add(&ioctx, oid, 0, "snap3")); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 1, &snap)); ASSERT_EQ("snap2", snap.name); ASSERT_EQ(userSnapNamespace, snap.snapshot_namespace); ASSERT_EQ(0, get_snapshot_name(&ioctx, oid, 1, &snap_name)); ASSERT_EQ("snap2", snap_name); ASSERT_EQ(0, get_size(&ioctx, oid, 1, &snap_size, &snap_order)); ASSERT_EQ(10U, snap_size); ASSERT_EQ(0, get_parent(&ioctx, oid, 1, &parent.spec, &parent.overlap)); ASSERT_EQ(0, get_protection_status(&ioctx, oid, 1, &protection_status)); ASSERT_EQ(0, get_snapshot_timestamp(&ioctx, oid, 1, &snap_timestamp)); ASSERT_EQ(0, snapshot_rename(&ioctx, oid, 0, "snap1-rename")); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 0, &snap)); ASSERT_EQ("snap1-rename", snap.name); ASSERT_EQ(0, get_snapshot_name(&ioctx, oid, 0, &snap_name)); ASSERT_EQ("snap1-rename", snap_name); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 0)); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(1u, snapc.snaps.size()); ASSERT_EQ(1u, snapc.snaps[0]); ASSERT_EQ(1u, snapc.seq); uint64_t size; uint8_t order; ASSERT_EQ(0, set_size(&ioctx, oid, 0)); ASSERT_EQ(0, get_size(&ioctx, oid, CEPH_NOSNAP, &size, &order)); ASSERT_EQ(0u, size); ASSERT_EQ(22u, order); uint64_t large_snap_id = 1ull << 63; ASSERT_EQ(0, snapshot_add(&ioctx, oid, large_snap_id, "snap3")); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(2u, snapc.snaps.size()); ASSERT_EQ(large_snap_id, snapc.snaps[0]); ASSERT_EQ(1u, snapc.snaps[1]); ASSERT_EQ(large_snap_id, snapc.seq); ASSERT_EQ(0, snapshot_get(&ioctx, oid, large_snap_id, &snap)); ASSERT_EQ("snap3", snap.name); ASSERT_EQ(0, get_snapshot_name(&ioctx, oid, large_snap_id, &snap_name)); ASSERT_EQ("snap3", snap_name); ASSERT_EQ(0, get_size(&ioctx, oid, large_snap_id, &snap_size, &snap_order)); ASSERT_EQ(0U, snap_size); ASSERT_EQ(22u, snap_order); ASSERT_EQ(0, get_size(&ioctx, oid, 1, &snap_size, &snap_order)); ASSERT_EQ(10u, snap_size); ASSERT_EQ(22u, snap_order); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, large_snap_id)); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(1u, snapc.snaps.size()); ASSERT_EQ(1u, snapc.snaps[0]); ASSERT_EQ(large_snap_id, snapc.seq); ASSERT_EQ(-ENOENT, snapshot_remove(&ioctx, oid, large_snap_id)); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 1)); ASSERT_EQ(0, get_snapcontext(&ioctx, oid, &snapc)); ASSERT_EQ(0u, snapc.snaps.size()); ASSERT_EQ(large_snap_id, snapc.seq); ioctx.close(); } TEST_F(TestClsRbd, snapid_race) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); buffer::list bl; buffer::ptr bp(4096); bp.zero(); bl.append(bp); string oid = get_temp_image_name(); ASSERT_EQ(0, ioctx.write(oid, bl, 4096, 0)); ASSERT_EQ(0, old_snapshot_add(&ioctx, oid, 1, "test1")); ASSERT_EQ(0, old_snapshot_add(&ioctx, oid, 3, "test3")); ASSERT_EQ(-ESTALE, old_snapshot_add(&ioctx, oid, 2, "test2")); ioctx.close(); } TEST_F(TestClsRbd, stripingv2) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); string oid2 = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 10, 22, 0, oid, -1)); uint64_t su = 65536, sc = 12; ASSERT_EQ(-ENOEXEC, get_stripe_unit_count(&ioctx, oid, &su, &sc)); ASSERT_EQ(-ENOEXEC, set_stripe_unit_count(&ioctx, oid, su, sc)); ASSERT_EQ(0, create_image(&ioctx, oid2, 10, 22, RBD_FEATURE_STRIPINGV2, oid2, -1)); ASSERT_EQ(0, get_stripe_unit_count(&ioctx, oid2, &su, &sc)); ASSERT_EQ(1ull << 22, su); ASSERT_EQ(1ull, sc); su = 8192; sc = 456; ASSERT_EQ(0, set_stripe_unit_count(&ioctx, oid2, su, sc)); su = sc = 0; ASSERT_EQ(0, get_stripe_unit_count(&ioctx, oid2, &su, &sc)); ASSERT_EQ(8192ull, su); ASSERT_EQ(456ull, sc); // su must not be larger than an object ASSERT_EQ(-EINVAL, set_stripe_unit_count(&ioctx, oid2, 1 << 23, 1)); // su must be a factor of object size ASSERT_EQ(-EINVAL, set_stripe_unit_count(&ioctx, oid2, 511, 1)); // su and sc must be non-zero ASSERT_EQ(-EINVAL, set_stripe_unit_count(&ioctx, oid2, 0, 1)); ASSERT_EQ(-EINVAL, set_stripe_unit_count(&ioctx, oid2, 1, 0)); ASSERT_EQ(-EINVAL, set_stripe_unit_count(&ioctx, oid2, 0, 0)); ioctx.close(); } TEST_F(TestClsRbd, object_map_save) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); BitVector<2> ref_bit_vector; ref_bit_vector.resize(32); for (uint64_t i = 0; i < ref_bit_vector.size(); ++i) { ref_bit_vector[i] = 1; } librados::ObjectWriteOperation op; object_map_save(&op, ref_bit_vector); ASSERT_EQ(0, ioctx.operate(oid, &op)); BitVector<2> osd_bit_vector; ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); } TEST_F(TestClsRbd, object_map_resize) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); BitVector<2> ref_bit_vector; ref_bit_vector.resize(32); for (uint64_t i = 0; i < ref_bit_vector.size(); ++i) { ref_bit_vector[i] = 1; } librados::ObjectWriteOperation op1; object_map_resize(&op1, ref_bit_vector.size(), 1); ASSERT_EQ(0, ioctx.operate(oid, &op1)); BitVector<2> osd_bit_vector; ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); ref_bit_vector.resize(64); for (uint64_t i = 32; i < ref_bit_vector.size(); ++i) { ref_bit_vector[i] = 2; } librados::ObjectWriteOperation op2; object_map_resize(&op2, ref_bit_vector.size(), 2); ASSERT_EQ(0, ioctx.operate(oid, &op2)); ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); ref_bit_vector.resize(32); librados::ObjectWriteOperation op3; object_map_resize(&op3, ref_bit_vector.size(), 1); ASSERT_EQ(-ESTALE, ioctx.operate(oid, &op3)); librados::ObjectWriteOperation op4; object_map_resize(&op4, ref_bit_vector.size(), 2); ASSERT_EQ(0, ioctx.operate(oid, &op4)); ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); ioctx.close(); } TEST_F(TestClsRbd, object_map_update) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); BitVector<2> ref_bit_vector; ref_bit_vector.resize(16); for (uint64_t i = 0; i < ref_bit_vector.size(); ++i) { ref_bit_vector[i] = 2; } BitVector<2> osd_bit_vector; librados::ObjectWriteOperation op1; object_map_resize(&op1, ref_bit_vector.size(), 2); ASSERT_EQ(0, ioctx.operate(oid, &op1)); ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); ref_bit_vector[7] = 1; ref_bit_vector[8] = 1; librados::ObjectWriteOperation op2; object_map_update(&op2, 7, 9, 1, boost::optional<uint8_t>()); ASSERT_EQ(0, ioctx.operate(oid, &op2)); ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); ref_bit_vector[7] = 3; ref_bit_vector[8] = 3; librados::ObjectWriteOperation op3; object_map_update(&op3, 6, 10, 3, 1); ASSERT_EQ(0, ioctx.operate(oid, &op3)); ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); ioctx.close(); } TEST_F(TestClsRbd, object_map_load_enoent) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); BitVector<2> osd_bit_vector; ASSERT_EQ(-ENOENT, object_map_load(&ioctx, oid, &osd_bit_vector)); ioctx.close(); } TEST_F(TestClsRbd, object_map_snap_add) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); BitVector<2> ref_bit_vector; ref_bit_vector.resize(16); for (uint64_t i = 0; i < ref_bit_vector.size(); ++i) { if (i < 4) { ref_bit_vector[i] = OBJECT_NONEXISTENT; } else { ref_bit_vector[i] = OBJECT_EXISTS; } } BitVector<2> osd_bit_vector; librados::ObjectWriteOperation op1; object_map_resize(&op1, ref_bit_vector.size(), OBJECT_EXISTS); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; object_map_update(&op2, 0, 4, OBJECT_NONEXISTENT, boost::optional<uint8_t>()); ASSERT_EQ(0, ioctx.operate(oid, &op2)); ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); librados::ObjectWriteOperation op3; object_map_snap_add(&op3); ASSERT_EQ(0, ioctx.operate(oid, &op3)); for (uint64_t i = 0; i < ref_bit_vector.size(); ++i) { if (ref_bit_vector[i] == OBJECT_EXISTS) { ref_bit_vector[i] = OBJECT_EXISTS_CLEAN; } } ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); } TEST_F(TestClsRbd, object_map_snap_remove) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); BitVector<2> ref_bit_vector; ref_bit_vector.resize(16); for (uint64_t i = 0; i < ref_bit_vector.size(); ++i) { if (i < 4) { ref_bit_vector[i] = OBJECT_EXISTS_CLEAN; } else { ref_bit_vector[i] = OBJECT_EXISTS; } } BitVector<2> osd_bit_vector; librados::ObjectWriteOperation op1; object_map_resize(&op1, ref_bit_vector.size(), OBJECT_EXISTS); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; object_map_update(&op2, 0, 4, OBJECT_EXISTS_CLEAN, boost::optional<uint8_t>()); ASSERT_EQ(0, ioctx.operate(oid, &op2)); ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); BitVector<2> snap_bit_vector; snap_bit_vector.resize(4); for (uint64_t i = 0; i < snap_bit_vector.size(); ++i) { if (i == 1 || i == 2) { snap_bit_vector[i] = OBJECT_EXISTS; } else { snap_bit_vector[i] = OBJECT_NONEXISTENT; } } librados::ObjectWriteOperation op3; object_map_snap_remove(&op3, snap_bit_vector); ASSERT_EQ(0, ioctx.operate(oid, &op3)); ref_bit_vector[1] = OBJECT_EXISTS; ref_bit_vector[2] = OBJECT_EXISTS; ASSERT_EQ(0, object_map_load(&ioctx, oid, &osd_bit_vector)); ASSERT_EQ(ref_bit_vector, osd_bit_vector); } TEST_F(TestClsRbd, flags) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); uint64_t flags; ASSERT_EQ(0, get_flags(&ioctx, oid, CEPH_NOSNAP, &flags)); ASSERT_EQ(0U, flags); librados::ObjectWriteOperation op1; set_flags(&op1, CEPH_NOSNAP, 3, 2); ASSERT_EQ(0, ioctx.operate(oid, &op1)); ASSERT_EQ(0, get_flags(&ioctx, oid, CEPH_NOSNAP, &flags)); ASSERT_EQ(2U, flags); uint64_t snap_id = 10; ASSERT_EQ(-ENOENT, get_flags(&ioctx, oid, snap_id, &flags)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, snap_id, "snap")); librados::ObjectWriteOperation op2; set_flags(&op2, snap_id, 31, 4); ASSERT_EQ(0, ioctx.operate(oid, &op2)); ASSERT_EQ(0, get_flags(&ioctx, oid, snap_id, &flags)); ASSERT_EQ(6U, flags); ioctx.close(); } TEST_F(TestClsRbd, metadata) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); map<string, bufferlist> pairs; string value; ASSERT_EQ(0, metadata_list(&ioctx, oid, "", 0, &pairs)); ASSERT_TRUE(pairs.empty()); pairs["key1"].append("value1"); pairs["key2"].append("value2"); ASSERT_EQ(0, metadata_set(&ioctx, oid, pairs)); ASSERT_EQ(0, metadata_get(&ioctx, oid, "key1", &value)); ASSERT_EQ(0, strcmp("value1", value.c_str())); pairs.clear(); ASSERT_EQ(0, metadata_list(&ioctx, oid, "", 0, &pairs)); ASSERT_EQ(2U, pairs.size()); ASSERT_EQ(0, strncmp("value1", pairs["key1"].c_str(), 6)); ASSERT_EQ(0, strncmp("value2", pairs["key2"].c_str(), 6)); pairs.clear(); ASSERT_EQ(0, metadata_remove(&ioctx, oid, "key1")); ASSERT_EQ(0, metadata_remove(&ioctx, oid, "key3")); ASSERT_TRUE(metadata_get(&ioctx, oid, "key1", &value) < 0); ASSERT_EQ(0, metadata_list(&ioctx, oid, "", 0, &pairs)); ASSERT_EQ(1U, pairs.size()); ASSERT_EQ(0, strncmp("value2", pairs["key2"].c_str(), 6)); pairs.clear(); char key[10], val[20]; for (int i = 0; i < 1024; i++) { sprintf(key, "key%d", i); sprintf(val, "value%d", i); pairs[key].append(val, strlen(val)); } ASSERT_EQ(0, metadata_set(&ioctx, oid, pairs)); string last_read = ""; uint64_t max_read = 48, r; uint64_t size = 0; map<string, bufferlist> data; do { map<string, bufferlist> cur; metadata_list(&ioctx, oid, last_read, max_read, &cur); size += cur.size(); for (map<string, bufferlist>::iterator it = cur.begin(); it != cur.end(); ++it) data[it->first] = it->second; last_read = cur.rbegin()->first; r = cur.size(); } while (r == max_read); ASSERT_EQ(size, 1024U); for (map<string, bufferlist>::iterator it = data.begin(); it != data.end(); ++it) { ASSERT_TRUE(it->second.contents_equal(pairs[it->first])); } ioctx.close(); } TEST_F(TestClsRbd, set_features) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); uint64_t base_features = RBD_FEATURE_LAYERING | RBD_FEATURE_DEEP_FLATTEN; ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, base_features, oid, -1)); uint64_t features = RBD_FEATURES_MUTABLE; uint64_t mask = RBD_FEATURES_MUTABLE; ASSERT_EQ(0, set_features(&ioctx, oid, features, mask)); uint64_t actual_features; uint64_t incompatible_features; ASSERT_EQ(0, get_features(&ioctx, oid, true, &actual_features, &incompatible_features)); uint64_t expected_features = RBD_FEATURES_MUTABLE | base_features; ASSERT_EQ(expected_features, actual_features); features = 0; mask = RBD_FEATURE_OBJECT_MAP; ASSERT_EQ(0, set_features(&ioctx, oid, features, mask)); ASSERT_EQ(0, get_features(&ioctx, oid, true, &actual_features, &incompatible_features)); expected_features = (RBD_FEATURES_MUTABLE | base_features) & ~RBD_FEATURE_OBJECT_MAP; ASSERT_EQ(expected_features, actual_features); ASSERT_EQ(0, set_features(&ioctx, oid, 0, RBD_FEATURE_DEEP_FLATTEN)); ASSERT_EQ(-EINVAL, set_features(&ioctx, oid, RBD_FEATURE_DEEP_FLATTEN, RBD_FEATURE_DEEP_FLATTEN)); ASSERT_EQ(-EINVAL, set_features(&ioctx, oid, 0, RBD_FEATURE_LAYERING)); ASSERT_EQ(-EINVAL, set_features(&ioctx, oid, 0, RBD_FEATURE_OPERATIONS)); } TEST_F(TestClsRbd, mirror) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_MIRRORING); std::vector<cls::rbd::MirrorPeer> peers; ASSERT_EQ(-ENOENT, mirror_peer_list(&ioctx, &peers)); std::string uuid; ASSERT_EQ(-ENOENT, mirror_uuid_get(&ioctx, &uuid)); ASSERT_EQ(-EINVAL, mirror_peer_add(&ioctx, {"uuid1", MIRROR_PEER_DIRECTION_RX, "siteA", "client", "mirror uuid"})); ASSERT_EQ(-EINVAL, mirror_peer_ping(&ioctx, "siteA", "mirror uuid")); cls::rbd::MirrorMode mirror_mode; ASSERT_EQ(0, mirror_mode_get(&ioctx, &mirror_mode)); ASSERT_EQ(cls::rbd::MIRROR_MODE_DISABLED, mirror_mode); ASSERT_EQ(-EINVAL, mirror_mode_set(&ioctx, cls::rbd::MIRROR_MODE_IMAGE)); ASSERT_EQ(-EINVAL, mirror_uuid_set(&ioctx, "")); ASSERT_EQ(0, mirror_uuid_set(&ioctx, "mirror-uuid")); ASSERT_EQ(0, mirror_uuid_get(&ioctx, &uuid)); ASSERT_EQ("mirror-uuid", uuid); ASSERT_EQ(0, mirror_mode_set(&ioctx, cls::rbd::MIRROR_MODE_IMAGE)); ASSERT_EQ(0, mirror_mode_get(&ioctx, &mirror_mode)); ASSERT_EQ(cls::rbd::MIRROR_MODE_IMAGE, mirror_mode); ASSERT_EQ(-EINVAL, mirror_uuid_set(&ioctx, "new-mirror-uuid")); ASSERT_EQ(0, mirror_mode_set(&ioctx, cls::rbd::MIRROR_MODE_POOL)); ASSERT_EQ(0, mirror_mode_get(&ioctx, &mirror_mode)); ASSERT_EQ(cls::rbd::MIRROR_MODE_POOL, mirror_mode); ASSERT_EQ(-EINVAL, mirror_peer_add(&ioctx, {"mirror-uuid", MIRROR_PEER_DIRECTION_RX, "siteA", "client", ""})); ASSERT_EQ(-EINVAL, mirror_peer_add(&ioctx, {"uuid1", MIRROR_PEER_DIRECTION_TX, "siteA", "client", "mirror uuid"})); ASSERT_EQ(0, mirror_peer_add(&ioctx, {"uuid1", MIRROR_PEER_DIRECTION_RX, "siteA", "client", "fsidA"})); ASSERT_EQ(0, mirror_peer_add(&ioctx, {"uuid2", MIRROR_PEER_DIRECTION_RX, "siteB", "admin", ""})); ASSERT_EQ(-ESTALE, mirror_peer_add(&ioctx, {"uuid2", MIRROR_PEER_DIRECTION_RX, "siteC", "foo", ""})); ASSERT_EQ(-EEXIST, mirror_peer_add(&ioctx, {"uuid3", MIRROR_PEER_DIRECTION_RX, "siteA", "foo", ""})); ASSERT_EQ(-EEXIST, mirror_peer_add(&ioctx, {"uuid3", MIRROR_PEER_DIRECTION_RX, "siteC", "client", "fsidA"})); ASSERT_EQ(0, mirror_peer_add(&ioctx, {"uuid3", MIRROR_PEER_DIRECTION_RX, "siteC", "admin", ""})); ASSERT_EQ(0, mirror_peer_add(&ioctx, {"uuid4", MIRROR_PEER_DIRECTION_RX, "siteD", "admin", ""})); ASSERT_EQ(0, mirror_peer_list(&ioctx, &peers)); std::vector<cls::rbd::MirrorPeer> expected_peers = { {"uuid1", MIRROR_PEER_DIRECTION_RX, "siteA", "client", "fsidA"}, {"uuid2", MIRROR_PEER_DIRECTION_RX, "siteB", "admin", ""}, {"uuid3", MIRROR_PEER_DIRECTION_RX, "siteC", "admin", ""}, {"uuid4", MIRROR_PEER_DIRECTION_RX, "siteD", "admin", ""}}; ASSERT_EQ(expected_peers, peers); ASSERT_EQ(0, mirror_peer_remove(&ioctx, "uuid5")); ASSERT_EQ(0, mirror_peer_remove(&ioctx, "uuid4")); ASSERT_EQ(0, mirror_peer_remove(&ioctx, "uuid2")); ASSERT_EQ(0, mirror_peer_list(&ioctx, &peers)); expected_peers = { {"uuid1", MIRROR_PEER_DIRECTION_RX, "siteA", "client", "fsidA"}, {"uuid3", MIRROR_PEER_DIRECTION_RX, "siteC", "admin", ""}}; ASSERT_EQ(expected_peers, peers); ASSERT_EQ(-ENOENT, mirror_peer_set_client(&ioctx, "uuid4", "new client")); ASSERT_EQ(0, mirror_peer_set_client(&ioctx, "uuid1", "new client")); ASSERT_EQ(-ENOENT, mirror_peer_set_cluster(&ioctx, "uuid4", "new site")); ASSERT_EQ(0, mirror_peer_set_cluster(&ioctx, "uuid3", "new site")); ASSERT_EQ(0, mirror_peer_list(&ioctx, &peers)); expected_peers = { {"uuid1", MIRROR_PEER_DIRECTION_RX, "siteA", "new client", "fsidA"}, {"uuid3", MIRROR_PEER_DIRECTION_RX, "new site", "admin", ""}}; ASSERT_EQ(expected_peers, peers); ASSERT_EQ(0, mirror_peer_remove(&ioctx, "uuid1")); ASSERT_EQ(0, mirror_peer_list(&ioctx, &peers)); expected_peers = { {"uuid3", MIRROR_PEER_DIRECTION_RX, "new site", "admin", ""}}; ASSERT_EQ(expected_peers, peers); ASSERT_EQ(-EINVAL, mirror_peer_ping(&ioctx, "", "mirror uuid")); ASSERT_EQ(-EINVAL, mirror_peer_ping(&ioctx, "new site", "")); ASSERT_EQ(0, mirror_peer_ping(&ioctx, "new site", "mirror uuid")); ASSERT_EQ(0, mirror_peer_list(&ioctx, &peers)); ASSERT_EQ(1U, peers.size()); ASSERT_LT(utime_t{}, peers[0].last_seen); expected_peers = { {"uuid3", MIRROR_PEER_DIRECTION_RX_TX, "new site", "admin", "mirror uuid"}}; expected_peers[0].last_seen = peers[0].last_seen; ASSERT_EQ(expected_peers, peers); ASSERT_EQ(0, mirror_peer_remove(&ioctx, "uuid3")); ASSERT_EQ(0, mirror_peer_ping(&ioctx, "siteA", "mirror uuid")); ASSERT_EQ(0, mirror_peer_list(&ioctx, &peers)); ASSERT_EQ(1U, peers.size()); ASSERT_FALSE(peers[0].uuid.empty()); ASSERT_LT(utime_t{}, peers[0].last_seen); expected_peers = { {peers[0].uuid, MIRROR_PEER_DIRECTION_TX, "siteA", "", "mirror uuid"}}; expected_peers[0].last_seen = peers[0].last_seen; ASSERT_EQ(expected_peers, peers); ASSERT_EQ(-EBUSY, mirror_mode_set(&ioctx, cls::rbd::MIRROR_MODE_DISABLED)); ASSERT_EQ(0, mirror_peer_remove(&ioctx, peers[0].uuid)); ASSERT_EQ(0, mirror_peer_remove(&ioctx, "DNE")); ASSERT_EQ(0, mirror_peer_list(&ioctx, &peers)); expected_peers = {}; ASSERT_EQ(expected_peers, peers); ASSERT_EQ(0, mirror_mode_set(&ioctx, cls::rbd::MIRROR_MODE_DISABLED)); ASSERT_EQ(0, mirror_mode_get(&ioctx, &mirror_mode)); ASSERT_EQ(cls::rbd::MIRROR_MODE_DISABLED, mirror_mode); ASSERT_EQ(-ENOENT, mirror_uuid_get(&ioctx, &uuid)); } TEST_F(TestClsRbd, mirror_image) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_MIRRORING); std::map<std::string, std::string> mirror_image_ids; ASSERT_EQ(-ENOENT, mirror_image_list(&ioctx, "", 0, &mirror_image_ids)); cls::rbd::MirrorImage image1(cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "uuid1", cls::rbd::MIRROR_IMAGE_STATE_ENABLED); cls::rbd::MirrorImage image2(cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "uuid2", cls::rbd::MIRROR_IMAGE_STATE_DISABLING); cls::rbd::MirrorImage image3(cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "uuid3", cls::rbd::MIRROR_IMAGE_STATE_ENABLED); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id1", image1)); ASSERT_EQ(-ENOENT, mirror_image_set(&ioctx, "image_id2", image2)); image2.state = cls::rbd::MIRROR_IMAGE_STATE_ENABLED; ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id2", image2)); image2.state = cls::rbd::MIRROR_IMAGE_STATE_DISABLING; ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id2", image2)); ASSERT_EQ(-EINVAL, mirror_image_set(&ioctx, "image_id1", image2)); ASSERT_EQ(-EEXIST, mirror_image_set(&ioctx, "image_id3", image2)); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id3", image3)); std::string image_id; ASSERT_EQ(0, mirror_image_get_image_id(&ioctx, "uuid2", &image_id)); ASSERT_EQ("image_id2", image_id); cls::rbd::MirrorImage read_image; ASSERT_EQ(0, mirror_image_get(&ioctx, "image_id1", &read_image)); ASSERT_EQ(read_image, image1); ASSERT_EQ(0, mirror_image_get(&ioctx, "image_id2", &read_image)); ASSERT_EQ(read_image, image2); ASSERT_EQ(0, mirror_image_get(&ioctx, "image_id3", &read_image)); ASSERT_EQ(read_image, image3); ASSERT_EQ(0, mirror_image_list(&ioctx, "", 1, &mirror_image_ids)); std::map<std::string, std::string> expected_mirror_image_ids = { {"image_id1", "uuid1"}}; ASSERT_EQ(expected_mirror_image_ids, mirror_image_ids); ASSERT_EQ(0, mirror_image_list(&ioctx, "image_id1", 2, &mirror_image_ids)); expected_mirror_image_ids = {{"image_id2", "uuid2"}, {"image_id3", "uuid3"}}; ASSERT_EQ(expected_mirror_image_ids, mirror_image_ids); ASSERT_EQ(0, mirror_image_remove(&ioctx, "image_id2")); ASSERT_EQ(-ENOENT, mirror_image_get_image_id(&ioctx, "uuid2", &image_id)); ASSERT_EQ(-EBUSY, mirror_image_remove(&ioctx, "image_id1")); ASSERT_EQ(0, mirror_image_list(&ioctx, "", 3, &mirror_image_ids)); expected_mirror_image_ids = {{"image_id1", "uuid1"}, {"image_id3", "uuid3"}}; ASSERT_EQ(expected_mirror_image_ids, mirror_image_ids); image1.state = cls::rbd::MIRROR_IMAGE_STATE_DISABLING; image3.state = cls::rbd::MIRROR_IMAGE_STATE_DISABLING; ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id1", image1)); ASSERT_EQ(0, mirror_image_get(&ioctx, "image_id1", &read_image)); ASSERT_EQ(read_image, image1); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id3", image3)); ASSERT_EQ(0, mirror_image_remove(&ioctx, "image_id1")); ASSERT_EQ(0, mirror_image_remove(&ioctx, "image_id3")); ASSERT_EQ(0, mirror_image_list(&ioctx, "", 3, &mirror_image_ids)); expected_mirror_image_ids = {}; ASSERT_EQ(expected_mirror_image_ids, mirror_image_ids); } TEST_F(TestClsRbd, mirror_image_status) { struct WatchCtx : public librados::WatchCtx2 { librados::IoCtx *m_ioctx; explicit WatchCtx(librados::IoCtx *ioctx) : m_ioctx(ioctx) {} void handle_notify(uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl_) override { bufferlist bl; m_ioctx->notify_ack(RBD_MIRRORING, notify_id, cookie, bl); } void handle_error(uint64_t cookie, int err) override {} }; map<std::string, cls::rbd::MirrorImage> images; map<std::string, cls::rbd::MirrorImageStatus> statuses; std::map<cls::rbd::MirrorImageStatusState, int32_t> states; std::map<std::string, entity_inst_t> instances; cls::rbd::MirrorImageStatus read_status; entity_inst_t read_instance; uint64_t watch_handle; librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_MIRRORING); int64_t instance_id = librados::Rados(ioctx).get_instance_id(); // Test list fails on nonexistent RBD_MIRRORING object ASSERT_EQ(-ENOENT, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); // Test status set cls::rbd::MirrorImage image1(cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "uuid1", cls::rbd::MIRROR_IMAGE_STATE_ENABLED); cls::rbd::MirrorImage image2(cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "uuid2", cls::rbd::MIRROR_IMAGE_STATE_ENABLED); cls::rbd::MirrorImage image3(cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "uuid3", cls::rbd::MIRROR_IMAGE_STATE_ENABLED); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id1", image1)); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id2", image2)); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id3", image3)); cls::rbd::MirrorImageSiteStatus status1( "", cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN, ""); cls::rbd::MirrorImageSiteStatus status2( "", cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING, ""); cls::rbd::MirrorImageSiteStatus status3( "", cls::rbd::MIRROR_IMAGE_STATUS_STATE_ERROR, ""); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid1", status1)); images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); ASSERT_EQ(3U, images.size()); ASSERT_EQ(1U, statuses.size()); // Test status is down due to RBD_MIRRORING is not watched status1.up = false; ASSERT_EQ(statuses["image_id1"], cls::rbd::MirrorImageStatus{{status1}}); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid1", &read_status)); ASSERT_EQ(read_status, cls::rbd::MirrorImageStatus{{status1}}); // Test status summary. All statuses are unknown due to down. states.clear(); cls::rbd::MirrorPeer mirror_peer{ "uuid", cls::rbd::MIRROR_PEER_DIRECTION_RX, "siteA", "client", "fsidA"}; ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(1U, states.size()); ASSERT_EQ(3, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN]); // Test get instance return -ESTALE due to down. ASSERT_EQ(-ESTALE, mirror_image_instance_get(&ioctx, "uuid1", &read_instance)); instances.clear(); ASSERT_EQ(0, mirror_image_instance_list(&ioctx, "", 1024, &instances)); ASSERT_TRUE(instances.empty()); // Test remove_down removes stale statuses ASSERT_EQ(0, mirror_image_status_remove_down(&ioctx)); ASSERT_EQ(-ENOENT, mirror_image_status_get(&ioctx, "uuid1", &read_status)); ASSERT_EQ(-ENOENT, mirror_image_instance_get(&ioctx, "uuid1", &read_instance)); ASSERT_EQ(0, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); ASSERT_EQ(3U, images.size()); ASSERT_TRUE(statuses.empty()); ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(1U, states.size()); ASSERT_EQ(3, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN]); // Test remove of status ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid1", status1)); ASSERT_EQ(0, mirror_image_status_remove(&ioctx, "uuid1")); ASSERT_EQ(-ENOENT, mirror_image_instance_get(&ioctx, "uuid1", &read_instance)); // Test statuses are not down after watcher is started ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid1", status1)); WatchCtx watch_ctx(&ioctx); ASSERT_EQ(0, ioctx.watch2(RBD_MIRRORING, &watch_handle, &watch_ctx)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid2", status2)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid3", status3)); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid1", &read_status)); status1.up = true; ASSERT_EQ(read_status, cls::rbd::MirrorImageStatus{{status1}}); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid2", &read_status)); status2.up = true; ASSERT_EQ(read_status, cls::rbd::MirrorImageStatus{{status2}}); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid3", &read_status)); status3.up = true; ASSERT_EQ(read_status, cls::rbd::MirrorImageStatus{{status3}}); images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); ASSERT_EQ(3U, images.size()); ASSERT_EQ(3U, statuses.size()); ASSERT_EQ(statuses["image_id1"], cls::rbd::MirrorImageStatus{{status1}}); ASSERT_EQ(statuses["image_id2"], cls::rbd::MirrorImageStatus{{status2}}); ASSERT_EQ(statuses["image_id3"], cls::rbd::MirrorImageStatus{{status3}}); read_instance = {}; ASSERT_EQ(0, mirror_image_instance_get(&ioctx, "uuid1", &read_instance)); ASSERT_EQ(read_instance.name.num(), instance_id); instances.clear(); ASSERT_EQ(0, mirror_image_instance_list(&ioctx, "", 1024, &instances)); ASSERT_EQ(3U, instances.size()); ASSERT_EQ(instances["image_id1"].name.num(), instance_id); ASSERT_EQ(instances["image_id2"].name.num(), instance_id); ASSERT_EQ(instances["image_id3"].name.num(), instance_id); ASSERT_EQ(0, mirror_image_status_remove_down(&ioctx)); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid1", &read_status)); ASSERT_EQ(read_status, cls::rbd::MirrorImageStatus{{status1}}); images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); ASSERT_EQ(3U, images.size()); ASSERT_EQ(3U, statuses.size()); ASSERT_EQ(statuses["image_id1"], cls::rbd::MirrorImageStatus{{status1}}); ASSERT_EQ(statuses["image_id2"], cls::rbd::MirrorImageStatus{{status2}}); ASSERT_EQ(statuses["image_id3"], cls::rbd::MirrorImageStatus{{status3}}); states.clear(); ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(3U, states.size()); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN]); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING]); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_ERROR]); // Test update status1.state = status3.state = cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING; ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid1", status1)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid3", status3)); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid3", &read_status)); ASSERT_EQ(read_status, cls::rbd::MirrorImageStatus{{status3}}); states.clear(); ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(1U, states.size()); ASSERT_EQ(3, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING]); // Remote status ASSERT_EQ(0, mirror_uuid_set(&ioctx, "mirror-uuid")); ASSERT_EQ(0, mirror_mode_set(&ioctx, cls::rbd::MIRROR_MODE_POOL)); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid1", &read_status)); cls::rbd::MirrorImageStatus expected_status1({status1}); ASSERT_EQ(expected_status1, read_status); cls::rbd::MirrorImageSiteStatus remote_status1( "fsidA", cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING, ""); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid1", remote_status1)); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid1", &read_status)); remote_status1.up = true; expected_status1 = {{status1, remote_status1}}; ASSERT_EQ(expected_status1, read_status); // summary under different modes cls::rbd::MirrorImageSiteStatus remote_status2( "fsidA", cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING, ""); remote_status2.up = true; cls::rbd::MirrorImageSiteStatus remote_status3( "fsidA", cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN, ""); remote_status3.up = true; status1.state = cls::rbd::MIRROR_IMAGE_STATUS_STATE_ERROR; ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid1", status1)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid2", status2)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid3", status3)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid2", remote_status2)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, "uuid3", remote_status3)); expected_status1 = {{status1, remote_status1}}; cls::rbd::MirrorImageStatus expected_status2({status2, remote_status2}); cls::rbd::MirrorImageStatus expected_status3({status3, remote_status3}); images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); ASSERT_EQ(3U, images.size()); ASSERT_EQ(3U, statuses.size()); ASSERT_EQ(statuses["image_id1"], expected_status1); ASSERT_EQ(statuses["image_id2"], expected_status2); ASSERT_EQ(statuses["image_id3"], expected_status3); states.clear(); mirror_peer.mirror_peer_direction = cls::rbd::MIRROR_PEER_DIRECTION_RX; ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(2U, states.size()); ASSERT_EQ(2, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING]); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_ERROR]); states.clear(); mirror_peer.mirror_peer_direction = cls::rbd::MIRROR_PEER_DIRECTION_TX; ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(2U, states.size()); ASSERT_EQ(2, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING]); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN]); states.clear(); mirror_peer.mirror_peer_direction = cls::rbd::MIRROR_PEER_DIRECTION_RX_TX; ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(3U, states.size()); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_REPLAYING]); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN]); ASSERT_EQ(1, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_ERROR]); // Test statuses are down after removing watcher ioctx.unwatch2(watch_handle); ASSERT_EQ(0, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); ASSERT_EQ(3U, images.size()); ASSERT_EQ(3U, statuses.size()); status1.up = false; remote_status1.up = false; expected_status1 = {{status1, remote_status1}}; ASSERT_EQ(statuses["image_id1"], expected_status1); status2.up = false; remote_status2.up = false; expected_status2 = {{status2, remote_status2}}; ASSERT_EQ(statuses["image_id2"], expected_status2); status3.up = false; remote_status3.up = false; expected_status3 = {{status3, remote_status3}}; ASSERT_EQ(statuses["image_id3"], expected_status3); ASSERT_EQ(0, mirror_image_status_get(&ioctx, "uuid1", &read_status)); ASSERT_EQ(read_status, expected_status1); states.clear(); ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(1U, states.size()); ASSERT_EQ(3, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN]); ASSERT_EQ(-ESTALE, mirror_image_instance_get(&ioctx, "uuid1", &read_instance)); instances.clear(); ASSERT_EQ(0, mirror_image_instance_list(&ioctx, "", 1024, &instances)); ASSERT_TRUE(instances.empty()); ASSERT_EQ(0, mirror_image_status_remove_down(&ioctx)); ASSERT_EQ(-ENOENT, mirror_image_status_get(&ioctx, "uuid1", &read_status)); images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, "", 1024, &images, &statuses)); ASSERT_EQ(3U, images.size()); ASSERT_TRUE(statuses.empty()); states.clear(); ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {mirror_peer}, &states)); ASSERT_EQ(1U, states.size()); ASSERT_EQ(3, states[cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN]); // Remove images image1.state = cls::rbd::MIRROR_IMAGE_STATE_DISABLING; image2.state = cls::rbd::MIRROR_IMAGE_STATE_DISABLING; image3.state = cls::rbd::MIRROR_IMAGE_STATE_DISABLING; ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id1", image1)); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id2", image2)); ASSERT_EQ(0, mirror_image_set(&ioctx, "image_id3", image3)); ASSERT_EQ(0, mirror_image_remove(&ioctx, "image_id1")); ASSERT_EQ(0, mirror_image_remove(&ioctx, "image_id2")); ASSERT_EQ(0, mirror_image_remove(&ioctx, "image_id3")); states.clear(); ASSERT_EQ(0, mirror_image_status_get_summary(&ioctx, {}, &states)); ASSERT_EQ(0U, states.size()); // Test status list with large number of images size_t N = 1024; ASSERT_EQ(0U, N % 2); for (size_t i = 0; i < N; i++) { std::string id = "id" + stringify(i); std::string uuid = "uuid" + stringify(i); cls::rbd::MirrorImage image(cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, uuid, cls::rbd::MIRROR_IMAGE_STATE_ENABLED); cls::rbd::MirrorImageSiteStatus status( "", cls::rbd::MIRROR_IMAGE_STATUS_STATE_UNKNOWN, ""); ASSERT_EQ(0, mirror_image_set(&ioctx, id, image)); ASSERT_EQ(0, mirror_image_status_set(&ioctx, uuid, status)); } std::string last_read = ""; images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, last_read, N * 2, &images, &statuses)); ASSERT_EQ(N, images.size()); ASSERT_EQ(N, statuses.size()); images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, last_read, N / 2, &images, &statuses)); ASSERT_EQ(N / 2, images.size()); ASSERT_EQ(N / 2, statuses.size()); last_read = images.rbegin()->first; images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, last_read, N / 2, &images, &statuses)); ASSERT_EQ(N / 2, images.size()); ASSERT_EQ(N / 2, statuses.size()); last_read = images.rbegin()->first; images.clear(); statuses.clear(); ASSERT_EQ(0, mirror_image_status_list(&ioctx, last_read, N / 2, &images, &statuses)); ASSERT_EQ(0U, images.size()); ASSERT_EQ(0U, statuses.size()); } TEST_F(TestClsRbd, mirror_image_map) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_MIRRORING); std::map<std::string, cls::rbd::MirrorImageMap> image_mapping; ASSERT_EQ(-ENOENT, mirror_image_map_list(&ioctx, "", 0, &image_mapping)); utime_t expected_time = ceph_clock_now(); bufferlist expected_data; expected_data.append("test"); std::map<std::string, cls::rbd::MirrorImageMap> expected_image_mapping; while (expected_image_mapping.size() < 1024) { librados::ObjectWriteOperation op; for (uint32_t i = 0; i < 32; ++i) { std::string global_image_id{stringify(expected_image_mapping.size())}; cls::rbd::MirrorImageMap mirror_image_map{ stringify(i), expected_time, expected_data}; expected_image_mapping.emplace(global_image_id, mirror_image_map); mirror_image_map_update(&op, global_image_id, mirror_image_map); } ASSERT_EQ(0, ioctx.operate(RBD_MIRRORING, &op)); } ASSERT_EQ(0, mirror_image_map_list(&ioctx, "", 1000, &image_mapping)); ASSERT_EQ(1000U, image_mapping.size()); ASSERT_EQ(0, mirror_image_map_list(&ioctx, image_mapping.rbegin()->first, 1000, &image_mapping)); ASSERT_EQ(24U, image_mapping.size()); const auto& image_map = *image_mapping.begin(); ASSERT_EQ("978", image_map.first); cls::rbd::MirrorImageMap expected_mirror_image_map{ stringify(18), expected_time, expected_data}; ASSERT_EQ(expected_mirror_image_map, image_map.second); expected_time = ceph_clock_now(); expected_mirror_image_map.mapped_time = expected_time; expected_data.append("update"); expected_mirror_image_map.data = expected_data; librados::ObjectWriteOperation op; mirror_image_map_remove(&op, "1"); mirror_image_map_update(&op, "10", expected_mirror_image_map); ASSERT_EQ(0, ioctx.operate(RBD_MIRRORING, &op)); ASSERT_EQ(0, mirror_image_map_list(&ioctx, "0", 1, &image_mapping)); ASSERT_EQ(1U, image_mapping.size()); const auto& updated_image_map = *image_mapping.begin(); ASSERT_EQ("10", updated_image_map.first); ASSERT_EQ(expected_mirror_image_map, updated_image_map.second); } TEST_F(TestClsRbd, mirror_instances) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_MIRROR_LEADER); std::vector<std::string> instance_ids; ASSERT_EQ(-ENOENT, mirror_instances_list(&ioctx, &instance_ids)); ASSERT_EQ(0, ioctx.create(RBD_MIRROR_LEADER, true)); ASSERT_EQ(0, mirror_instances_list(&ioctx, &instance_ids)); ASSERT_EQ(0U, instance_ids.size()); ASSERT_EQ(0, mirror_instances_add(&ioctx, "instance_id1")); ASSERT_EQ(0, mirror_instances_list(&ioctx, &instance_ids)); ASSERT_EQ(1U, instance_ids.size()); ASSERT_EQ(instance_ids[0], "instance_id1"); ASSERT_EQ(0, mirror_instances_add(&ioctx, "instance_id1")); ASSERT_EQ(0, mirror_instances_add(&ioctx, "instance_id2")); ASSERT_EQ(0, mirror_instances_list(&ioctx, &instance_ids)); ASSERT_EQ(2U, instance_ids.size()); ASSERT_EQ(0, mirror_instances_remove(&ioctx, "instance_id1")); ASSERT_EQ(0, mirror_instances_list(&ioctx, &instance_ids)); ASSERT_EQ(1U, instance_ids.size()); ASSERT_EQ(instance_ids[0], "instance_id2"); ASSERT_EQ(0, mirror_instances_remove(&ioctx, "instance_id2")); ASSERT_EQ(0, mirror_instances_list(&ioctx, &instance_ids)); ASSERT_EQ(0U, instance_ids.size()); } TEST_F(TestClsRbd, mirror_snapshot) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 10, 22, 0, oid, -1)); cls::rbd::MirrorSnapshotNamespace primary = { cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer1", "peer2"}, "", CEPH_NOSNAP}; cls::rbd::MirrorSnapshotNamespace non_primary = { cls::rbd::MIRROR_SNAPSHOT_STATE_NON_PRIMARY, {"peer1"}, "uuid", 123}; librados::ObjectWriteOperation op; ::librbd::cls_client::snapshot_add(&op, 1, "primary", primary); ::librbd::cls_client::snapshot_add(&op, 2, "non_primary", non_primary); ASSERT_EQ(0, ioctx.operate(oid, &op)); cls::rbd::SnapshotInfo snap; ASSERT_EQ(0, snapshot_get(&ioctx, oid, 1, &snap)); auto sn = std::get_if<cls::rbd::MirrorSnapshotNamespace>( &snap.snapshot_namespace); ASSERT_NE(nullptr, sn); ASSERT_EQ(primary, *sn); ASSERT_EQ(2U, sn->mirror_peer_uuids.size()); ASSERT_EQ(1U, sn->mirror_peer_uuids.count("peer1")); ASSERT_EQ(1U, sn->mirror_peer_uuids.count("peer2")); ASSERT_EQ(-ENOENT, mirror_image_snapshot_unlink_peer(&ioctx, oid, 1, "peer")); ASSERT_EQ(0, mirror_image_snapshot_unlink_peer(&ioctx, oid, 1, "peer1")); ASSERT_EQ(-ENOENT, mirror_image_snapshot_unlink_peer(&ioctx, oid, 1, "peer1")); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 1, &snap)); sn = std::get_if<cls::rbd::MirrorSnapshotNamespace>( &snap.snapshot_namespace); ASSERT_NE(nullptr, sn); ASSERT_EQ(1U, sn->mirror_peer_uuids.size()); ASSERT_EQ(1U, sn->mirror_peer_uuids.count("peer2")); ASSERT_EQ(0, mirror_image_snapshot_unlink_peer(&ioctx, oid, 1, "peer2")); ASSERT_EQ(-ENOENT, mirror_image_snapshot_unlink_peer(&ioctx, oid, 1, "peer2")); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 1, &snap)); sn = std::get_if<cls::rbd::MirrorSnapshotNamespace>( &snap.snapshot_namespace); ASSERT_NE(nullptr, sn); ASSERT_EQ(0U, sn->mirror_peer_uuids.size()); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 2, &snap)); auto nsn = std::get_if<cls::rbd::MirrorSnapshotNamespace>( &snap.snapshot_namespace); ASSERT_NE(nullptr, nsn); ASSERT_EQ(non_primary, *nsn); ASSERT_EQ(1U, nsn->mirror_peer_uuids.size()); ASSERT_EQ(1U, nsn->mirror_peer_uuids.count("peer1")); ASSERT_FALSE(nsn->complete); ASSERT_EQ(nsn->last_copied_object_number, 0); ASSERT_EQ(0, mirror_image_snapshot_set_copy_progress(&ioctx, oid, 2, true, 10)); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 2, &snap)); nsn = std::get_if<cls::rbd::MirrorSnapshotNamespace>( &snap.snapshot_namespace); ASSERT_NE(nullptr, nsn); ASSERT_TRUE(nsn->complete); ASSERT_EQ(nsn->last_copied_object_number, 10); ASSERT_EQ(0, mirror_image_snapshot_unlink_peer(&ioctx, oid, 2, "peer1")); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 1)); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 2)); } TEST_F(TestClsRbd, group_dir_list) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id1 = "cgid1"; string group_name1 = "cgname1"; string group_id2 = "cgid2"; string group_name2 = "cgname2"; ASSERT_EQ(0, group_dir_add(&ioctx, RBD_GROUP_DIRECTORY, group_name1, group_id1)); ASSERT_EQ(0, group_dir_add(&ioctx, RBD_GROUP_DIRECTORY, group_name2, group_id2)); map<string, string> cgs; ASSERT_EQ(0, group_dir_list(&ioctx, RBD_GROUP_DIRECTORY, "", 10, &cgs)); ASSERT_EQ(2U, cgs.size()); auto it = cgs.begin(); ASSERT_EQ(group_id1, it->second); ASSERT_EQ(group_name1, it->first); ++it; ASSERT_EQ(group_id2, it->second); ASSERT_EQ(group_name2, it->first); } void add_group_to_dir(librados::IoCtx ioctx, string group_id, string group_name) { ASSERT_EQ(0, group_dir_add(&ioctx, RBD_GROUP_DIRECTORY, group_name, group_id)); set<string> keys; ASSERT_EQ(0, ioctx.omap_get_keys(RBD_GROUP_DIRECTORY, "", 10, &keys)); ASSERT_EQ(2U, keys.size()); ASSERT_EQ("id_" + group_id, *keys.begin()); ASSERT_EQ("name_" + group_name, *keys.rbegin()); } TEST_F(TestClsRbd, group_dir_add) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_GROUP_DIRECTORY); string group_id = "cgid"; string group_name = "cgname"; add_group_to_dir(ioctx, group_id, group_name); } TEST_F(TestClsRbd, dir_add_already_existing) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_GROUP_DIRECTORY); string group_id = "cgidexisting"; string group_name = "cgnameexisting"; add_group_to_dir(ioctx, group_id, group_name); ASSERT_EQ(-EEXIST, group_dir_add(&ioctx, RBD_GROUP_DIRECTORY, group_name, group_id)); } TEST_F(TestClsRbd, group_dir_rename) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_GROUP_DIRECTORY); string group_id = "cgid"; string src_name = "cgnamesrc"; string dest_name = "cgnamedest"; add_group_to_dir(ioctx, group_id, src_name); ASSERT_EQ(0, group_dir_rename(&ioctx, RBD_GROUP_DIRECTORY, src_name, dest_name, group_id)); map<string, string> cgs; ASSERT_EQ(0, group_dir_list(&ioctx, RBD_GROUP_DIRECTORY, "", 10, &cgs)); ASSERT_EQ(1U, cgs.size()); auto it = cgs.begin(); ASSERT_EQ(group_id, it->second); ASSERT_EQ(dest_name, it->first); // destination group name existing ASSERT_EQ(-EEXIST, group_dir_rename(&ioctx, RBD_GROUP_DIRECTORY, dest_name, dest_name, group_id)); ASSERT_EQ(0, group_dir_remove(&ioctx, RBD_GROUP_DIRECTORY, dest_name, group_id)); // source group name missing ASSERT_EQ(-ENOENT, group_dir_rename(&ioctx, RBD_GROUP_DIRECTORY, dest_name, src_name, group_id)); } TEST_F(TestClsRbd, group_dir_remove) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_GROUP_DIRECTORY); string group_id = "cgidtodel"; string group_name = "cgnametodel"; add_group_to_dir(ioctx, group_id, group_name); ASSERT_EQ(0, group_dir_remove(&ioctx, RBD_GROUP_DIRECTORY, group_name, group_id)); set<string> keys; ASSERT_EQ(0, ioctx.omap_get_keys(RBD_GROUP_DIRECTORY, "", 10, &keys)); ASSERT_EQ(0U, keys.size()); } TEST_F(TestClsRbd, group_dir_remove_missing) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); ioctx.remove(RBD_GROUP_DIRECTORY); string group_id = "cgidtodelmissing"; string group_name = "cgnametodelmissing"; // These two lines ensure that RBD_GROUP_DIRECTORY exists. It's important for the // last two lines. add_group_to_dir(ioctx, group_id, group_name); ASSERT_EQ(0, group_dir_remove(&ioctx, RBD_GROUP_DIRECTORY, group_name, group_id)); // Removing missing ASSERT_EQ(-ENOENT, group_dir_remove(&ioctx, RBD_GROUP_DIRECTORY, group_name, group_id)); set<string> keys; ASSERT_EQ(0, ioctx.omap_get_keys(RBD_GROUP_DIRECTORY, "", 10, &keys)); ASSERT_EQ(0U, keys.size()); } void test_image_add(librados::IoCtx &ioctx, const string& group_id, const string& image_id, int64_t pool_id) { cls::rbd::GroupImageStatus st(image_id, pool_id, cls::rbd::GROUP_IMAGE_LINK_STATE_INCOMPLETE); ASSERT_EQ(0, group_image_set(&ioctx, group_id, st)); set<string> keys; ASSERT_EQ(0, ioctx.omap_get_keys(group_id, "", 10, &keys)); auto it = keys.begin(); ASSERT_EQ(1U, keys.size()); string image_key = cls::rbd::GroupImageSpec(image_id, pool_id).image_key(); ASSERT_EQ(image_key, *it); } TEST_F(TestClsRbd, group_image_add) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id"; ASSERT_EQ(0, ioctx.create(group_id, true)); int64_t pool_id = ioctx.get_id(); string image_id = "image_id"; test_image_add(ioctx, group_id, image_id, pool_id); } TEST_F(TestClsRbd, group_image_remove) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id1"; ASSERT_EQ(0, ioctx.create(group_id, true)); int64_t pool_id = ioctx.get_id(); string image_id = "image_id"; test_image_add(ioctx, group_id, image_id, pool_id); cls::rbd::GroupImageSpec spec(image_id, pool_id); ASSERT_EQ(0, group_image_remove(&ioctx, group_id, spec)); set<string> keys; ASSERT_EQ(0, ioctx.omap_get_keys(group_id, "", 10, &keys)); ASSERT_EQ(0U, keys.size()); } TEST_F(TestClsRbd, group_image_list) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id2"; ASSERT_EQ(0, ioctx.create(group_id, true)); int64_t pool_id = ioctx.get_id(); string image_id = "imageid"; // Image id shouldn't contain underscores test_image_add(ioctx, group_id, image_id, pool_id); vector<cls::rbd::GroupImageStatus> images; cls::rbd::GroupImageSpec empty_image_spec = cls::rbd::GroupImageSpec(); ASSERT_EQ(0, group_image_list(&ioctx, group_id, empty_image_spec, 1024, &images)); ASSERT_EQ(1U, images.size()); ASSERT_EQ(image_id, images[0].spec.image_id); ASSERT_EQ(pool_id, images[0].spec.pool_id); ASSERT_EQ(cls::rbd::GROUP_IMAGE_LINK_STATE_INCOMPLETE, images[0].state); cls::rbd::GroupImageStatus last_image = *images.rbegin(); ASSERT_EQ(0, group_image_list(&ioctx, group_id, last_image.spec, 1024, &images)); ASSERT_EQ(0U, images.size()); } TEST_F(TestClsRbd, group_image_clean) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id3"; ASSERT_EQ(0, ioctx.create(group_id, true)); int64_t pool_id = ioctx.get_id(); string image_id = "image_id"; test_image_add(ioctx, group_id, image_id, pool_id); cls::rbd::GroupImageStatus incomplete_st(image_id, pool_id, cls::rbd::GROUP_IMAGE_LINK_STATE_INCOMPLETE); ASSERT_EQ(0, group_image_set(&ioctx, group_id, incomplete_st)); // Set to dirty first in order to make sure that group_image_clean // actually does something. cls::rbd::GroupImageStatus attached_st(image_id, pool_id, cls::rbd::GROUP_IMAGE_LINK_STATE_ATTACHED); ASSERT_EQ(0, group_image_set(&ioctx, group_id, attached_st)); string image_key = cls::rbd::GroupImageSpec(image_id, pool_id).image_key(); map<string, bufferlist> vals; ASSERT_EQ(0, ioctx.omap_get_vals(group_id, "", 10, &vals)); cls::rbd::GroupImageLinkState ref_state; auto it = vals[image_key].cbegin(); decode(ref_state, it); ASSERT_EQ(cls::rbd::GROUP_IMAGE_LINK_STATE_ATTACHED, ref_state); } TEST_F(TestClsRbd, image_group_add) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); int64_t pool_id = ioctx.get_id(); string image_id = "imageid"; ASSERT_EQ(0, create_image(&ioctx, image_id, 2<<20, 0, RBD_FEATURE_LAYERING, image_id, -1)); string group_id = "group_id"; cls::rbd::GroupSpec spec(group_id, pool_id); ASSERT_EQ(0, image_group_add(&ioctx, image_id, spec)); map<string, bufferlist> vals; ASSERT_EQ(0, ioctx.omap_get_vals(image_id, "", RBD_GROUP_REF, 10, &vals)); cls::rbd::GroupSpec val_spec; auto it = vals[RBD_GROUP_REF].cbegin(); decode(val_spec, it); ASSERT_EQ(group_id, val_spec.group_id); ASSERT_EQ(pool_id, val_spec.pool_id); } TEST_F(TestClsRbd, image_group_remove) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); int64_t pool_id = ioctx.get_id(); string image_id = "image_id"; ASSERT_EQ(0, create_image(&ioctx, image_id, 2<<20, 0, RBD_FEATURE_LAYERING, image_id, -1)); string group_id = "group_id"; cls::rbd::GroupSpec spec(group_id, pool_id); ASSERT_EQ(0, image_group_add(&ioctx, image_id, spec)); // Add reference in order to make sure that image_group_remove actually // does something. ASSERT_EQ(0, image_group_remove(&ioctx, image_id, spec)); map<string, bufferlist> vals; ASSERT_EQ(0, ioctx.omap_get_vals(image_id, "", RBD_GROUP_REF, 10, &vals)); ASSERT_EQ(0U, vals.size()); } TEST_F(TestClsRbd, image_group_get) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); int64_t pool_id = ioctx.get_id(); string image_id = "imageidgroupspec"; ASSERT_EQ(0, create_image(&ioctx, image_id, 2<<20, 0, RBD_FEATURE_LAYERING, image_id, -1)); string group_id = "group_id_get_group_spec"; cls::rbd::GroupSpec spec_add(group_id, pool_id); ASSERT_EQ(0, image_group_add(&ioctx, image_id, spec_add)); cls::rbd::GroupSpec spec; ASSERT_EQ(0, image_group_get(&ioctx, image_id, &spec)); ASSERT_EQ(group_id, spec.group_id); ASSERT_EQ(pool_id, spec.pool_id); } TEST_F(TestClsRbd, group_snap_set_empty_name) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_add_empty_name"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id = "snap_id"; cls::rbd::GroupSnapshot snap = {snap_id, "", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(-EINVAL, group_snap_set(&ioctx, group_id, snap)); } TEST_F(TestClsRbd, group_snap_set_empty_id) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_add_empty_id"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id = "snap_id"; cls::rbd::GroupSnapshot snap = {"", "snap_name", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(-EINVAL, group_snap_set(&ioctx, group_id, snap)); } TEST_F(TestClsRbd, group_snap_set_duplicate_id) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_add_duplicate_id"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id = "snap_id"; cls::rbd::GroupSnapshot snap = {snap_id, "snap_name", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap)); cls::rbd::GroupSnapshot snap1 = {snap_id, "snap_name1", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(-EEXIST, group_snap_set(&ioctx, group_id, snap1)); } TEST_F(TestClsRbd, group_snap_set_duplicate_name) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_add_duplicate_name"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id1 = "snap_id1"; cls::rbd::GroupSnapshot snap = {snap_id1, "snap_name", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap)); string snap_id2 = "snap_id2"; cls::rbd::GroupSnapshot snap1 = {snap_id2, "snap_name", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(-EEXIST, group_snap_set(&ioctx, group_id, snap1)); } TEST_F(TestClsRbd, group_snap_set) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_add"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id = "snap_id"; cls::rbd::GroupSnapshot snap = {snap_id, "test_snapshot", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap)); set<string> keys; ASSERT_EQ(0, ioctx.omap_get_keys(group_id, "", 10, &keys)); auto it = keys.begin(); ASSERT_EQ(1U, keys.size()); string snap_key = "snapshot_" + stringify(snap.id); ASSERT_EQ(snap_key, *it); } TEST_F(TestClsRbd, group_snap_list) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_list"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id1 = "snap_id1"; cls::rbd::GroupSnapshot snap1 = {snap_id1, "test_snapshot1", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap1)); string snap_id2 = "snap_id2"; cls::rbd::GroupSnapshot snap2 = {snap_id2, "test_snapshot2", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap2)); std::vector<cls::rbd::GroupSnapshot> snapshots; ASSERT_EQ(0, group_snap_list(&ioctx, group_id, cls::rbd::GroupSnapshot(), 10, &snapshots)); ASSERT_EQ(2U, snapshots.size()); ASSERT_EQ(snap_id1, snapshots[0].id); ASSERT_EQ(snap_id2, snapshots[1].id); } static std::string hexify(int v) { ostringstream oss; oss << std::setw(8) << std::setfill('0') << std::hex << v; //oss << v; return oss.str(); } TEST_F(TestClsRbd, group_snap_list_max_return) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_list_max_return"; ASSERT_EQ(0, ioctx.create(group_id, true)); for (int i = 0; i < 15; ++i) { string snap_id = "snap_id" + hexify(i); cls::rbd::GroupSnapshot snap = {snap_id, "test_snapshot" + hexify(i), cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap)); } std::vector<cls::rbd::GroupSnapshot> snapshots; ASSERT_EQ(0, group_snap_list(&ioctx, group_id, cls::rbd::GroupSnapshot(), 10, &snapshots)); ASSERT_EQ(10U, snapshots.size()); for (int i = 0; i < 10; ++i) { string snap_id = "snap_id" + hexify(i); ASSERT_EQ(snap_id, snapshots[i].id); } cls::rbd::GroupSnapshot last_snap = *snapshots.rbegin(); ASSERT_EQ(0, group_snap_list(&ioctx, group_id, last_snap, 10, &snapshots)); ASSERT_EQ(5U, snapshots.size()); for (int i = 10; i < 15; ++i) { string snap_id = "snap_id" + hexify(i); ASSERT_EQ(snap_id, snapshots[i - 10].id); } } TEST_F(TestClsRbd, group_snap_list_max_read) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_list_max_read"; ASSERT_EQ(0, ioctx.create(group_id, true)); // 2 * RBD_MAX_KEYS_READ + a few for (int i = 0; i < 150; ++i) { string snap_id = "snap_id" + hexify(i); cls::rbd::GroupSnapshot snap = {snap_id, "test_snapshot" + hexify(i), cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap)); } std::vector<cls::rbd::GroupSnapshot> snapshots; ASSERT_EQ(0, group_snap_list(&ioctx, group_id, cls::rbd::GroupSnapshot(), 500, &snapshots)); ASSERT_EQ(150U, snapshots.size()); for (int i = 0; i < 150; ++i) { string snap_id = "snap_id" + hexify(i); ASSERT_EQ(snap_id, snapshots[i].id); } } TEST_F(TestClsRbd, group_snap_remove) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_remove"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id = "snap_id"; cls::rbd::GroupSnapshot snap = {snap_id, "test_snapshot", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap)); set<string> keys; ASSERT_EQ(0, ioctx.omap_get_keys(group_id, "", 10, &keys)); auto it = keys.begin(); ASSERT_EQ(1U, keys.size()); string snap_key = "snapshot_" + stringify(snap.id); ASSERT_EQ(snap_key, *it); // Remove the snapshot ASSERT_EQ(0, group_snap_remove(&ioctx, group_id, snap_id)); ASSERT_EQ(0, ioctx.omap_get_keys(group_id, "", 10, &keys)); ASSERT_EQ(0U, keys.size()); } TEST_F(TestClsRbd, group_snap_get_by_id) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string group_id = "group_id_snap_get_by_id"; ASSERT_EQ(0, ioctx.create(group_id, true)); string snap_id = "snap_id"; cls::rbd::GroupSnapshot snap = {snap_id, "test_snapshot", cls::rbd::GROUP_SNAPSHOT_STATE_INCOMPLETE}; ASSERT_EQ(0, group_snap_set(&ioctx, group_id, snap)); cls::rbd::GroupSnapshot received_snap; ASSERT_EQ(0, group_snap_get_by_id(&ioctx, group_id, snap_id, &received_snap)); ASSERT_EQ(snap.id, received_snap.id); ASSERT_EQ(snap.name, received_snap.name); ASSERT_EQ(snap.state, received_snap.state); } TEST_F(TestClsRbd, trash_methods) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string id = "123456789"; string id2 = "123456780"; std::map<string, cls::rbd::TrashImageSpec> entries; ASSERT_EQ(-ENOENT, trash_list(&ioctx, "", 1024, &entries)); utime_t now1 = ceph_clock_now(); utime_t now1_delay = now1; now1_delay += 380; cls::rbd::TrashImageSpec trash_spec(cls::rbd::TRASH_IMAGE_SOURCE_USER, "name", now1, now1_delay); ASSERT_EQ(0, trash_add(&ioctx, id, trash_spec)); utime_t now2 = ceph_clock_now(); utime_t now2_delay = now2; now2_delay += 480; cls::rbd::TrashImageSpec trash_spec2(cls::rbd::TRASH_IMAGE_SOURCE_MIRRORING, "name2", now2, now2_delay); ASSERT_EQ(-EEXIST, trash_add(&ioctx, id, trash_spec2)); ASSERT_EQ(0, trash_remove(&ioctx, id)); ASSERT_EQ(-ENOENT, trash_remove(&ioctx, id)); ASSERT_EQ(0, trash_list(&ioctx, "", 1024, &entries)); ASSERT_TRUE(entries.empty()); ASSERT_EQ(0, trash_add(&ioctx, id, trash_spec2)); ASSERT_EQ(0, trash_add(&ioctx, id2, trash_spec)); ASSERT_EQ(0, trash_list(&ioctx, "", 1, &entries)); ASSERT_TRUE(entries.find(id2) != entries.end()); ASSERT_EQ(cls::rbd::TRASH_IMAGE_SOURCE_USER, entries[id2].source); ASSERT_EQ(std::string("name"), entries[id2].name); ASSERT_EQ(now1, entries[id2].deletion_time); ASSERT_EQ(now1_delay, entries[id2].deferment_end_time); ASSERT_EQ(0, trash_list(&ioctx, id2, 1, &entries)); ASSERT_TRUE(entries.find(id) != entries.end()); ASSERT_EQ(cls::rbd::TRASH_IMAGE_SOURCE_MIRRORING, entries[id].source); ASSERT_EQ(std::string("name2"), entries[id].name); ASSERT_EQ(now2, entries[id].deletion_time); ASSERT_EQ(now2_delay, entries[id].deferment_end_time); ASSERT_EQ(0, trash_list(&ioctx, id, 1, &entries)); ASSERT_TRUE(entries.empty()); cls::rbd::TrashImageSpec spec_res1; ASSERT_EQ(0, trash_get(&ioctx, id, &spec_res1)); cls::rbd::TrashImageSpec spec_res2; ASSERT_EQ(0, trash_get(&ioctx, id2, &spec_res2)); ASSERT_EQ(spec_res1.name, "name2"); ASSERT_EQ(spec_res1.deletion_time, now2); ASSERT_EQ(spec_res1.deferment_end_time, now2_delay); ASSERT_EQ(spec_res2.name, "name"); ASSERT_EQ(spec_res2.deletion_time, now1); ASSERT_EQ(spec_res2.deferment_end_time, now1_delay); ioctx.close(); } TEST_F(TestClsRbd, op_features) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); uint64_t op_features = RBD_OPERATION_FEATURE_CLONE_PARENT; uint64_t mask = ~RBD_OPERATION_FEATURES_ALL; ASSERT_EQ(-EINVAL, op_features_set(&ioctx, oid, op_features, mask)); mask = 0; ASSERT_EQ(0, op_features_set(&ioctx, oid, op_features, mask)); uint64_t actual_op_features; ASSERT_EQ(0, op_features_get(&ioctx, oid, &actual_op_features)); ASSERT_EQ(0u, actual_op_features); uint64_t features; uint64_t incompatible_features; ASSERT_EQ(0, get_features(&ioctx, oid, true, &features, &incompatible_features)); ASSERT_EQ(0u, features); op_features = RBD_OPERATION_FEATURES_ALL; mask = RBD_OPERATION_FEATURES_ALL; ASSERT_EQ(0, op_features_set(&ioctx, oid, op_features, mask)); ASSERT_EQ(0, op_features_get(&ioctx, oid, &actual_op_features)); ASSERT_EQ(mask, actual_op_features); ASSERT_EQ(0, get_features(&ioctx, oid, true, &features, &incompatible_features)); ASSERT_EQ(RBD_FEATURE_OPERATIONS, features); op_features = 0; mask = RBD_OPERATION_FEATURE_CLONE_PARENT; ASSERT_EQ(0, op_features_set(&ioctx, oid, op_features, mask)); ASSERT_EQ(0, op_features_get(&ioctx, oid, &actual_op_features)); uint64_t expected_op_features = RBD_OPERATION_FEATURES_ALL & ~RBD_OPERATION_FEATURE_CLONE_PARENT; ASSERT_EQ(expected_op_features, actual_op_features); mask = RBD_OPERATION_FEATURES_ALL; ASSERT_EQ(0, op_features_set(&ioctx, oid, op_features, mask)); ASSERT_EQ(0, get_features(&ioctx, oid, true, &features, &incompatible_features)); ASSERT_EQ(0u, features); } TEST_F(TestClsRbd, clone_parent) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 123, "user_snap")); ASSERT_EQ(-ENOENT, child_attach(&ioctx, oid, 345, {})); ASSERT_EQ(-ENOENT, child_detach(&ioctx, oid, 123, {})); ASSERT_EQ(-ENOENT, child_detach(&ioctx, oid, 345, {})); ASSERT_EQ(0, child_attach(&ioctx, oid, 123, {1, "", "image1"})); ASSERT_EQ(-EEXIST, child_attach(&ioctx, oid, 123, {1, "", "image1"})); ASSERT_EQ(0, child_attach(&ioctx, oid, 123, {1, "", "image2"})); ASSERT_EQ(0, child_attach(&ioctx, oid, 123, {2, "", "image2"})); cls::rbd::SnapshotInfo snap; ASSERT_EQ(0, snapshot_get(&ioctx, oid, 123, &snap)); ASSERT_EQ(3U, snap.child_count); // op feature should have been enabled uint64_t op_features; uint64_t expected_op_features = RBD_OPERATION_FEATURE_CLONE_PARENT; ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & expected_op_features) == expected_op_features); // cannot attach to trashed snapshot librados::ObjectWriteOperation op1; ::librbd::cls_client::snapshot_add(&op1, 234, "trash_snap", cls::rbd::UserSnapshotNamespace()); ASSERT_EQ(0, ioctx.operate(oid, &op1)); librados::ObjectWriteOperation op2; ::librbd::cls_client::snapshot_trash_add(&op2, 234); ASSERT_EQ(0, ioctx.operate(oid, &op2)); ASSERT_EQ(-ENOENT, child_attach(&ioctx, oid, 234, {})); cls::rbd::ChildImageSpecs child_images; ASSERT_EQ(0, children_list(&ioctx, oid, 123, &child_images)); cls::rbd::ChildImageSpecs expected_child_images = { {1, "", "image1"}, {1, "", "image2"}, {2, "", "image2"}}; ASSERT_EQ(expected_child_images, child_images); // move snapshot to the trash ASSERT_EQ(-EBUSY, snapshot_remove(&ioctx, oid, 123)); librados::ObjectWriteOperation op3; ::librbd::cls_client::snapshot_trash_add(&op3, 123); ASSERT_EQ(0, ioctx.operate(oid, &op3)); ASSERT_EQ(0, snapshot_get(&ioctx, oid, 123, &snap)); ASSERT_EQ(cls::rbd::SNAPSHOT_NAMESPACE_TYPE_TRASH, cls::rbd::get_snap_namespace_type(snap.snapshot_namespace)); expected_op_features |= RBD_OPERATION_FEATURE_SNAP_TRASH; ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & expected_op_features) == expected_op_features); expected_child_images = {{1, "", "image1"}, {2, "", "image2"}}; ASSERT_EQ(0, child_detach(&ioctx, oid, 123, {1, "", "image2"})); ASSERT_EQ(0, children_list(&ioctx, oid, 123, &child_images)); ASSERT_EQ(expected_child_images, child_images); ASSERT_EQ(0, child_detach(&ioctx, oid, 123, {2, "", "image2"})); ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & expected_op_features) == expected_op_features); ASSERT_EQ(0, child_detach(&ioctx, oid, 123, {1, "", "image1"})); ASSERT_EQ(-ENOENT, children_list(&ioctx, oid, 123, &child_images)); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 234)); ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & expected_op_features) == RBD_OPERATION_FEATURE_SNAP_TRASH); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 123)); ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & expected_op_features) == 0); } TEST_F(TestClsRbd, clone_parent_ns) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 123, "user_snap")); ASSERT_EQ(0, child_attach(&ioctx, oid, 123, {1, "ns1", "image1"})); ASSERT_EQ(-EEXIST, child_attach(&ioctx, oid, 123, {1, "ns1", "image1"})); ASSERT_EQ(0, child_attach(&ioctx, oid, 123, {1, "ns2", "image1"})); cls::rbd::ChildImageSpecs child_images; ASSERT_EQ(0, children_list(&ioctx, oid, 123, &child_images)); cls::rbd::ChildImageSpecs expected_child_images = { {1, "ns1", "image1"}, {1, "ns2", "image1"}}; ASSERT_EQ(expected_child_images, child_images); expected_child_images = {{1, "ns1", "image1"}}; ASSERT_EQ(0, child_detach(&ioctx, oid, 123, {1, "ns2", "image1"})); ASSERT_EQ(0, children_list(&ioctx, oid, 123, &child_images)); ASSERT_EQ(expected_child_images, child_images); ASSERT_EQ(0, child_detach(&ioctx, oid, 123, {1, "ns1", "image1"})); ASSERT_EQ(-ENOENT, children_list(&ioctx, oid, 123, &child_images)); ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 123)); } TEST_F(TestClsRbd, clone_child) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, RBD_FEATURE_LAYERING | RBD_FEATURE_DEEP_FLATTEN, oid, -1)); ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 2}, 1)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 123, "user_snap1")); ASSERT_EQ(0, op_features_set(&ioctx, oid, RBD_OPERATION_FEATURE_CLONE_CHILD, RBD_OPERATION_FEATURE_CLONE_CHILD)); // clone child should be disabled due to deep flatten ASSERT_EQ(0, remove_parent(&ioctx, oid)); uint64_t op_features; ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & RBD_OPERATION_FEATURE_CLONE_CHILD) == 0ULL); ASSERT_EQ(0, set_features(&ioctx, oid, 0, RBD_FEATURE_DEEP_FLATTEN)); ASSERT_EQ(0, set_parent(&ioctx, oid, {1, "", "parent", 2}, 1)); ASSERT_EQ(0, snapshot_add(&ioctx, oid, 124, "user_snap2")); ASSERT_EQ(0, op_features_set(&ioctx, oid, RBD_OPERATION_FEATURE_CLONE_CHILD, RBD_OPERATION_FEATURE_CLONE_CHILD)); // clone child should remain enabled w/o deep flatten ASSERT_EQ(0, remove_parent(&ioctx, oid)); ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & RBD_OPERATION_FEATURE_CLONE_CHILD) == RBD_OPERATION_FEATURE_CLONE_CHILD); // ... but removing the last linked snapshot should disable it ASSERT_EQ(0, snapshot_remove(&ioctx, oid, 124)); ASSERT_EQ(0, op_features_get(&ioctx, oid, &op_features)); ASSERT_TRUE((op_features & RBD_OPERATION_FEATURE_CLONE_CHILD) == 0ULL); } TEST_F(TestClsRbd, namespace_methods) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string name1 = "123456789"; string name2 = "123456780"; std::list<std::string> entries; ASSERT_EQ(-ENOENT, namespace_list(&ioctx, "", 1024, &entries)); ASSERT_EQ(0, namespace_add(&ioctx, name1)); ASSERT_EQ(-EEXIST, namespace_add(&ioctx, name1)); ASSERT_EQ(0, namespace_remove(&ioctx, name1)); ASSERT_EQ(-ENOENT, namespace_remove(&ioctx, name1)); ASSERT_EQ(0, namespace_list(&ioctx, "", 1024, &entries)); ASSERT_TRUE(entries.empty()); ASSERT_EQ(0, namespace_add(&ioctx, name1)); ASSERT_EQ(0, namespace_add(&ioctx, name2)); ASSERT_EQ(0, namespace_list(&ioctx, "", 1, &entries)); ASSERT_EQ(1U, entries.size()); ASSERT_EQ(name2, entries.front()); ASSERT_EQ(0, namespace_list(&ioctx, name2, 1, &entries)); ASSERT_EQ(1U, entries.size()); ASSERT_EQ(name1, entries.front()); ASSERT_EQ(0, namespace_list(&ioctx, name1, 1, &entries)); ASSERT_TRUE(entries.empty()); } TEST_F(TestClsRbd, migration) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, create_image(&ioctx, oid, 0, 22, 0, oid, -1)); cls::rbd::MigrationSpec migration_spec(cls::rbd::MIGRATION_HEADER_TYPE_DST, -1, "", "", "", "{\"format\": \"raw\"}", {}, 0, false, cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, false, cls::rbd::MIGRATION_STATE_PREPARING, "123"); cls::rbd::MigrationSpec read_migration_spec; ASSERT_EQ(-EINVAL, migration_get(&ioctx, oid, &read_migration_spec)); uint64_t features; uint64_t incompatible_features; ASSERT_EQ(0, get_features(&ioctx, oid, CEPH_NOSNAP, &features, &incompatible_features)); ASSERT_EQ(0U, features); ASSERT_EQ(0, migration_set(&ioctx, oid, migration_spec)); ASSERT_EQ(0, migration_get(&ioctx, oid, &read_migration_spec)); ASSERT_EQ(migration_spec, read_migration_spec); ASSERT_EQ(0, get_features(&ioctx, oid, CEPH_NOSNAP, &features, &incompatible_features)); ASSERT_EQ(RBD_FEATURE_MIGRATING, features); ASSERT_EQ(-EEXIST, migration_set(&ioctx, oid, migration_spec)); migration_spec.state = cls::rbd::MIGRATION_STATE_PREPARED; migration_spec.state_description = "456"; ASSERT_EQ(0, migration_set_state(&ioctx, oid, migration_spec.state, migration_spec.state_description)); ASSERT_EQ(0, migration_get(&ioctx, oid, &read_migration_spec)); ASSERT_EQ(migration_spec, read_migration_spec); ASSERT_EQ(0, migration_remove(&ioctx, oid)); ASSERT_EQ(0, get_features(&ioctx, oid, CEPH_NOSNAP, &features, &incompatible_features)); ASSERT_EQ(0U, features); ASSERT_EQ(-EINVAL, migration_get(&ioctx, oid, &read_migration_spec)); ASSERT_EQ(-EINVAL, migration_set_state(&ioctx, oid, migration_spec.state, migration_spec.state_description)); migration_spec.header_type = cls::rbd::MIGRATION_HEADER_TYPE_SRC; ASSERT_EQ(0, migration_set(&ioctx, oid, migration_spec)); ASSERT_EQ(0, get_features(&ioctx, oid, CEPH_NOSNAP, &features, &incompatible_features)); ASSERT_EQ(RBD_FEATURE_MIGRATING, features); ASSERT_EQ(0, migration_remove(&ioctx, oid)); ASSERT_EQ(-EINVAL, migration_get(&ioctx, oid, &read_migration_spec)); ASSERT_EQ(0, get_features(&ioctx, oid, CEPH_NOSNAP, &features, &incompatible_features)); ASSERT_EQ(0U, features); ioctx.close(); } TEST_F(TestClsRbd, migration_v1) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); bufferlist header; header.append(RBD_HEADER_TEXT, sizeof(RBD_HEADER_TEXT)); string oid = get_temp_image_name(); ASSERT_EQ(0, ioctx.write(oid, header, header.length(), 0)); cls::rbd::MigrationSpec migration_spec(cls::rbd::MIGRATION_HEADER_TYPE_DST, 1, "name", "ns", "id", "", {}, 0, false, cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, false, cls::rbd::MIGRATION_STATE_PREPARING, "123"); cls::rbd::MigrationSpec read_migration_spec; ASSERT_EQ(-EINVAL, migration_get(&ioctx, oid, &read_migration_spec)); // v1 format image can only be migration source ASSERT_EQ(-EINVAL, migration_set(&ioctx, oid, migration_spec)); migration_spec.header_type = cls::rbd::MIGRATION_HEADER_TYPE_SRC; ASSERT_EQ(0, migration_set(&ioctx, oid, migration_spec)); ASSERT_EQ(0, migration_get(&ioctx, oid, &read_migration_spec)); ASSERT_EQ(migration_spec, read_migration_spec); header.clear(); ASSERT_EQ(static_cast<int>(sizeof(RBD_MIGRATE_HEADER_TEXT)), ioctx.read(oid, header, sizeof(RBD_MIGRATE_HEADER_TEXT), 0)); ASSERT_STREQ(RBD_MIGRATE_HEADER_TEXT, header.c_str()); ASSERT_EQ(-EEXIST, migration_set(&ioctx, oid, migration_spec)); migration_spec.state = cls::rbd::MIGRATION_STATE_PREPARED; migration_spec.state_description = "456"; ASSERT_EQ(0, migration_set_state(&ioctx, oid, migration_spec.state, migration_spec.state_description)); ASSERT_EQ(0, migration_get(&ioctx, oid, &read_migration_spec)); ASSERT_EQ(migration_spec, read_migration_spec); ASSERT_EQ(0, migration_remove(&ioctx, oid)); ASSERT_EQ(-EINVAL, migration_get(&ioctx, oid, &read_migration_spec)); ASSERT_EQ(-EINVAL, migration_set_state(&ioctx, oid, migration_spec.state, migration_spec.state_description)); header.clear(); ASSERT_EQ(static_cast<int>(sizeof(RBD_HEADER_TEXT)), ioctx.read(oid, header, sizeof(RBD_HEADER_TEXT), 0)); ASSERT_STREQ(RBD_HEADER_TEXT, header.c_str()); ioctx.close(); } TEST_F(TestClsRbd, assert_snapc_seq) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ASSERT_EQ(0, assert_snapc_seq(&ioctx, oid, 0, cls::rbd::ASSERT_SNAPC_SEQ_GT_SNAPSET_SEQ)); ASSERT_EQ(-ERANGE, assert_snapc_seq(&ioctx, oid, 0, cls::rbd::ASSERT_SNAPC_SEQ_LE_SNAPSET_SEQ)); ASSERT_EQ(0, ioctx.create(oid, true)); uint64_t snapc_seq = 0; ASSERT_EQ(-ERANGE, assert_snapc_seq(&ioctx, oid, snapc_seq, cls::rbd::ASSERT_SNAPC_SEQ_GT_SNAPSET_SEQ)); ASSERT_EQ(0, assert_snapc_seq(&ioctx, oid, snapc_seq, cls::rbd::ASSERT_SNAPC_SEQ_LE_SNAPSET_SEQ)); std::vector<uint64_t> snaps; snaps.push_back(CEPH_NOSNAP); ASSERT_EQ(0, ioctx.selfmanaged_snap_create(&snaps.back())); snapc_seq = snaps[0]; ASSERT_EQ(0, assert_snapc_seq(&ioctx, oid, snapc_seq, cls::rbd::ASSERT_SNAPC_SEQ_GT_SNAPSET_SEQ)); ASSERT_EQ(-ERANGE, assert_snapc_seq(&ioctx, oid, snapc_seq, cls::rbd::ASSERT_SNAPC_SEQ_LE_SNAPSET_SEQ)); ASSERT_EQ(0, ioctx.selfmanaged_snap_set_write_ctx(snaps[0], snaps)); bufferlist bl; bl.append("foo"); ASSERT_EQ(0, ioctx.write(oid, bl, bl.length(), 0)); ASSERT_EQ(-ERANGE, assert_snapc_seq(&ioctx, oid, snapc_seq, cls::rbd::ASSERT_SNAPC_SEQ_GT_SNAPSET_SEQ)); ASSERT_EQ(0, assert_snapc_seq(&ioctx, oid, snapc_seq, cls::rbd::ASSERT_SNAPC_SEQ_LE_SNAPSET_SEQ)); ASSERT_EQ(0, assert_snapc_seq(&ioctx, oid, snapc_seq + 1, cls::rbd::ASSERT_SNAPC_SEQ_GT_SNAPSET_SEQ)); ASSERT_EQ(-ERANGE, assert_snapc_seq(&ioctx, oid, snapc_seq + 1, cls::rbd::ASSERT_SNAPC_SEQ_LE_SNAPSET_SEQ)); ASSERT_EQ(0, ioctx.selfmanaged_snap_remove(snapc_seq)); } TEST_F(TestClsRbd, sparsify) { librados::IoCtx ioctx; ASSERT_EQ(0, _rados.ioctx_create(_pool_name.c_str(), ioctx)); string oid = get_temp_image_name(); ioctx.remove(oid); bool sparse_read_supported = is_sparse_read_supported(ioctx, oid); // test sparsify on a non-existent object ASSERT_EQ(-ENOENT, sparsify(&ioctx, oid, 16, false)); uint64_t size; ASSERT_EQ(-ENOENT, ioctx.stat(oid, &size, NULL)); ASSERT_EQ(-ENOENT, sparsify(&ioctx, oid, 16, true)); ASSERT_EQ(-ENOENT, ioctx.stat(oid, &size, NULL)); // test sparsify on an empty object ASSERT_EQ(0, ioctx.create(oid, true)); ASSERT_EQ(0, sparsify(&ioctx, oid, 16, false)); ASSERT_EQ(0, sparsify(&ioctx, oid, 16, true)); ASSERT_EQ(-ENOENT, sparsify(&ioctx, oid, 16, false)); // test sparsify on a zeroed object bufferlist inbl; inbl.append(std::string(4096, '\0')); ASSERT_EQ(0, ioctx.write(oid, inbl, inbl.length(), 0)); ASSERT_EQ(0, sparsify(&ioctx, oid, 16, false)); std::map<uint64_t, uint64_t> m; bufferlist outbl; std::map<uint64_t, uint64_t> expected_m; bufferlist expected_outbl; switch (int r = ioctx.sparse_read(oid, m, outbl, inbl.length(), 0); r) { case 0: expected_m = {}; ASSERT_EQ(expected_m, m); break; case 1: expected_m = {{0, 0}}; ASSERT_EQ(expected_m, m); break; default: FAIL() << r << " is odd"; } ASSERT_EQ(m, expected_m); ASSERT_EQ(0, sparsify(&ioctx, oid, 16, true)); ASSERT_EQ(-ENOENT, sparsify(&ioctx, oid, 16, true)); ASSERT_EQ(0, ioctx.write(oid, inbl, inbl.length(), 0)); ASSERT_EQ(0, sparsify(&ioctx, oid, 16, true)); ASSERT_EQ(-ENOENT, sparsify(&ioctx, oid, 16, true)); // test sparsify on an object with zeroes inbl.append(std::string(4096, '1')); inbl.append(std::string(4096, '\0')); inbl.append(std::string(4096, '2')); inbl.append(std::string(4096, '\0')); ASSERT_EQ(0, ioctx.write(oid, inbl, inbl.length(), 0)); // try to sparsify with sparse_size too large ASSERT_EQ(0, sparsify(&ioctx, oid, inbl.length(), true)); expected_m = {{0, inbl.length()}}; expected_outbl = inbl; ASSERT_EQ((int)expected_m.size(), ioctx.sparse_read(oid, m, outbl, inbl.length(), 0)); ASSERT_EQ(m, expected_m); ASSERT_TRUE(outbl.contents_equal(expected_outbl)); // sparsify with small sparse_size ASSERT_EQ(0, sparsify(&ioctx, oid, 16, true)); outbl.clear(); ASSERT_EQ((int)(inbl.length() - 4096), ioctx.read(oid, outbl, inbl.length(), 0)); outbl.append(std::string(4096, '\0')); ASSERT_TRUE(outbl.contents_equal(expected_outbl)); if (sparse_read_supported) { expected_m = {{4096 * 1, 4096}, {4096 * 3, 4096}}; expected_outbl.clear(); expected_outbl.append(std::string(4096, '1')); expected_outbl.append(std::string(4096, '2')); } else { expected_m = {{0, 4 * 4096}}; expected_outbl.clear(); expected_outbl.append(std::string(4096, '\0')); expected_outbl.append(std::string(4096, '1')); expected_outbl.append(std::string(4096, '\0')); expected_outbl.append(std::string(4096, '2')); } m.clear(); outbl.clear(); ASSERT_EQ((int)expected_m.size(), ioctx.sparse_read(oid, m, outbl, inbl.length(), 0)); ASSERT_EQ(m, expected_m); ASSERT_TRUE(outbl.contents_equal(expected_outbl)); // test it is the same after yet another sparsify ASSERT_EQ(0, sparsify(&ioctx, oid, 16, true)); m.clear(); outbl.clear(); ASSERT_EQ((int)expected_m.size(), ioctx.sparse_read(oid, m, outbl, inbl.length(), 0)); ASSERT_EQ(m, expected_m); ASSERT_TRUE(outbl.contents_equal(expected_outbl)); ASSERT_EQ(0, ioctx.remove(oid)); ioctx.close(); }
125,005
35.455526
106
cc
null
ceph-main/src/test/cls_refcount/test_cls_refcount.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "cls/refcount/cls_refcount_client.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include <errno.h> #include <string> #include <vector> using namespace std; static librados::ObjectWriteOperation *new_op() { return new librados::ObjectWriteOperation(); } TEST(cls_refcount, test_implicit) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; string oldtag = "oldtag"; string newtag = "newtag"; /* get on a missing object will fail */ librados::ObjectWriteOperation *op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(-ENOENT, ioctx.operate(oid, op)); delete op; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> refs; ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); string wildcard_tag; string tag = refs.front(); ASSERT_EQ(wildcard_tag, tag); /* take another reference, verify */ op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(2, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } ASSERT_EQ(1, (int)refs_map.count(wildcard_tag)); ASSERT_EQ(1, (int)refs_map.count(newtag)); delete op; /* drop reference to oldtag */ op = new_op(); cls_refcount_put(*op, oldtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(newtag, tag); delete op; /* drop oldtag reference again, op should return success, wouldn't do anything */ op = new_op(); cls_refcount_put(*op, oldtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(newtag, tag); delete op; /* drop newtag reference, make sure object removed */ op = new_op(); cls_refcount_put(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } /* * similar to test_implicit, just changes the order of the tags removal * see issue #20107 */ TEST(cls_refcount, test_implicit_idempotent) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; string oldtag = "oldtag"; string newtag = "newtag"; /* get on a missing object will fail */ librados::ObjectWriteOperation *op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(-ENOENT, ioctx.operate(oid, op)); delete op; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> refs; ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); string wildcard_tag; string tag = refs.front(); ASSERT_EQ(wildcard_tag, tag); /* take another reference, verify */ op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(2, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } ASSERT_EQ(1, (int)refs_map.count(wildcard_tag)); ASSERT_EQ(1, (int)refs_map.count(newtag)); delete op; /* drop reference to newtag */ op = new_op(); cls_refcount_put(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(string(), tag); delete op; /* drop newtag reference again, op should return success, wouldn't do anything */ op = new_op(); cls_refcount_put(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(string(), tag); delete op; /* drop oldtag reference, make sure object removed */ op = new_op(); cls_refcount_put(*op, oldtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } TEST(cls_refcount, test_put_snap) { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); bufferlist bl; bl.append("hi there"); ASSERT_EQ(0, ioctx.write("foo", bl, bl.length(), 0)); ASSERT_EQ(0, ioctx.snap_create("snapfoo")); ASSERT_EQ(0, ioctx.remove("foo")); sleep(2); ASSERT_EQ(0, ioctx.snap_create("snapbar")); librados::ObjectWriteOperation *op = new_op(); cls_refcount_put(*op, "notag", true); ASSERT_EQ(-ENOENT, ioctx.operate("foo", op)); EXPECT_EQ(0, ioctx.snap_remove("snapfoo")); EXPECT_EQ(0, ioctx.snap_remove("snapbar")); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } TEST(cls_refcount, test_explicit) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> refs; ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(0, (int)refs.size()); /* take first reference, verify */ string newtag = "newtag"; librados::ObjectWriteOperation *op = new_op(); cls_refcount_get(*op, newtag); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(1, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } ASSERT_EQ(1, (int)refs_map.count(newtag)); delete op; /* try to drop reference to unexisting tag */ string nosuchtag = "nosuchtag"; op = new_op(); cls_refcount_put(*op, nosuchtag); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(1, (int)refs.size()); string tag = refs.front(); ASSERT_EQ(newtag, tag); delete op; /* drop newtag reference, make sure object removed */ op = new_op(); cls_refcount_put(*op, newtag); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } TEST(cls_refcount, set) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> tag_refs, refs; #define TAGS_NUM 5 string tags[TAGS_NUM]; char buf[16]; for (int i = 0; i < TAGS_NUM; i++) { snprintf(buf, sizeof(buf), "tag%d", i); tags[i] = buf; tag_refs.push_back(tags[i]); } ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(0, (int)refs.size()); /* set reference list, verify */ librados::ObjectWriteOperation *op = new_op(); cls_refcount_set(*op, tag_refs); ASSERT_EQ(0, ioctx.operate(oid, op)); refs.clear(); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(TAGS_NUM, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } for (int i = 0; i < TAGS_NUM; i++) { ASSERT_EQ(1, (int)refs_map.count(tags[i])); } delete op; /* remove all refs */ for (int i = 0; i < TAGS_NUM; i++) { op = new_op(); cls_refcount_put(*op, tags[i]); ASSERT_EQ(0, ioctx.operate(oid, op)); delete op; } ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } TEST(cls_refcount, test_implicit_ec) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_ec_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; string oldtag = "oldtag"; string newtag = "newtag"; /* get on a missing object will fail */ librados::ObjectWriteOperation *op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(-ENOENT, ioctx.operate(oid, op)); delete op; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> refs; ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); string wildcard_tag; string tag = refs.front(); ASSERT_EQ(wildcard_tag, tag); /* take another reference, verify */ op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(2, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } ASSERT_EQ(1, (int)refs_map.count(wildcard_tag)); ASSERT_EQ(1, (int)refs_map.count(newtag)); delete op; /* drop reference to oldtag */ op = new_op(); cls_refcount_put(*op, oldtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(newtag, tag); delete op; /* drop oldtag reference again, op should return success, wouldn't do anything */ op = new_op(); cls_refcount_put(*op, oldtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(newtag, tag); delete op; /* drop newtag reference, make sure object removed */ op = new_op(); cls_refcount_put(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_ec_pool_pp(pool_name, rados)); } /* * similar to test_implicit, just changes the order of the tags removal * see issue #20107 */ TEST(cls_refcount, test_implicit_idempotent_ec) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_ec_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; string oldtag = "oldtag"; string newtag = "newtag"; /* get on a missing object will fail */ librados::ObjectWriteOperation *op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(-ENOENT, ioctx.operate(oid, op)); delete op; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> refs; ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); string wildcard_tag; string tag = refs.front(); ASSERT_EQ(wildcard_tag, tag); /* take another reference, verify */ op = new_op(); cls_refcount_get(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(2, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } ASSERT_EQ(1, (int)refs_map.count(wildcard_tag)); ASSERT_EQ(1, (int)refs_map.count(newtag)); delete op; /* drop reference to newtag */ op = new_op(); cls_refcount_put(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(string(), tag); delete op; /* drop newtag reference again, op should return success, wouldn't do anything */ op = new_op(); cls_refcount_put(*op, newtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs, true)); ASSERT_EQ(1, (int)refs.size()); tag = refs.front(); ASSERT_EQ(string(), tag); delete op; /* drop oldtag reference, make sure object removed */ op = new_op(); cls_refcount_put(*op, oldtag, true); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_ec_pool_pp(pool_name, rados)); } TEST(cls_refcount, test_put_snap_ec) { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_ec_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); bufferlist bl; bl.append("hi there"); ASSERT_EQ(0, ioctx.write("foo", bl, bl.length(), 0)); ASSERT_EQ(0, ioctx.snap_create("snapfoo")); ASSERT_EQ(0, ioctx.remove("foo")); sleep(2); ASSERT_EQ(0, ioctx.snap_create("snapbar")); librados::ObjectWriteOperation *op = new_op(); cls_refcount_put(*op, "notag", true); ASSERT_EQ(-ENOENT, ioctx.operate("foo", op)); EXPECT_EQ(0, ioctx.snap_remove("snapfoo")); EXPECT_EQ(0, ioctx.snap_remove("snapbar")); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_ec_pool_pp(pool_name, rados)); } TEST(cls_refcount, test_explicit_ec) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_ec_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> refs; ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(0, (int)refs.size()); /* take first reference, verify */ string newtag = "newtag"; librados::ObjectWriteOperation *op = new_op(); cls_refcount_get(*op, newtag); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(1, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } ASSERT_EQ(1, (int)refs_map.count(newtag)); delete op; /* try to drop reference to unexisting tag */ string nosuchtag = "nosuchtag"; op = new_op(); cls_refcount_put(*op, nosuchtag); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(1, (int)refs.size()); string tag = refs.front(); ASSERT_EQ(newtag, tag); delete op; /* drop newtag reference, make sure object removed */ op = new_op(); cls_refcount_put(*op, newtag); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); delete op; /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_ec_pool_pp(pool_name, rados)); } TEST(cls_refcount, set_ec) /* test refcount using implicit referencing of newly created objects */ { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_ec_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); /* read reference, should return a single wildcard entry */ list<string> tag_refs, refs; #define TAGS_NUM 5 string tags[TAGS_NUM]; char buf[16]; for (int i = 0; i < TAGS_NUM; i++) { snprintf(buf, sizeof(buf), "tag%d", i); tags[i] = buf; tag_refs.push_back(tags[i]); } ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(0, (int)refs.size()); /* set reference list, verify */ librados::ObjectWriteOperation *op = new_op(); cls_refcount_set(*op, tag_refs); ASSERT_EQ(0, ioctx.operate(oid, op)); refs.clear(); ASSERT_EQ(0, cls_refcount_read(ioctx, oid, &refs)); ASSERT_EQ(TAGS_NUM, (int)refs.size()); map<string, bool> refs_map; for (list<string>::iterator iter = refs.begin(); iter != refs.end(); ++iter) { refs_map[*iter] = true; } for (int i = 0; i < TAGS_NUM; i++) { ASSERT_EQ(1, (int)refs_map.count(tags[i])); } delete op; /* remove all refs */ for (int i = 0; i < TAGS_NUM; i++) { op = new_op(); cls_refcount_put(*op, tags[i]); ASSERT_EQ(0, ioctx.operate(oid, op)); delete op; } ASSERT_EQ(-ENOENT, ioctx.stat(oid, NULL, NULL)); /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_ec_pool_pp(pool_name, rados)); }
18,789
23.120668
119
cc
null
ceph-main/src/test/cls_rgw/test_cls_rgw.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "cls/rgw/cls_rgw_client.h" #include "cls/rgw/cls_rgw_ops.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include "global/global_context.h" #include "common/ceph_context.h" #include <errno.h> #include <string> #include <vector> #include <map> #include <set> using namespace std; using namespace librados; // creates a temporary pool and initializes an IoCtx shared by all tests class cls_rgw : public ::testing::Test { static librados::Rados rados; static std::string pool_name; protected: static librados::IoCtx ioctx; static void SetUpTestCase() { pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); } static void TearDownTestCase() { /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); } }; librados::Rados cls_rgw::rados; std::string cls_rgw::pool_name; librados::IoCtx cls_rgw::ioctx; string str_int(string s, int i) { char buf[32]; snprintf(buf, sizeof(buf), "-%d", i); s.append(buf); return s; } void test_stats(librados::IoCtx& ioctx, string& oid, RGWObjCategory category, uint64_t num_entries, uint64_t total_size) { map<int, struct rgw_cls_list_ret> results; map<int, string> oids; oids[0] = oid; ASSERT_EQ(0, CLSRGWIssueGetDirHeader(ioctx, oids, results, 8)()); uint64_t entries = 0; uint64_t size = 0; map<int, struct rgw_cls_list_ret>::iterator iter = results.begin(); for (; iter != results.end(); ++iter) { entries += (iter->second).dir.header.stats[category].num_entries; size += (iter->second).dir.header.stats[category].total_size; } ASSERT_EQ(total_size, size); ASSERT_EQ(num_entries, entries); } void index_prepare(librados::IoCtx& ioctx, string& oid, RGWModifyOp index_op, string& tag, const cls_rgw_obj_key& key, string& loc, uint16_t bi_flags = 0, bool log_op = true) { ObjectWriteOperation op; rgw_zone_set zones_trace; cls_rgw_bucket_prepare_op(op, index_op, tag, key, loc, log_op, bi_flags, zones_trace); ASSERT_EQ(0, ioctx.operate(oid, &op)); } void index_complete(librados::IoCtx& ioctx, string& oid, RGWModifyOp index_op, string& tag, int epoch, const cls_rgw_obj_key& key, rgw_bucket_dir_entry_meta& meta, uint16_t bi_flags = 0, bool log_op = true) { ObjectWriteOperation op; rgw_bucket_entry_ver ver; ver.pool = ioctx.get_id(); ver.epoch = epoch; meta.accounted_size = meta.size; cls_rgw_bucket_complete_op(op, index_op, tag, ver, key, meta, nullptr, log_op, bi_flags, nullptr); ASSERT_EQ(0, ioctx.operate(oid, &op)); if (!key.instance.empty()) { bufferlist olh_tag; olh_tag.append(tag); rgw_zone_set zone_set; ASSERT_EQ(0, cls_rgw_bucket_link_olh(ioctx, oid, key, olh_tag, false, tag, &meta, epoch, ceph::real_time{}, true, true, zone_set)); } } TEST_F(cls_rgw, index_basic) { string bucket_oid = str_int("bucket", 0); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); uint64_t epoch = 1; uint64_t obj_size = 1024; #define NUM_OBJS 10 for (int i = 0; i < NUM_OBJS; i++) { cls_rgw_obj_key obj = str_int("obj", i); string tag = str_int("tag", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, i, obj_size * i); rgw_bucket_dir_entry_meta meta; meta.category = RGWObjCategory::None; meta.size = obj_size; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, epoch, obj, meta); } test_stats(ioctx, bucket_oid, RGWObjCategory::None, NUM_OBJS, obj_size * NUM_OBJS); } TEST_F(cls_rgw, index_multiple_obj_writers) { string bucket_oid = str_int("bucket", 1); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); uint64_t obj_size = 1024; cls_rgw_obj_key obj = str_int("obj", 0); string loc = str_int("loc", 0); /* multi prepare on a single object */ for (int i = 0; i < NUM_OBJS; i++) { string tag = str_int("tag", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, 0, 0); } for (int i = NUM_OBJS; i > 0; i--) { string tag = str_int("tag", i - 1); rgw_bucket_dir_entry_meta meta; meta.category = RGWObjCategory::None; meta.size = obj_size * i; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, i, obj, meta); /* verify that object size doesn't change, as we went back with epoch */ test_stats(ioctx, bucket_oid, RGWObjCategory::None, 1, obj_size * NUM_OBJS); } } TEST_F(cls_rgw, index_remove_object) { string bucket_oid = str_int("bucket", 2); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); uint64_t obj_size = 1024; uint64_t total_size = 0; int epoch = 0; /* prepare multiple objects */ for (int i = 0; i < NUM_OBJS; i++) { cls_rgw_obj_key obj = str_int("obj", i); string tag = str_int("tag", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, i, total_size); rgw_bucket_dir_entry_meta meta; meta.category = RGWObjCategory::None; meta.size = i * obj_size; total_size += i * obj_size; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, ++epoch, obj, meta); test_stats(ioctx, bucket_oid, RGWObjCategory::None, i + 1, total_size); } int i = NUM_OBJS / 2; string tag_remove = "tag-rm"; string tag_modify = "tag-mod"; cls_rgw_obj_key obj = str_int("obj", i); string loc = str_int("loc", i); /* prepare both removal and modification on the same object */ index_prepare(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag_remove, obj, loc); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag_modify, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, NUM_OBJS, total_size); rgw_bucket_dir_entry_meta meta; /* complete object removal */ index_complete(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag_remove, ++epoch, obj, meta); /* verify stats correct */ total_size -= i * obj_size; test_stats(ioctx, bucket_oid, RGWObjCategory::None, NUM_OBJS - 1, total_size); meta.size = 512; meta.category = RGWObjCategory::None; /* complete object modification */ index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag_modify, ++epoch, obj, meta); /* verify stats correct */ total_size += meta.size; test_stats(ioctx, bucket_oid, RGWObjCategory::None, NUM_OBJS, total_size); /* prepare both removal and modification on the same object, this time we'll * first complete modification then remove*/ index_prepare(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag_remove, obj, loc); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag_modify, obj, loc); /* complete modification */ total_size -= meta.size; meta.size = i * obj_size * 2; meta.category = RGWObjCategory::None; /* complete object modification */ index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag_modify, ++epoch, obj, meta); /* verify stats correct */ total_size += meta.size; test_stats(ioctx, bucket_oid, RGWObjCategory::None, NUM_OBJS, total_size); /* complete object removal */ index_complete(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag_remove, ++epoch, obj, meta); /* verify stats correct */ total_size -= meta.size; test_stats(ioctx, bucket_oid, RGWObjCategory::None, NUM_OBJS - 1, total_size); } TEST_F(cls_rgw, index_suggest) { string bucket_oid = str_int("suggest", 1); { ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); } uint64_t total_size = 0; int epoch = 0; int num_objs = 100; uint64_t obj_size = 1024; /* create multiple objects */ for (int i = 0; i < num_objs; i++) { cls_rgw_obj_key obj = str_int("obj", i); string tag = str_int("tag", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, i, total_size); rgw_bucket_dir_entry_meta meta; meta.category = RGWObjCategory::None; meta.size = obj_size; total_size += meta.size; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, ++epoch, obj, meta); test_stats(ioctx, bucket_oid, RGWObjCategory::None, i + 1, total_size); } /* prepare (without completion) some of the objects */ for (int i = 0; i < num_objs; i += 2) { cls_rgw_obj_key obj = str_int("obj", i); string tag = str_int("tag-prepare", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, num_objs, total_size); } int actual_num_objs = num_objs; /* remove half of the objects */ for (int i = num_objs / 2; i < num_objs; i++) { cls_rgw_obj_key obj = str_int("obj", i); string tag = str_int("tag-rm", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, actual_num_objs, total_size); rgw_bucket_dir_entry_meta meta; index_complete(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag, ++epoch, obj, meta); total_size -= obj_size; actual_num_objs--; test_stats(ioctx, bucket_oid, RGWObjCategory::None, actual_num_objs, total_size); } bufferlist updates; for (int i = 0; i < num_objs; i += 2) { cls_rgw_obj_key obj = str_int("obj", i); string tag = str_int("tag-rm", i); string loc = str_int("loc", i); rgw_bucket_dir_entry dirent; dirent.key.name = obj.name; dirent.locator = loc; dirent.exists = (i < num_objs / 2); // we removed half the objects dirent.meta.size = 1024; dirent.meta.accounted_size = 1024; char suggest_op = (i < num_objs / 2 ? CEPH_RGW_UPDATE : CEPH_RGW_REMOVE); cls_rgw_encode_suggestion(suggest_op, dirent, updates); } map<int, string> bucket_objs; bucket_objs[0] = bucket_oid; int r = CLSRGWIssueSetTagTimeout(ioctx, bucket_objs, 8 /* max aio */, 1)(); ASSERT_EQ(0, r); sleep(1); /* suggest changes! */ { ObjectWriteOperation op; cls_rgw_suggest_changes(op, updates); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); } /* suggest changes twice! */ { ObjectWriteOperation op; cls_rgw_suggest_changes(op, updates); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); } test_stats(ioctx, bucket_oid, RGWObjCategory::None, num_objs / 2, total_size); } static void list_entries(librados::IoCtx& ioctx, const std::string& oid, uint32_t num_entries, std::map<int, rgw_cls_list_ret>& results) { std::map<int, std::string> oids = { {0, oid} }; cls_rgw_obj_key start_key; string empty_prefix; string empty_delimiter; ASSERT_EQ(0, CLSRGWIssueBucketList(ioctx, start_key, empty_prefix, empty_delimiter, num_entries, true, oids, results, 1)()); } TEST_F(cls_rgw, index_suggest_complete) { string bucket_oid = str_int("suggest", 2); { ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); } cls_rgw_obj_key obj = str_int("obj", 0); string tag = str_int("tag-prepare", 0); string loc = str_int("loc", 0); // prepare entry index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); // list entry before completion rgw_bucket_dir_entry dirent; { std::map<int, rgw_cls_list_ret> listing; list_entries(ioctx, bucket_oid, 1, listing); ASSERT_EQ(1, listing.size()); const auto& entries = listing.begin()->second.dir.m; ASSERT_EQ(1, entries.size()); dirent = entries.begin()->second; ASSERT_EQ(obj, dirent.key); } // complete entry { rgw_bucket_dir_entry_meta meta; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, 1, obj, meta); } // suggest removal of listed entry { bufferlist updates; cls_rgw_encode_suggestion(CEPH_RGW_REMOVE, dirent, updates); ObjectWriteOperation op; cls_rgw_suggest_changes(op, updates); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); } // list entry again, verify that suggested removal was not applied { std::map<int, rgw_cls_list_ret> listing; list_entries(ioctx, bucket_oid, 1, listing); ASSERT_EQ(1, listing.size()); const auto& entries = listing.begin()->second.dir.m; ASSERT_EQ(1, entries.size()); EXPECT_TRUE(entries.begin()->second.exists); } } /* * This case is used to test whether get_obj_vals will * return all validate utf8 objnames and filter out those * in BI_PREFIX_CHAR private namespace. */ TEST_F(cls_rgw, index_list) { string bucket_oid = str_int("bucket", 4); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); uint64_t epoch = 1; uint64_t obj_size = 1024; const int num_objs = 4; const string keys[num_objs] = { /* single byte utf8 character */ { static_cast<char>(0x41) }, /* double byte utf8 character */ { static_cast<char>(0xCF), static_cast<char>(0x8F) }, /* treble byte utf8 character */ { static_cast<char>(0xDF), static_cast<char>(0x8F), static_cast<char>(0x8F) }, /* quadruble byte utf8 character */ { static_cast<char>(0xF7), static_cast<char>(0x8F), static_cast<char>(0x8F), static_cast<char>(0x8F) }, }; for (int i = 0; i < num_objs; i++) { string obj = keys[i]; string tag = str_int("tag", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc, 0 /* bi_flags */, false /* log_op */); rgw_bucket_dir_entry_meta meta; meta.category = RGWObjCategory::None; meta.size = obj_size; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, epoch, obj, meta, 0 /* bi_flags */, false /* log_op */); } map<string, bufferlist> entries; /* insert 998 omap key starts with BI_PREFIX_CHAR, * so bucket list first time will get one key before 0x80 and one key after */ for (int i = 0; i < 998; ++i) { char buf[10]; snprintf(buf, sizeof(buf), "%c%s%d", 0x80, "1000_", i); entries.emplace(string{buf}, bufferlist{}); } ioctx.omap_set(bucket_oid, entries); test_stats(ioctx, bucket_oid, RGWObjCategory::None, num_objs, obj_size * num_objs); map<int, string> oids = { {0, bucket_oid} }; map<int, struct rgw_cls_list_ret> list_results; cls_rgw_obj_key start_key("", ""); string empty_prefix; string empty_delimiter; int r = CLSRGWIssueBucketList(ioctx, start_key, empty_prefix, empty_delimiter, 1000, true, oids, list_results, 1)(); ASSERT_EQ(r, 0); ASSERT_EQ(1u, list_results.size()); auto it = list_results.begin(); auto m = (it->second).dir.m; ASSERT_EQ(4u, m.size()); int i = 0; for(auto it2 = m.cbegin(); it2 != m.cend(); it2++, i++) { ASSERT_EQ(it2->first.compare(keys[i]), 0); } } /* * This case is used to test when bucket index list that includes a * delimiter can handle the first chunk ending in a delimiter. */ TEST_F(cls_rgw, index_list_delimited) { string bucket_oid = str_int("bucket", 7); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); uint64_t epoch = 1; uint64_t obj_size = 1024; const int file_num_objs = 5; const int dir_num_objs = 1005; std::vector<std::string> file_prefixes = { "a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u" }; std::vector<std::string> dir_prefixes = { "b/", "d/", "f/", "h/", "j/", "l/", "n/", "p/", "r/", "t/" }; rgw_bucket_dir_entry_meta meta; meta.category = RGWObjCategory::None; meta.size = obj_size; // create top-level files for (const auto& p : file_prefixes) { for (int i = 0; i < file_num_objs; i++) { string tag = str_int("tag", i); string loc = str_int("loc", i); const string obj = str_int(p, i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc, 0 /* bi_flags */, false /* log_op */); index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, epoch, obj, meta, 0 /* bi_flags */, false /* log_op */); } } // create large directories for (const auto& p : dir_prefixes) { for (int i = 0; i < dir_num_objs; i++) { string tag = str_int("tag", i); string loc = str_int("loc", i); const string obj = p + str_int("f", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc, 0 /* bi_flags */, false /* log_op */); index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, epoch, obj, meta, 0 /* bi_flags */, false /* log_op */); } } map<int, string> oids = { {0, bucket_oid} }; map<int, struct rgw_cls_list_ret> list_results; cls_rgw_obj_key start_key("", ""); const string empty_prefix; const string delimiter = "/"; int r = CLSRGWIssueBucketList(ioctx, start_key, empty_prefix, delimiter, 1000, true, oids, list_results, 1)(); ASSERT_EQ(r, 0); ASSERT_EQ(1u, list_results.size()) << "Because we only have one bucket index shard, we should " "only get one list_result."; auto it = list_results.begin(); auto id_entry_map = it->second.dir.m; bool truncated = it->second.is_truncated; // the cls code will make 4 tries to get 1000 entries; however // because each of the subdirectories is so large, each attempt will // only retrieve the first part of the subdirectory ASSERT_EQ(48u, id_entry_map.size()) << "We should get 40 top-level entries and the tops of 8 \"subdirectories\"."; ASSERT_EQ(true, truncated) << "We did not get all entries."; ASSERT_EQ("a-0", id_entry_map.cbegin()->first); ASSERT_EQ("p/", id_entry_map.crbegin()->first); // now let's get the rest of the entries list_results.clear(); cls_rgw_obj_key start_key2("p/", ""); r = CLSRGWIssueBucketList(ioctx, start_key2, empty_prefix, delimiter, 1000, true, oids, list_results, 1)(); ASSERT_EQ(r, 0); it = list_results.begin(); id_entry_map = it->second.dir.m; truncated = it->second.is_truncated; ASSERT_EQ(17u, id_entry_map.size()) << "We should get 15 top-level entries and the tops of 2 \"subdirectories\"."; ASSERT_EQ(false, truncated) << "We now have all entries."; ASSERT_EQ("q-0", id_entry_map.cbegin()->first); ASSERT_EQ("u-4", id_entry_map.crbegin()->first); } TEST_F(cls_rgw, bi_list) { string bucket_oid = str_int("bucket", 5); CephContext *cct = reinterpret_cast<CephContext *>(ioctx.cct()); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); const std::string empty_name_filter; uint64_t max = 10; std::list<rgw_cls_bi_entry> entries; bool is_truncated; std::string marker; int ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, max, &entries, &is_truncated); ASSERT_EQ(ret, 0); ASSERT_EQ(entries.size(), 0u) << "The listing of an empty bucket as 0 entries."; ASSERT_EQ(is_truncated, false) << "The listing of an empty bucket is not truncated."; uint64_t epoch = 1; uint64_t obj_size = 1024; const uint64_t num_objs = 35; for (uint64_t i = 0; i < num_objs; i++) { string obj = str_int(i % 4 ? "obj" : "об'єкт", i); string tag = str_int("tag", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc, RGW_BILOG_FLAG_VERSIONED_OP); rgw_bucket_dir_entry_meta meta; meta.category = RGWObjCategory::None; meta.size = obj_size; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, epoch, obj, meta, RGW_BILOG_FLAG_VERSIONED_OP); } ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, num_objs + 10, &entries, &is_truncated); ASSERT_EQ(ret, 0); if (is_truncated) { ASSERT_LT(entries.size(), num_objs); } else { ASSERT_EQ(entries.size(), num_objs); } uint64_t num_entries = 0; is_truncated = true; marker.clear(); while(is_truncated) { ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, max, &entries, &is_truncated); ASSERT_EQ(ret, 0); if (is_truncated) { ASSERT_LT(entries.size(), num_objs - num_entries); } else { ASSERT_EQ(entries.size(), num_objs - num_entries); } num_entries += entries.size(); marker = entries.back().idx; } // try with marker as final entry ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, max, &entries, &is_truncated); ASSERT_EQ(ret, 0); ASSERT_EQ(entries.size(), 0u); ASSERT_EQ(is_truncated, false); if (cct->_conf->osd_max_omap_entries_per_request < 15) { num_entries = 0; max = 15; is_truncated = true; marker.clear(); while(is_truncated) { ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, max, &entries, &is_truncated); ASSERT_EQ(ret, 0); if (is_truncated) { ASSERT_LT(entries.size(), num_objs - num_entries); } else { ASSERT_EQ(entries.size(), num_objs - num_entries); } num_entries += entries.size(); marker = entries.back().idx; } // try with marker as final entry ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, max, &entries, &is_truncated); ASSERT_EQ(ret, 0); ASSERT_EQ(entries.size(), 0u); ASSERT_EQ(is_truncated, false); } // test with name filters; pairs contain filter and expected number of elements returned const std::list<std::pair<const std::string,unsigned>> filters_results = { { str_int("obj", 9), 1 }, { str_int("об'єкт", 8), 1 }, { str_int("obj", 8), 0 } }; for (const auto& filter_result : filters_results) { is_truncated = true; entries.clear(); marker.clear(); ret = cls_rgw_bi_list(ioctx, bucket_oid, filter_result.first, marker, max, &entries, &is_truncated); ASSERT_EQ(ret, 0) << "bi list test with name filters should succeed"; ASSERT_EQ(entries.size(), filter_result.second) << "bi list test with filters should return the correct number of results"; ASSERT_EQ(is_truncated, false) << "bi list test with filters should return correct truncation indicator"; } // test whether combined segment count is correcgt is_truncated = false; entries.clear(); marker.clear(); ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, num_objs - 1, &entries, &is_truncated); ASSERT_EQ(ret, 0) << "combined segment count should succeed"; ASSERT_EQ(entries.size(), num_objs - 1) << "combined segment count should return the correct number of results"; ASSERT_EQ(is_truncated, true) << "combined segment count should return correct truncation indicator"; marker = entries.back().idx; // advance marker ret = cls_rgw_bi_list(ioctx, bucket_oid, empty_name_filter, marker, num_objs - 1, &entries, &is_truncated); ASSERT_EQ(ret, 0) << "combined segment count should succeed"; ASSERT_EQ(entries.size(), 1) << "combined segment count should return the correct number of results"; ASSERT_EQ(is_truncated, false) << "combined segment count should return correct truncation indicator"; } /* test garbage collection */ static void create_obj(cls_rgw_obj& obj, int i, int j) { char buf[32]; snprintf(buf, sizeof(buf), "-%d.%d", i, j); obj.pool = "pool"; obj.pool.append(buf); obj.key.name = "oid"; obj.key.name.append(buf); obj.loc = "loc"; obj.loc.append(buf); } static bool cmp_objs(cls_rgw_obj& obj1, cls_rgw_obj& obj2) { return (obj1.pool == obj2.pool) && (obj1.key == obj2.key) && (obj1.loc == obj2.loc); } TEST_F(cls_rgw, gc_set) { /* add chains */ string oid = "obj"; for (int i = 0; i < 10; i++) { char buf[32]; snprintf(buf, sizeof(buf), "chain-%d", i); string tag = buf; librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); op.create(false); // create object info.tag = tag; cls_rgw_gc_set_entry(op, 0, info); ASSERT_EQ(0, ioctx.operate(oid, &op)); } bool truncated; list<cls_rgw_gc_obj_info> entries; string marker; string next_marker; /* list chains, verify truncated */ ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 8, true, entries, &truncated, next_marker)); ASSERT_EQ(8, (int)entries.size()); ASSERT_EQ(1, truncated); entries.clear(); next_marker.clear(); /* list all chains, verify not truncated */ ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 10, true, entries, &truncated, next_marker)); ASSERT_EQ(10, (int)entries.size()); ASSERT_EQ(0, truncated); /* verify all chains are valid */ list<cls_rgw_gc_obj_info>::iterator iter = entries.begin(); for (int i = 0; i < 10; i++, ++iter) { cls_rgw_gc_obj_info& entry = *iter; /* create expected chain name */ char buf[32]; snprintf(buf, sizeof(buf), "chain-%d", i); string tag = buf; /* verify chain name as expected */ ASSERT_EQ(entry.tag, tag); /* verify expected num of objects in chain */ ASSERT_EQ(2, (int)entry.chain.objs.size()); list<cls_rgw_obj>::iterator oiter = entry.chain.objs.begin(); cls_rgw_obj obj1, obj2; /* create expected objects */ create_obj(obj1, i, 1); create_obj(obj2, i, 2); /* assign returned object names */ cls_rgw_obj& ret_obj1 = *oiter++; cls_rgw_obj& ret_obj2 = *oiter; /* verify objects are as expected */ ASSERT_EQ(1, (int)cmp_objs(obj1, ret_obj1)); ASSERT_EQ(1, (int)cmp_objs(obj2, ret_obj2)); } } TEST_F(cls_rgw, gc_list) { /* add chains */ string oid = "obj"; for (int i = 0; i < 10; i++) { char buf[32]; snprintf(buf, sizeof(buf), "chain-%d", i); string tag = buf; librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); op.create(false); // create object info.tag = tag; cls_rgw_gc_set_entry(op, 0, info); ASSERT_EQ(0, ioctx.operate(oid, &op)); } bool truncated; list<cls_rgw_gc_obj_info> entries; list<cls_rgw_gc_obj_info> entries2; string marker; string next_marker; /* list chains, verify truncated */ ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 8, true, entries, &truncated, next_marker)); ASSERT_EQ(8, (int)entries.size()); ASSERT_EQ(1, truncated); marker = next_marker; next_marker.clear(); ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 8, true, entries2, &truncated, next_marker)); ASSERT_EQ(2, (int)entries2.size()); ASSERT_EQ(0, truncated); entries.splice(entries.end(), entries2); /* verify all chains are valid */ list<cls_rgw_gc_obj_info>::iterator iter = entries.begin(); for (int i = 0; i < 10; i++, ++iter) { cls_rgw_gc_obj_info& entry = *iter; /* create expected chain name */ char buf[32]; snprintf(buf, sizeof(buf), "chain-%d", i); string tag = buf; /* verify chain name as expected */ ASSERT_EQ(entry.tag, tag); /* verify expected num of objects in chain */ ASSERT_EQ(2, (int)entry.chain.objs.size()); list<cls_rgw_obj>::iterator oiter = entry.chain.objs.begin(); cls_rgw_obj obj1, obj2; /* create expected objects */ create_obj(obj1, i, 1); create_obj(obj2, i, 2); /* assign returned object names */ cls_rgw_obj& ret_obj1 = *oiter++; cls_rgw_obj& ret_obj2 = *oiter; /* verify objects are as expected */ ASSERT_EQ(1, (int)cmp_objs(obj1, ret_obj1)); ASSERT_EQ(1, (int)cmp_objs(obj2, ret_obj2)); } } TEST_F(cls_rgw, gc_defer) { librados::IoCtx ioctx; librados::Rados rados; string gc_pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(gc_pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(gc_pool_name.c_str(), ioctx)); string oid = "obj"; string tag = "mychain"; librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; op.create(false); info.tag = tag; /* create chain */ cls_rgw_gc_set_entry(op, 0, info); ASSERT_EQ(0, ioctx.operate(oid, &op)); bool truncated; list<cls_rgw_gc_obj_info> entries; string marker; string next_marker; /* list chains, verify num entries as expected */ ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 1, true, entries, &truncated, next_marker)); ASSERT_EQ(1, (int)entries.size()); ASSERT_EQ(0, truncated); librados::ObjectWriteOperation op2; /* defer chain */ cls_rgw_gc_defer_entry(op2, 5, tag); ASSERT_EQ(0, ioctx.operate(oid, &op2)); entries.clear(); next_marker.clear(); /* verify list doesn't show deferred entry (this may fail if cluster is thrashing) */ ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 1, true, entries, &truncated, next_marker)); ASSERT_EQ(0, (int)entries.size()); ASSERT_EQ(0, truncated); /* wait enough */ sleep(5); next_marker.clear(); /* verify list shows deferred entry */ ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 1, true, entries, &truncated, next_marker)); ASSERT_EQ(1, (int)entries.size()); ASSERT_EQ(0, truncated); librados::ObjectWriteOperation op3; vector<string> tags; tags.push_back(tag); /* remove chain */ cls_rgw_gc_remove(op3, tags); ASSERT_EQ(0, ioctx.operate(oid, &op3)); entries.clear(); next_marker.clear(); /* verify entry was removed */ ASSERT_EQ(0, cls_rgw_gc_list(ioctx, oid, marker, 1, true, entries, &truncated, next_marker)); ASSERT_EQ(0, (int)entries.size()); ASSERT_EQ(0, truncated); /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(gc_pool_name, rados)); } auto populate_usage_log_info(std::string user, std::string payer, int total_usage_entries) { rgw_usage_log_info info; for (int i=0; i < total_usage_entries; i++){ auto bucket = str_int("bucket", i); info.entries.emplace_back(rgw_usage_log_entry(user, payer, bucket)); } return info; } auto gen_usage_log_info(std::string payer, std::string bucket, int total_usage_entries) { rgw_usage_log_info info; for (int i=0; i < total_usage_entries; i++){ auto user = str_int("user", i); info.entries.emplace_back(rgw_usage_log_entry(user, payer, bucket)); } return info; } TEST_F(cls_rgw, usage_basic) { string oid="usage.1"; string user="user1"; uint64_t start_epoch{0}, end_epoch{(uint64_t) -1}; int total_usage_entries = 512; uint64_t max_entries = 2000; string payer; auto info = populate_usage_log_info(user, payer, total_usage_entries); ObjectWriteOperation op; cls_rgw_usage_log_add(op, info); ASSERT_EQ(0, ioctx.operate(oid, &op)); string read_iter; map <rgw_user_bucket, rgw_usage_log_entry> usage, usage2; bool truncated; int ret = cls_rgw_usage_log_read(ioctx, oid, user, "", start_epoch, end_epoch, max_entries, read_iter, usage, &truncated); // read the entries, and see that we have all the added entries ASSERT_EQ(0, ret); ASSERT_FALSE(truncated); ASSERT_EQ(static_cast<uint64_t>(total_usage_entries), usage.size()); // delete and read to assert that we've deleted all the values ASSERT_EQ(0, cls_rgw_usage_log_trim(ioctx, oid, user, "", start_epoch, end_epoch)); ret = cls_rgw_usage_log_read(ioctx, oid, user, "", start_epoch, end_epoch, max_entries, read_iter, usage2, &truncated); ASSERT_EQ(0, ret); ASSERT_EQ(0u, usage2.size()); // add and read to assert that bucket option is valid for usage reading string bucket1 = "bucket-usage-1"; string bucket2 = "bucket-usage-2"; info = gen_usage_log_info(payer, bucket1, 100); cls_rgw_usage_log_add(op, info); ASSERT_EQ(0, ioctx.operate(oid, &op)); info = gen_usage_log_info(payer, bucket2, 100); cls_rgw_usage_log_add(op, info); ASSERT_EQ(0, ioctx.operate(oid, &op)); ret = cls_rgw_usage_log_read(ioctx, oid, "", bucket1, start_epoch, end_epoch, max_entries, read_iter, usage2, &truncated); ASSERT_EQ(0, ret); ASSERT_EQ(100u, usage2.size()); // delete and read to assert that bucket option is valid for usage trim ASSERT_EQ(0, cls_rgw_usage_log_trim(ioctx, oid, "", bucket1, start_epoch, end_epoch)); ret = cls_rgw_usage_log_read(ioctx, oid, "", bucket1, start_epoch, end_epoch, max_entries, read_iter, usage2, &truncated); ASSERT_EQ(0, ret); ASSERT_EQ(0u, usage2.size()); ASSERT_EQ(0, cls_rgw_usage_log_trim(ioctx, oid, "", bucket2, start_epoch, end_epoch)); } TEST_F(cls_rgw, usage_clear_no_obj) { string user="user1"; string oid="usage.10"; librados::ObjectWriteOperation op; cls_rgw_usage_log_clear(op); int ret = ioctx.operate(oid, &op); ASSERT_EQ(0, ret); } TEST_F(cls_rgw, usage_clear) { string user="user1"; string payer; string oid="usage.10"; librados::ObjectWriteOperation op; int max_entries=2000; auto info = populate_usage_log_info(user, payer, max_entries); cls_rgw_usage_log_add(op, info); ASSERT_EQ(0, ioctx.operate(oid, &op)); ObjectWriteOperation op2; cls_rgw_usage_log_clear(op2); int ret = ioctx.operate(oid, &op2); ASSERT_EQ(0, ret); map <rgw_user_bucket, rgw_usage_log_entry> usage; bool truncated; uint64_t start_epoch{0}, end_epoch{(uint64_t) -1}; string read_iter; ret = cls_rgw_usage_log_read(ioctx, oid, user, "", start_epoch, end_epoch, max_entries, read_iter, usage, &truncated); ASSERT_EQ(0, ret); ASSERT_EQ(0u, usage.size()); } static int bilog_list(librados::IoCtx& ioctx, const std::string& oid, cls_rgw_bi_log_list_ret *result) { int retcode = 0; librados::ObjectReadOperation op; cls_rgw_bilog_list(op, "", 128, result, &retcode); int ret = ioctx.operate(oid, &op, nullptr); if (ret < 0) { return ret; } return retcode; } static int bilog_trim(librados::IoCtx& ioctx, const std::string& oid, const std::string& start_marker, const std::string& end_marker) { librados::ObjectWriteOperation op; cls_rgw_bilog_trim(op, start_marker, end_marker); return ioctx.operate(oid, &op); } TEST_F(cls_rgw, bi_log_trim) { string bucket_oid = str_int("bucket", 6); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); // create 10 versioned entries. this generates instance and olh bi entries, // allowing us to check that bilog trim doesn't remove any of those for (int i = 0; i < 10; i++) { cls_rgw_obj_key obj{str_int("obj", i), "inst"}; string tag = str_int("tag", i); string loc = str_int("loc", i); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); rgw_bucket_dir_entry_meta meta; index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, 1, obj, meta); } // bi list { list<rgw_cls_bi_entry> entries; bool truncated{false}; ASSERT_EQ(0, cls_rgw_bi_list(ioctx, bucket_oid, "", "", 128, &entries, &truncated)); // prepare/complete/instance/olh entry for each EXPECT_EQ(40u, entries.size()); EXPECT_FALSE(truncated); } // bilog list vector<rgw_bi_log_entry> bilog1; { cls_rgw_bi_log_list_ret bilog; ASSERT_EQ(0, bilog_list(ioctx, bucket_oid, &bilog)); // complete/olh entry for each EXPECT_EQ(20u, bilog.entries.size()); bilog1.assign(std::make_move_iterator(bilog.entries.begin()), std::make_move_iterator(bilog.entries.end())); } // trim front of bilog { const std::string from = ""; const std::string to = bilog1[0].id; ASSERT_EQ(0, bilog_trim(ioctx, bucket_oid, from, to)); cls_rgw_bi_log_list_ret bilog; ASSERT_EQ(0, bilog_list(ioctx, bucket_oid, &bilog)); EXPECT_EQ(19u, bilog.entries.size()); EXPECT_EQ(bilog1[1].id, bilog.entries.begin()->id); ASSERT_EQ(-ENODATA, bilog_trim(ioctx, bucket_oid, from, to)); } // trim back of bilog { const std::string from = bilog1[18].id; const std::string to = "9"; ASSERT_EQ(0, bilog_trim(ioctx, bucket_oid, from, to)); cls_rgw_bi_log_list_ret bilog; ASSERT_EQ(0, bilog_list(ioctx, bucket_oid, &bilog)); EXPECT_EQ(18u, bilog.entries.size()); EXPECT_EQ(bilog1[18].id, bilog.entries.rbegin()->id); ASSERT_EQ(-ENODATA, bilog_trim(ioctx, bucket_oid, from, to)); } // trim middle of bilog { const std::string from = bilog1[13].id; const std::string to = bilog1[14].id; ASSERT_EQ(0, bilog_trim(ioctx, bucket_oid, from, to)); cls_rgw_bi_log_list_ret bilog; ASSERT_EQ(0, bilog_list(ioctx, bucket_oid, &bilog)); EXPECT_EQ(17u, bilog.entries.size()); ASSERT_EQ(-ENODATA, bilog_trim(ioctx, bucket_oid, from, to)); } // trim full bilog { const std::string from = ""; const std::string to = "9"; ASSERT_EQ(0, bilog_trim(ioctx, bucket_oid, from, to)); cls_rgw_bi_log_list_ret bilog; ASSERT_EQ(0, bilog_list(ioctx, bucket_oid, &bilog)); EXPECT_EQ(0u, bilog.entries.size()); ASSERT_EQ(-ENODATA, bilog_trim(ioctx, bucket_oid, from, to)); } // bi list should be the same { list<rgw_cls_bi_entry> entries; bool truncated{false}; ASSERT_EQ(0, cls_rgw_bi_list(ioctx, bucket_oid, "", "", 128, &entries, &truncated)); EXPECT_EQ(40u, entries.size()); EXPECT_FALSE(truncated); } } TEST_F(cls_rgw, index_racing_removes) { string bucket_oid = str_int("bucket", 8); ObjectWriteOperation op; cls_rgw_bucket_init_index(op); ASSERT_EQ(0, ioctx.operate(bucket_oid, &op)); int epoch = 0; rgw_bucket_dir_entry dirent; rgw_bucket_dir_entry_meta meta; // prepare/complete add for single object const cls_rgw_obj_key obj{"obj"}; std::string loc = "loc"; { std::string tag = "tag-add"; index_prepare(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, obj, loc); index_complete(ioctx, bucket_oid, CLS_RGW_OP_ADD, tag, ++epoch, obj, meta); test_stats(ioctx, bucket_oid, RGWObjCategory::None, 1, 0); } // list to verify no pending ops { std::map<int, rgw_cls_list_ret> results; list_entries(ioctx, bucket_oid, 1, results); ASSERT_EQ(1, results.size()); const auto& entries = results.begin()->second.dir.m; ASSERT_EQ(1, entries.size()); dirent = std::move(entries.begin()->second); ASSERT_EQ(obj, dirent.key); ASSERT_TRUE(dirent.exists); ASSERT_TRUE(dirent.pending_map.empty()); } // prepare three racing removals std::string tag1 = "tag-rm1"; std::string tag2 = "tag-rm2"; std::string tag3 = "tag-rm3"; index_prepare(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag1, obj, loc); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag2, obj, loc); index_prepare(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag3, obj, loc); test_stats(ioctx, bucket_oid, RGWObjCategory::None, 1, 0); // complete on tag2 index_complete(ioctx, bucket_oid, CLS_RGW_OP_DEL, tag2, ++epoch, obj, meta); { std::map<int, rgw_cls_list_ret> results; list_entries(ioctx, bucket_oid, 1, results); ASSERT_EQ(1, results.size()); const auto& entries = results.begin()->second.dir.m; ASSERT_EQ(1, entries.size()); dirent = std::move(entries.begin()->second); ASSERT_EQ(obj, dirent.key); ASSERT_FALSE(dirent.exists); ASSERT_FALSE(dirent.pending_map.empty()); } // cancel on tag1 index_complete(ioctx, bucket_oid, CLS_RGW_OP_CANCEL, tag1, ++epoch, obj, meta); { std::map<int, rgw_cls_list_ret> results; list_entries(ioctx, bucket_oid, 1, results); ASSERT_EQ(1, results.size()); const auto& entries = results.begin()->second.dir.m; ASSERT_EQ(1, entries.size()); dirent = std::move(entries.begin()->second); ASSERT_EQ(obj, dirent.key); ASSERT_FALSE(dirent.exists); ASSERT_FALSE(dirent.pending_map.empty()); } // final cancel on tag3 index_complete(ioctx, bucket_oid, CLS_RGW_OP_CANCEL, tag3, ++epoch, obj, meta); // verify that the key was removed { std::map<int, rgw_cls_list_ret> results; list_entries(ioctx, bucket_oid, 1, results); EXPECT_EQ(1, results.size()); const auto& entries = results.begin()->second.dir.m; ASSERT_EQ(0, entries.size()); } test_stats(ioctx, bucket_oid, RGWObjCategory::None, 0, 0); }
40,907
29.460164
120
cc
null
ceph-main/src/test/cls_rgw/test_cls_rgw_stats.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <vector> #include <boost/circular_buffer.hpp> #include <boost/intrusive/set.hpp> #include <gtest/gtest.h> #include "cls/rgw/cls_rgw_client.h" #include "common/debug.h" #include "common/dout.h" #include "common/errno.h" #include "common/random_string.h" #include "global/global_context.h" #include "test/librados/test_cxx.h" #define dout_subsys ceph_subsys_rgw #define dout_context g_ceph_context // simulation parameters: // total number of index operations to prepare constexpr size_t max_operations = 2048; // total number of object names. each operation chooses one at random constexpr size_t max_entries = 32; // maximum number of pending operations. once the limit is reached, the oldest // pending operation is finished before another can start constexpr size_t max_pending = 16; // object size is randomly distributed between 0 and 4M constexpr size_t max_object_size = 4*1024*1024; // multipart upload threshold constexpr size_t max_part_size = 1024*1024; // create/destroy a pool that's shared by all tests in the process struct RadosEnv : public ::testing::Environment { static std::optional<std::string> pool_name; public: static librados::Rados rados; static librados::IoCtx ioctx; void SetUp() override { // create pool std::string name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(name, rados)); pool_name = name; ASSERT_EQ(rados.ioctx_create(name.c_str(), ioctx), 0); } void TearDown() override { ioctx.close(); if (pool_name) { ASSERT_EQ(destroy_one_pool_pp(*pool_name, rados), 0); } } }; std::optional<std::string> RadosEnv::pool_name; librados::Rados RadosEnv::rados; librados::IoCtx RadosEnv::ioctx; auto *const rados_env = ::testing::AddGlobalTestEnvironment(new RadosEnv); std::ostream& operator<<(std::ostream& out, const rgw_bucket_category_stats& c) { return out << "{count=" << c.num_entries << " size=" << c.total_size << '}'; } // librados helpers rgw_bucket_entry_ver last_version(librados::IoCtx& ioctx) { rgw_bucket_entry_ver ver; ver.pool = ioctx.get_id(); ver.epoch = ioctx.get_last_version(); return ver; } int index_init(librados::IoCtx& ioctx, const std::string& oid) { librados::ObjectWriteOperation op; cls_rgw_bucket_init_index(op); return ioctx.operate(oid, &op); } int index_prepare(librados::IoCtx& ioctx, const std::string& oid, const cls_rgw_obj_key& key, const std::string& tag, RGWModifyOp type) { librados::ObjectWriteOperation op; const std::string loc; // empty constexpr bool log_op = false; constexpr int flags = 0; rgw_zone_set zones; cls_rgw_bucket_prepare_op(op, type, tag, key, loc, log_op, flags, zones); return ioctx.operate(oid, &op); } int index_complete(librados::IoCtx& ioctx, const std::string& oid, const cls_rgw_obj_key& key, const std::string& tag, RGWModifyOp type, const rgw_bucket_entry_ver& ver, const rgw_bucket_dir_entry_meta& meta, std::list<cls_rgw_obj_key>* remove_objs) { librados::ObjectWriteOperation op; constexpr bool log_op = false; constexpr int flags = 0; constexpr rgw_zone_set* zones = nullptr; cls_rgw_bucket_complete_op(op, type, tag, ver, key, meta, remove_objs, log_op, flags, zones); return ioctx.operate(oid, &op); } void read_stats(librados::IoCtx& ioctx, const std::string& oid, rgw_bucket_dir_stats& stats) { auto oids = std::map<int, std::string>{{0, oid}}; std::map<int, rgw_cls_list_ret> results; ASSERT_EQ(0, CLSRGWIssueGetDirHeader(ioctx, oids, results, 8)()); ASSERT_EQ(1, results.size()); stats = std::move(results.begin()->second.dir.header.stats); } static void account_entry(rgw_bucket_dir_stats& stats, const rgw_bucket_dir_entry_meta& meta) { rgw_bucket_category_stats& c = stats[meta.category]; c.num_entries++; c.total_size += meta.accounted_size; c.total_size_rounded += cls_rgw_get_rounded_size(meta.accounted_size); c.actual_size += meta.size; } static void unaccount_entry(rgw_bucket_dir_stats& stats, const rgw_bucket_dir_entry_meta& meta) { rgw_bucket_category_stats& c = stats[meta.category]; c.num_entries--; c.total_size -= meta.accounted_size; c.total_size_rounded -= cls_rgw_get_rounded_size(meta.accounted_size); c.actual_size -= meta.size; } // a map of cached dir entries representing the expected state of cls_rgw struct object : rgw_bucket_dir_entry, boost::intrusive::set_base_hook<> { explicit object(const cls_rgw_obj_key& key) { this->key = key; } }; struct object_key { using type = cls_rgw_obj_key; const type& operator()(const object& o) const { return o.key; } }; using object_map_base = boost::intrusive::set<object, boost::intrusive::key_of_value<object_key>>; struct object_map : object_map_base { ~object_map() { clear_and_dispose(std::default_delete<object>{}); } }; // models a bucket index operation, starting with cls_rgw_bucket_prepare_op(). // stores all of the state necessary to complete the operation, either with // cls_rgw_bucket_complete_op() or cls_rgw_suggest_changes(). uploads larger // than max_part_size are modeled as multipart uploads struct operation { RGWModifyOp type; cls_rgw_obj_key key; std::string tag; rgw_bucket_entry_ver ver; std::string upload_id; // empty unless multipart rgw_bucket_dir_entry_meta meta; }; class simulator { public: simulator(librados::IoCtx& ioctx, std::string oid) : ioctx(ioctx), oid(std::move(oid)), pending(max_pending) { // generate a set of object keys. each operation chooses one at random keys.reserve(max_entries); for (size_t i = 0; i < max_entries; i++) { keys.emplace_back(gen_rand_alphanumeric_upper(g_ceph_context, 12)); } } void run(); private: void start(); int try_start(const cls_rgw_obj_key& key, const std::string& tag); void finish(const operation& op); void complete(const operation& op, RGWModifyOp type); void suggest(const operation& op, char suggestion); int init_multipart(const operation& op); void complete_multipart(const operation& op); object_map::iterator find_or_create(const cls_rgw_obj_key& key); librados::IoCtx& ioctx; std::string oid; std::vector<cls_rgw_obj_key> keys; object_map objects; boost::circular_buffer<operation> pending; rgw_bucket_dir_stats stats; }; void simulator::run() { // init the bucket index object ASSERT_EQ(0, index_init(ioctx, oid)); // run the simulation for N steps for (size_t i = 0; i < max_operations; i++) { if (pending.full()) { // if we're at max_pending, finish the oldest operation auto& op = pending.front(); finish(op); pending.pop_front(); // verify bucket stats rgw_bucket_dir_stats stored_stats; read_stats(ioctx, oid, stored_stats); const rgw_bucket_dir_stats& expected_stats = stats; ASSERT_EQ(expected_stats, stored_stats); } // initiate the next operation start(); // verify bucket stats rgw_bucket_dir_stats stored_stats; read_stats(ioctx, oid, stored_stats); const rgw_bucket_dir_stats& expected_stats = stats; ASSERT_EQ(expected_stats, stored_stats); } } object_map::iterator simulator::find_or_create(const cls_rgw_obj_key& key) { object_map::insert_commit_data commit; auto result = objects.insert_check(key, std::less<cls_rgw_obj_key>{}, commit); if (result.second) { // inserting new entry auto p = new object(key); result.first = objects.insert_commit(*p, commit); } return result.first; } int simulator::try_start(const cls_rgw_obj_key& key, const std::string& tag) { // choose randomly betwen create and delete const auto type = static_cast<RGWModifyOp>( ceph::util::generate_random_number<size_t, size_t>(CLS_RGW_OP_ADD, CLS_RGW_OP_DEL)); auto op = operation{type, key, tag}; op.meta.category = RGWObjCategory::Main; op.meta.size = op.meta.accounted_size = ceph::util::generate_random_number(1, max_object_size); if (type == CLS_RGW_OP_ADD && op.meta.size > max_part_size) { // simulate multipart for uploads over the max_part_size threshold op.upload_id = gen_rand_alphanumeric_upper(g_ceph_context, 12); int r = init_multipart(op); if (r != 0) { derr << "> failed to prepare multipart upload key=" << key << " upload=" << op.upload_id << " tag=" << tag << " type=" << type << ": " << cpp_strerror(r) << dendl; return r; } dout(1) << "> prepared multipart upload key=" << key << " upload=" << op.upload_id << " tag=" << tag << " type=" << type << " size=" << op.meta.size << dendl; } else { // prepare operation int r = index_prepare(ioctx, oid, op.key, op.tag, op.type); if (r != 0) { derr << "> failed to prepare operation key=" << key << " tag=" << tag << " type=" << type << ": " << cpp_strerror(r) << dendl; return r; } dout(1) << "> prepared operation key=" << key << " tag=" << tag << " type=" << type << " size=" << op.meta.size << dendl; } op.ver = last_version(ioctx); ceph_assert(!pending.full()); pending.push_back(std::move(op)); return 0; } void simulator::start() { // choose a random object key const size_t index = ceph::util::generate_random_number(0, keys.size() - 1); const auto& key = keys[index]; // generate a random tag const auto tag = gen_rand_alphanumeric_upper(g_ceph_context, 12); // retry until success. failures don't count towards max_operations while (try_start(key, tag) != 0) ; } void simulator::finish(const operation& op) { if (op.type == CLS_RGW_OP_ADD && !op.upload_id.empty()) { // multipart uploads either complete or abort based on part uploads complete_multipart(op); return; } // complete most operations, but finish some with cancel or dir suggest constexpr int cancel_percent = 10; constexpr int suggest_update_percent = 10; constexpr int suggest_remove_percent = 10; int result = ceph::util::generate_random_number(0, 99); if (result < cancel_percent) { complete(op, CLS_RGW_OP_CANCEL); return; } result -= cancel_percent; if (result < suggest_update_percent) { suggest(op, CEPH_RGW_UPDATE); return; } result -= suggest_update_percent; if (result < suggest_remove_percent) { suggest(op, CEPH_RGW_REMOVE); return; } complete(op, op.type); } void simulator::complete(const operation& op, RGWModifyOp type) { int r = index_complete(ioctx, oid, op.key, op.tag, type, op.ver, op.meta, nullptr); if (r != 0) { derr << "< failed to complete operation key=" << op.key << " tag=" << op.tag << " type=" << op.type << " size=" << op.meta.size << ": " << cpp_strerror(r) << dendl; return; } if (type == CLS_RGW_OP_CANCEL) { dout(1) << "< canceled operation key=" << op.key << " tag=" << op.tag << " type=" << op.type << " size=" << op.meta.size << dendl; } else if (type == CLS_RGW_OP_ADD) { auto obj = find_or_create(op.key); if (obj->exists) { unaccount_entry(stats, obj->meta); } obj->exists = true; obj->meta = op.meta; account_entry(stats, obj->meta); dout(1) << "< completed write operation key=" << op.key << " tag=" << op.tag << " type=" << type << " size=" << op.meta.size << dendl; } else { ceph_assert(type == CLS_RGW_OP_DEL); auto obj = objects.find(op.key, std::less<cls_rgw_obj_key>{}); if (obj != objects.end()) { if (obj->exists) { unaccount_entry(stats, obj->meta); } objects.erase_and_dispose(obj, std::default_delete<object>{}); } dout(1) << "< completed delete operation key=" << op.key << " tag=" << op.tag << " type=" << type << dendl; } } void simulator::suggest(const operation& op, char suggestion) { // read and decode the current dir entry rgw_cls_bi_entry bi_entry; int r = cls_rgw_bi_get(ioctx, oid, BIIndexType::Plain, op.key, &bi_entry); if (r != 0) { derr << "< no bi entry to suggest for operation key=" << op.key << " tag=" << op.tag << " type=" << op.type << " size=" << op.meta.size << ": " << cpp_strerror(r) << dendl; return; } ASSERT_EQ(bi_entry.type, BIIndexType::Plain); rgw_bucket_dir_entry entry; auto p = bi_entry.data.cbegin(); ASSERT_NO_THROW(decode(entry, p)); ASSERT_EQ(entry.key, op.key); // clear pending info and write it back; this cancels those pending // operations (we'll see EINVAL when we try to complete them), but dir // suggest is ignored unless the pending_map is empty entry.pending_map.clear(); bi_entry.data.clear(); encode(entry, bi_entry.data); r = cls_rgw_bi_put(ioctx, oid, bi_entry); ASSERT_EQ(0, r); // now suggest changes for this entry entry.ver = last_version(ioctx); entry.exists = (suggestion == CEPH_RGW_UPDATE); entry.meta = op.meta; bufferlist update; cls_rgw_encode_suggestion(suggestion, entry, update); librados::ObjectWriteOperation write_op; cls_rgw_suggest_changes(write_op, update); r = ioctx.operate(oid, &write_op); if (r != 0) { derr << "< failed to suggest operation key=" << op.key << " tag=" << op.tag << " type=" << op.type << " size=" << op.meta.size << ": " << cpp_strerror(r) << dendl; return; } // update our cache accordingly if (suggestion == CEPH_RGW_UPDATE) { auto obj = find_or_create(op.key); if (obj->exists) { unaccount_entry(stats, obj->meta); } obj->exists = true; obj->meta = op.meta; account_entry(stats, obj->meta); dout(1) << "< suggested update operation key=" << op.key << " tag=" << op.tag << " type=" << op.type << " size=" << op.meta.size << dendl; } else { ceph_assert(suggestion == CEPH_RGW_REMOVE); auto obj = objects.find(op.key, std::less<cls_rgw_obj_key>{}); if (obj != objects.end()) { if (obj->exists) { unaccount_entry(stats, obj->meta); } objects.erase_and_dispose(obj, std::default_delete<object>{}); } dout(1) << "< suggested remove operation key=" << op.key << " tag=" << op.tag << " type=" << op.type << dendl; } } int simulator::init_multipart(const operation& op) { // create (not just prepare) the meta object const auto meta_key = cls_rgw_obj_key{ fmt::format("_multipart_{}.2~{}.meta", op.key.name, op.upload_id)}; const std::string empty_tag; // empty tag enables complete without prepare const rgw_bucket_entry_ver empty_ver; rgw_bucket_dir_entry_meta meta_meta; meta_meta.category = RGWObjCategory::MultiMeta; int r = index_complete(ioctx, oid, meta_key, empty_tag, CLS_RGW_OP_ADD, empty_ver, meta_meta, nullptr); if (r != 0) { derr << " < failed to create multipart meta key=" << meta_key << ": " << cpp_strerror(r) << dendl; return r; } else { // account for meta object auto obj = find_or_create(meta_key); if (obj->exists) { unaccount_entry(stats, obj->meta); } obj->exists = true; obj->meta = meta_meta; account_entry(stats, obj->meta); } // prepare part uploads std::list<cls_rgw_obj_key> remove_objs; size_t part_id = 0; size_t remaining = op.meta.size; while (remaining > max_part_size) { remaining -= max_part_size; const auto part_size = std::min(remaining, max_part_size); const auto part_key = cls_rgw_obj_key{ fmt::format("_multipart_{}.2~{}.{}", op.key.name, op.upload_id, part_id)}; part_id++; r = index_prepare(ioctx, oid, part_key, op.tag, op.type); if (r != 0) { // if part prepare fails, remove the meta object and remove_objs [[maybe_unused]] int ignored = index_complete(ioctx, oid, meta_key, empty_tag, CLS_RGW_OP_DEL, empty_ver, meta_meta, &remove_objs); derr << " > failed to prepare part key=" << part_key << " size=" << part_size << dendl; return r; // return the error from prepare } dout(1) << " > prepared part key=" << part_key << " size=" << part_size << dendl; remove_objs.push_back(part_key); } return 0; } void simulator::complete_multipart(const operation& op) { const std::string empty_tag; // empty tag enables complete without prepare const rgw_bucket_entry_ver empty_ver; // try to finish part uploads size_t part_id = 0; std::list<cls_rgw_obj_key> remove_objs; RGWModifyOp type = op.type; // OP_ADD, or OP_CANCEL for abort size_t remaining = op.meta.size; while (remaining > max_part_size) { remaining -= max_part_size; const auto part_size = std::min(remaining, max_part_size); const auto part_key = cls_rgw_obj_key{ fmt::format("_multipart_{}.2~{}.{}", op.key.name, op.upload_id, part_id)}; part_id++; // cancel 10% of part uploads (and abort the multipart upload) constexpr int cancel_percent = 10; const int result = ceph::util::generate_random_number(0, 99); if (result < cancel_percent) { type = CLS_RGW_OP_CANCEL; // abort multipart dout(1) << " < canceled part key=" << part_key << " size=" << part_size << dendl; } else { rgw_bucket_dir_entry_meta meta; meta.category = op.meta.category; meta.size = meta.accounted_size = part_size; int r = index_complete(ioctx, oid, part_key, op.tag, op.type, empty_ver, meta, nullptr); if (r != 0) { derr << " < failed to complete part key=" << part_key << " size=" << meta.size << ": " << cpp_strerror(r) << dendl; type = CLS_RGW_OP_CANCEL; // abort multipart } else { dout(1) << " < completed part key=" << part_key << " size=" << meta.size << dendl; // account for successful part upload auto obj = find_or_create(part_key); if (obj->exists) { unaccount_entry(stats, obj->meta); } obj->exists = true; obj->meta = meta; account_entry(stats, obj->meta); } } remove_objs.push_back(part_key); } // delete the multipart meta object const auto meta_key = cls_rgw_obj_key{ fmt::format("_multipart_{}.2~{}.meta", op.key.name, op.upload_id)}; rgw_bucket_dir_entry_meta meta_meta; meta_meta.category = RGWObjCategory::MultiMeta; int r = index_complete(ioctx, oid, meta_key, empty_tag, CLS_RGW_OP_DEL, empty_ver, meta_meta, nullptr); if (r != 0) { derr << " < failed to remove multipart meta key=" << meta_key << ": " << cpp_strerror(r) << dendl; } else { // unaccount for meta object auto obj = objects.find(meta_key, std::less<cls_rgw_obj_key>{}); if (obj != objects.end()) { if (obj->exists) { unaccount_entry(stats, obj->meta); } objects.erase_and_dispose(obj, std::default_delete<object>{}); } } // create or cancel the head object r = index_complete(ioctx, oid, op.key, empty_tag, type, empty_ver, op.meta, &remove_objs); if (r != 0) { derr << "< failed to complete multipart upload key=" << op.key << " upload=" << op.upload_id << " tag=" << op.tag << " type=" << type << " size=" << op.meta.size << ": " << cpp_strerror(r) << dendl; return; } if (type == CLS_RGW_OP_ADD) { dout(1) << "< completed multipart upload key=" << op.key << " upload=" << op.upload_id << " tag=" << op.tag << " type=" << op.type << " size=" << op.meta.size << dendl; // account for head stats auto obj = find_or_create(op.key); if (obj->exists) { unaccount_entry(stats, obj->meta); } obj->exists = true; obj->meta = op.meta; account_entry(stats, obj->meta); } else { dout(1) << "< canceled multipart upload key=" << op.key << " upload=" << op.upload_id << " tag=" << op.tag << " type=" << op.type << " size=" << op.meta.size << dendl; } // unaccount for remove_objs for (const auto& part_key : remove_objs) { auto obj = objects.find(part_key, std::less<cls_rgw_obj_key>{}); if (obj != objects.end()) { if (obj->exists) { unaccount_entry(stats, obj->meta); } objects.erase_and_dispose(obj, std::default_delete<object>{}); } } } TEST(cls_rgw_stats, simulate) { const char* bucket_oid = __func__; auto sim = simulator{RadosEnv::ioctx, bucket_oid}; sim.run(); }
20,798
31.146832
81
cc
null
ceph-main/src/test/cls_rgw_gc/test_cls_rgw_gc.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "cls/rgw/cls_rgw_types.h" #include "cls/rgw_gc/cls_rgw_gc_client.h" #include "cls/rgw_gc/cls_rgw_gc_ops.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include "global/global_context.h" #include <errno.h> #include <string> #include <vector> #include <map> #include <set> using namespace std; using namespace librados; librados::Rados rados; librados::IoCtx ioctx; string pool_name; /* must be the first test! */ TEST(cls_rgw_gc, init) { pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); } string str_int(string s, int i) { char buf[32]; snprintf(buf, sizeof(buf), "-%d", i); s.append(buf); return s; } /* test garbage collection */ static void create_obj(cls_rgw_obj& obj, int i, int j) { char buf[32]; snprintf(buf, sizeof(buf), "-%d.%d", i, j); obj.pool = "pool"; obj.pool.append(buf); obj.key.name = "oid"; obj.key.name.append(buf); obj.loc = "loc"; obj.loc.append(buf); } TEST(cls_rgw_gc, gc_queue_ops1) { //Testing queue ops when data size is NOT a multiple of queue size string queue_name = "my-queue"; uint64_t queue_size = 322, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(queue_size, size); //Test enqueue for (int i = 0; i < 2; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 0, info); if (i == 1) { ASSERT_EQ(-ENOSPC, ioctx.operate(queue_name, &op)); } else { ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } } //Test remove queue entries librados::ObjectWriteOperation remove_op; string marker1; uint64_t num_entries = 1; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); //Test enqueue again for (int i = 0; i < 1; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 0, info); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } //Test list queue list<cls_rgw_gc_obj_info> list_info1; string marker, next_marker; uint64_t max = 1; bool expired_only = false, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(1, list_info1.size()); for (auto it : list_info1) { std::cerr << "[ ] list info tag = " << it.tag << std::endl; ASSERT_EQ("chain-0", it.tag); } } TEST(cls_rgw_gc, gc_queue_ops2) { //Testing list queue string queue_name = "my-second-queue"; uint64_t queue_size = 334, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); //Test list queue, when queue is empty list<cls_rgw_gc_obj_info> list_info; string marker1, next_marker1; uint64_t max1 = 2; bool expired_only1 = false, truncated1; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker1, max1, expired_only1, list_info, &truncated1, next_marker1); ASSERT_EQ(0, list_info.size()); //Test enqueue for (int i = 0; i < 3; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 0, info); if (i == 2) { ASSERT_EQ(-ENOSPC, ioctx.operate(queue_name, &op)); } else { ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } } //Test list queue list<cls_rgw_gc_obj_info> list_info1, list_info2, list_info3; string marker, next_marker; uint64_t max = 2; bool expired_only = false, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(2, list_info1.size()); int i = 0; for (auto it : list_info1) { string tag = "chain-" + to_string(i); ASSERT_EQ(tag, it.tag); i++; } max = 1; truncated = false; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info2, &truncated, next_marker); auto it = list_info2.front(); ASSERT_EQ(1, list_info2.size()); ASSERT_EQ(true, truncated); ASSERT_EQ("chain-0", it.tag); std::cerr << "[ ] next_marker is: = " << next_marker << std::endl; marker = next_marker; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info3, &truncated, next_marker); it = list_info3.front(); ASSERT_EQ(1, list_info3.size()); ASSERT_EQ(false, truncated); ASSERT_EQ("chain-1", it.tag); } #if 0 // TODO: fix or remove defer_gc() TEST(cls_rgw_gc, gc_queue_ops3) { //Testing remove queue entries string queue_name = "my-third-queue"; uint64_t queue_size = 501, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); //Test remove queue, when queue is empty librados::ObjectWriteOperation remove_op; string marker1; uint64_t num_entries = 2; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); cls_rgw_gc_obj_info defer_info; //Test enqueue for (int i = 0; i < 2; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 5, info); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); if (i == 0) defer_info = info; } //Test defer entry for 1st element librados::ObjectWriteOperation defer_op; cls_rgw_gc_queue_defer_entry(defer_op, 10, defer_info); ASSERT_EQ(0, ioctx.operate(queue_name, &defer_op)); //Test list queue list<cls_rgw_gc_obj_info> list_info1, list_info2; string marker, next_marker; uint64_t max = 2; bool expired_only = false, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(2, list_info1.size()); int i = 0; for (auto it : list_info1) { std::cerr << "[ ] list info tag = " << it.tag << std::endl; if (i == 0) { ASSERT_EQ("chain-1", it.tag); } if (i == 1) { ASSERT_EQ("chain-0", it.tag); } i++; } //Test remove entries num_entries = 2; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); //Test list queue again cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info2, &truncated, next_marker); ASSERT_EQ(0, list_info2.size()); } TEST(cls_rgw_gc, gc_queue_ops4) { //Testing remove queue entries string queue_name = "my-fourth-queue"; uint64_t queue_size = 501, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); //Test remove queue, when queue is empty librados::ObjectWriteOperation remove_op; string marker1; uint64_t num_entries = 2; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); cls_rgw_gc_obj_info defer_info; //Test enqueue for (int i = 0; i < 2; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 5, info); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); defer_info = info; } //Test defer entry for last element librados::ObjectWriteOperation defer_op; cls_rgw_gc_queue_defer_entry(defer_op, 10, defer_info); ASSERT_EQ(0, ioctx.operate(queue_name, &defer_op)); //Test list queue list<cls_rgw_gc_obj_info> list_info1, list_info2; string marker, next_marker; uint64_t max = 2; bool expired_only = false, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(2, list_info1.size()); int i = 0; for (auto it : list_info1) { string tag = "chain-" + to_string(i); ASSERT_EQ(tag, it.tag); i++; } //Test remove entries num_entries = 2; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); //Test list queue again cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info2, &truncated, next_marker); ASSERT_EQ(0, list_info2.size()); } #endif // defer_gc() disabled TEST(cls_rgw_gc, gc_queue_ops5) { //Testing remove queue entries string queue_name = "my-fifth-queue"; uint64_t queue_size = 501, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); //Test enqueue for (int i = 0; i < 3; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; if (i == 2) { cls_rgw_gc_queue_enqueue(op, 300, info); } else { cls_rgw_gc_queue_enqueue(op, 0, info); } ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } //Test list queue for expired entries only list<cls_rgw_gc_obj_info> list_info1, list_info2; string marker, next_marker, marker1; uint64_t max = 10; bool expired_only = true, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(2, list_info1.size()); int i = 0; for (auto it : list_info1) { string tag = "chain-" + to_string(i); ASSERT_EQ(tag, it.tag); i++; } //Test remove entries librados::ObjectWriteOperation remove_op; auto num_entries = list_info1.size(); cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); //Test list queue again for all entries expired_only = false; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info2, &truncated, next_marker); ASSERT_EQ(1, list_info2.size()); } TEST(cls_rgw_gc, gc_queue_ops6) { //Testing list queue, when data size is split at the end of the queue string queue_name = "my-sixth-queue"; uint64_t queue_size = 341, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); //Test enqueue for (int i = 0; i < 2; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 0, info); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } //Remove one element from queue librados::ObjectWriteOperation remove_op; string marker1; uint64_t num_entries = 1; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); //Enqueue one more element librados::ObjectWriteOperation enq_op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, 2, 1); create_obj(obj2, 2, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = "chain-2"; cls_rgw_gc_queue_enqueue(enq_op, 0, info); ASSERT_EQ(0, ioctx.operate(queue_name, &enq_op)); //Test list queue list<cls_rgw_gc_obj_info> list_info1, list_info2, list_info3; string marker, next_marker; uint64_t max = 2; bool expired_only = false, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(2, list_info1.size()); int i = 1; for (auto it : list_info1) { string tag = "chain-" + to_string(i); ASSERT_EQ(tag, it.tag); i++; } } TEST(cls_rgw_gc, gc_queue_ops7) { //Testing list queue, when data size is written at the end of queue and data is written after wrap around string queue_name = "my-seventh-queue"; uint64_t queue_size = 342, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); //Test enqueue for (int i = 0; i < 2; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 0, info); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } //Remove one element from queue librados::ObjectWriteOperation remove_op; string marker1; uint64_t num_entries = 1; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); //Enqueue one more element librados::ObjectWriteOperation enq_op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, 2, 1); create_obj(obj2, 2, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = "chain-2"; cls_rgw_gc_queue_enqueue(enq_op, 0, info); ASSERT_EQ(0, ioctx.operate(queue_name, &enq_op)); //Test list queue list<cls_rgw_gc_obj_info> list_info1, list_info2, list_info3; string marker, next_marker; uint64_t max = 2; bool expired_only = false, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(2, list_info1.size()); int i = 1; for (auto it : list_info1) { string tag = "chain-" + to_string(i); ASSERT_EQ(tag, it.tag); i++; } } TEST(cls_rgw_gc, gc_queue_ops8) { //Testing list queue, when data is split at the end of the queue string queue_name = "my-eighth-queue"; uint64_t queue_size = 344, num_urgent_data_entries = 10; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); //Test enqueue for (int i = 0; i < 2; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 0, info); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); } //Remove one element from queue librados::ObjectWriteOperation remove_op; string marker1; uint64_t num_entries = 1; cls_rgw_gc_queue_remove_entries(remove_op, num_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &remove_op)); //Enqueue one more element librados::ObjectWriteOperation enq_op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, 2, 1); create_obj(obj2, 2, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = "chain-2"; cls_rgw_gc_queue_enqueue(enq_op, 0, info); ASSERT_EQ(0, ioctx.operate(queue_name, &enq_op)); //Test list queue list<cls_rgw_gc_obj_info> list_info1, list_info2, list_info3; string marker, next_marker; uint64_t max = 2; bool expired_only = false, truncated; cls_rgw_gc_queue_list_entries(ioctx, queue_name, marker, max, expired_only, list_info1, &truncated, next_marker); ASSERT_EQ(2, list_info1.size()); int i = 1; for (auto it : list_info1) { string tag = "chain-" + to_string(i); ASSERT_EQ(tag, it.tag); i++; } } TEST(cls_rgw_gc, gc_queue_ops9) { //Testing remove queue entries string queue_name = "my-ninth-queue"; uint64_t queue_size = 668, num_urgent_data_entries = 1; librados::ObjectWriteOperation op; op.create(true); cls_rgw_gc_queue_init(op, queue_size, num_urgent_data_entries); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); uint64_t size = 0; int ret = cls_rgw_gc_queue_get_capacity(ioctx, queue_name, size); ASSERT_EQ(0, ret); ASSERT_EQ(size, queue_size); cls_rgw_gc_obj_info defer_info1, defer_info2; //Test enqueue for (int i = 0; i < 2; i++) { string tag = "chain-" + to_string(i); librados::ObjectWriteOperation op; cls_rgw_gc_obj_info info; cls_rgw_obj obj1, obj2; create_obj(obj1, i, 1); create_obj(obj2, i, 2); info.chain.objs.push_back(obj1); info.chain.objs.push_back(obj2); info.tag = tag; cls_rgw_gc_queue_enqueue(op, 5, info); ASSERT_EQ(0, ioctx.operate(queue_name, &op)); if (i == 0) { defer_info1 = info; } if (i == 1) { defer_info2 = info; } } //Test defer entry for last element librados::ObjectWriteOperation defer_op; cls_rgw_gc_queue_defer_entry(defer_op, 10, defer_info2); ASSERT_EQ(0, ioctx.operate(queue_name, &defer_op)); //Test defer entry for first element cls_rgw_gc_queue_defer_entry(defer_op, 10, defer_info1); ASSERT_EQ(-ENOSPC, ioctx.operate(queue_name, &defer_op)); } /* must be last test! */ TEST(cls_rgw_gc, finalize) { /* remove pool */ ioctx.close(); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, rados)); }
19,975
27.496434
119
cc
null
ceph-main/src/test/cls_sdk/test_cls_sdk.cc
#include <iostream> #include <errno.h> #include "test/librados/test_cxx.h" #include "gtest/gtest.h" using namespace librados; TEST(ClsSDK, TestSDKCoverageWrite) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist in, out; ASSERT_EQ(0, ioctx.exec("myobject", "sdk", "test_coverage_write", in, out)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); } TEST(ClsSDK, TestSDKCoverageReplay) { Rados cluster; std::string pool_name = get_temp_pool_name(); ASSERT_EQ("", create_one_pool_pp(pool_name, cluster)); IoCtx ioctx; cluster.ioctx_create(pool_name.c_str(), ioctx); bufferlist in, out; ASSERT_EQ(0, ioctx.exec("myobject", "sdk", "test_coverage_write", in, out)); ASSERT_EQ(0, ioctx.exec("myobject", "sdk", "test_coverage_replay", in, out)); ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster)); }
984
26.361111
79
cc
null
ceph-main/src/test/cls_version/test_cls_version.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/rados/librados.hpp" #include "include/types.h" #include "cls/version/cls_version_types.h" #include "cls/version/cls_version_client.h" #include "gtest/gtest.h" #include "test/librados/test_cxx.h" #include <errno.h> #include <string> #include <vector> using namespace std; static librados::ObjectWriteOperation *new_op() { return new librados::ObjectWriteOperation(); } static librados::ObjectReadOperation *new_rop() { return new librados::ObjectReadOperation(); } TEST(cls_rgw, test_version_inc_read) { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); obj_version ver; ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver)); ASSERT_EQ(0, (long long)ver.ver); ASSERT_EQ(0, (int)ver.tag.size()); /* inc version */ librados::ObjectWriteOperation *op = new_op(); cls_version_inc(*op); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver)); ASSERT_GT((long long)ver.ver, 0); ASSERT_NE(0, (int)ver.tag.size()); /* inc version again! */ delete op; op = new_op(); cls_version_inc(*op); ASSERT_EQ(0, ioctx.operate(oid, op)); obj_version ver2; ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver2)); ASSERT_GT((long long)ver2.ver, (long long)ver.ver); ASSERT_EQ(0, (int)ver2.tag.compare(ver.tag)); delete op; obj_version ver3; librados::ObjectReadOperation *rop = new_rop(); cls_version_read(*rop, &ver3); bufferlist outbl; ASSERT_EQ(0, ioctx.operate(oid, rop, &outbl)); ASSERT_EQ(ver2.ver, ver3.ver); ASSERT_EQ(1, (long long)ver2.compare(&ver3)); delete rop; } TEST(cls_rgw, test_version_set) { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); obj_version ver; ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver)); ASSERT_EQ(0, (long long)ver.ver); ASSERT_EQ(0, (int)ver.tag.size()); ver.ver = 123; ver.tag = "foo"; /* set version */ librados::ObjectWriteOperation *op = new_op(); cls_version_set(*op, ver); ASSERT_EQ(0, ioctx.operate(oid, op)); /* read version */ obj_version ver2; ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver2)); ASSERT_EQ((long long)ver2.ver, (long long)ver.ver); ASSERT_EQ(0, (int)ver2.tag.compare(ver.tag)); delete op; } TEST(cls_rgw, test_version_inc_cond) { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); obj_version ver; ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver)); ASSERT_EQ(0, (long long)ver.ver); ASSERT_EQ(0, (int)ver.tag.size()); /* inc version */ librados::ObjectWriteOperation *op = new_op(); cls_version_inc(*op); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver)); ASSERT_GT((long long)ver.ver, 0); ASSERT_NE(0, (int)ver.tag.size()); obj_version cond_ver = ver; /* inc version again! */ delete op; op = new_op(); cls_version_inc(*op); ASSERT_EQ(0, ioctx.operate(oid, op)); obj_version ver2; ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver2)); ASSERT_GT((long long)ver2.ver, (long long)ver.ver); ASSERT_EQ(0, (int)ver2.tag.compare(ver.tag)); /* now check various condition tests */ cls_version_inc(*op, cond_ver, VER_COND_NONE); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver2)); ASSERT_GT((long long)ver2.ver, (long long)ver.ver); ASSERT_EQ(0, (int)ver2.tag.compare(ver.tag)); /* a bunch of conditions that should fail */ delete op; op = new_op(); cls_version_inc(*op, cond_ver, VER_COND_EQ); ASSERT_EQ(-ECANCELED, ioctx.operate(oid, op)); delete op; op = new_op(); cls_version_inc(*op, cond_ver, VER_COND_LT); ASSERT_EQ(-ECANCELED, ioctx.operate(oid, op)); delete op; op = new_op(); cls_version_inc(*op, cond_ver, VER_COND_LE); ASSERT_EQ(-ECANCELED, ioctx.operate(oid, op)); delete op; op = new_op(); cls_version_inc(*op, cond_ver, VER_COND_TAG_NE); ASSERT_EQ(-ECANCELED, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver2)); ASSERT_GT((long long)ver2.ver, (long long)ver.ver); ASSERT_EQ(0, (int)ver2.tag.compare(ver.tag)); /* a bunch of conditions that should succeed */ delete op; op = new_op(); cls_version_inc(*op, ver2, VER_COND_EQ); ASSERT_EQ(0, ioctx.operate(oid, op)); delete op; op = new_op(); cls_version_inc(*op, cond_ver, VER_COND_GT); ASSERT_EQ(0, ioctx.operate(oid, op)); delete op; op = new_op(); cls_version_inc(*op, cond_ver, VER_COND_GE); ASSERT_EQ(0, ioctx.operate(oid, op)); delete op; op = new_op(); cls_version_inc(*op, cond_ver, VER_COND_TAG_EQ); ASSERT_EQ(0, ioctx.operate(oid, op)); delete op; } TEST(cls_rgw, test_version_inc_check) { librados::Rados rados; librados::IoCtx ioctx; string pool_name = get_temp_pool_name(); /* create pool */ ASSERT_EQ("", create_one_pool_pp(pool_name, rados)); ASSERT_EQ(0, rados.ioctx_create(pool_name.c_str(), ioctx)); /* add chains */ string oid = "obj"; /* create object */ ASSERT_EQ(0, ioctx.create(oid, true)); obj_version ver; ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver)); ASSERT_EQ(0, (long long)ver.ver); ASSERT_EQ(0, (int)ver.tag.size()); /* inc version */ librados::ObjectWriteOperation *op = new_op(); cls_version_inc(*op); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver)); ASSERT_GT((long long)ver.ver, 0); ASSERT_NE(0, (int)ver.tag.size()); obj_version cond_ver = ver; /* a bunch of conditions that should succeed */ librados::ObjectReadOperation *rop = new_rop(); cls_version_check(*rop, cond_ver, VER_COND_EQ); bufferlist bl; ASSERT_EQ(0, ioctx.operate(oid, rop, &bl)); delete rop; rop = new_rop(); cls_version_check(*rop, cond_ver, VER_COND_GE); ASSERT_EQ(0, ioctx.operate(oid, rop, &bl)); delete rop; rop = new_rop(); cls_version_check(*rop, cond_ver, VER_COND_LE); ASSERT_EQ(0, ioctx.operate(oid, rop, &bl)); delete rop; rop = new_rop(); cls_version_check(*rop, cond_ver, VER_COND_TAG_EQ); ASSERT_EQ(0, ioctx.operate(oid, rop, &bl)); obj_version ver2; delete op; op = new_op(); cls_version_inc(*op); ASSERT_EQ(0, ioctx.operate(oid, op)); ASSERT_EQ(0, cls_version_read(ioctx, oid, &ver2)); ASSERT_GT((long long)ver2.ver, (long long)ver.ver); ASSERT_EQ(0, (int)ver2.tag.compare(ver.tag)); delete op; /* a bunch of conditions that should fail */ delete rop; rop = new_rop(); cls_version_check(*rop, ver, VER_COND_LT); ASSERT_EQ(-ECANCELED, ioctx.operate(oid, rop, &bl)); delete rop; rop = new_rop(); cls_version_check(*rop, cond_ver, VER_COND_LE); ASSERT_EQ(-ECANCELED, ioctx.operate(oid, rop, &bl)); delete rop; rop = new_rop(); cls_version_check(*rop, cond_ver, VER_COND_TAG_NE); ASSERT_EQ(-ECANCELED, ioctx.operate(oid, rop, &bl)); delete rop; }
7,728
22.928793
70
cc
null
ceph-main/src/test/common/ObjectContents.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- #include "ObjectContents.h" #include "include/buffer.h" #include <iostream> #include <map> bool test_object_contents() { ObjectContents c, d; ceph_assert(!c.exists()); c.debug(std::cerr); c.write(10, 10, 10); ceph_assert(c.exists()); ceph_assert(c.size() == 20); c.debug(std::cerr); bufferlist bl; for (ObjectContents::Iterator iter = c.get_iterator(); iter.valid(); ++iter) { bl.append(*iter); } ceph_assert(bl.length() == 20); bufferlist bl2; for (unsigned i = 0; i < 8; ++i) bl2.append(bl[i]); c.write(10, 8, 4); c.debug(std::cerr); ObjectContents::Iterator iter = c.get_iterator(); iter.seek_to(8); for (uint64_t i = 8; i < 12; ++i, ++iter) { bl2.append(*iter); } for (unsigned i = 12; i < 20; ++i) bl2.append(bl[i]); ceph_assert(bl2.length() == 20); for (ObjectContents::Iterator iter3 = c.get_iterator(); iter.valid(); ++iter) { ceph_assert(bl2[iter3.get_pos()] == *iter3); } ceph_assert(bl2[0] == '\0'); ceph_assert(bl2[7] == '\0'); interval_set<uint64_t> to_clone; to_clone.insert(5, 10); d.clone_range(c, to_clone); ceph_assert(d.size() == 15); c.debug(std::cerr); d.debug(std::cerr); ObjectContents::Iterator iter2 = d.get_iterator(); iter2.seek_to(5); for (uint64_t i = 5; i < 15; ++i, ++iter2) { std::cerr << "i is " << i << std::endl; ceph_assert(iter2.get_pos() == i); ceph_assert(*iter2 == bl2[i]); } return true; } unsigned int ObjectContents::Iterator::get_state(uint64_t _pos) { if (parent->seeds.count(_pos)) { return parent->seeds[_pos]; } seek_to(_pos - 1); return current_state; } void ObjectContents::clone_range(ObjectContents &other, interval_set<uint64_t> &intervals) { interval_set<uint64_t> written_to_clone; written_to_clone.intersection_of(intervals, other.written); interval_set<uint64_t> zeroed = intervals; zeroed.subtract(written_to_clone); written.union_of(intervals); written.subtract(zeroed); for (interval_set<uint64_t>::iterator i = written_to_clone.begin(); i != written_to_clone.end(); ++i) { uint64_t start = i.get_start(); uint64_t len = i.get_len(); unsigned int seed = get_iterator().get_state(start+len); seeds[start+len] = seed; seeds.erase(seeds.lower_bound(start), seeds.lower_bound(start+len)); seeds[start] = other.get_iterator().get_state(start); seeds.insert(other.seeds.upper_bound(start), other.seeds.lower_bound(start+len)); } if (intervals.range_end() > _size) _size = intervals.range_end(); _exists = true; return; } void ObjectContents::write(unsigned int seed, uint64_t start, uint64_t len) { _exists = true; unsigned int _seed = get_iterator().get_state(start+len); seeds[start+len] = _seed; seeds.erase(seeds.lower_bound(start), seeds.lower_bound(start+len)); seeds[start] = seed; interval_set<uint64_t> to_write; to_write.insert(start, len); written.union_of(to_write); if (start + len > _size) _size = start + len; return; }
3,150
23.426357
72
cc
null
ceph-main/src/test/common/ObjectContents.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- #include "include/interval_set.h" #include "include/buffer_fwd.h" #include <map> #ifndef COMMON_OBJECT_H #define COMMON_OBJECT_H enum { RANDOMWRITEFULL, DELETED, CLONERANGE }; bool test_object_contents(); class ObjectContents { uint64_t _size; std::map<uint64_t, unsigned int> seeds; interval_set<uint64_t> written; bool _exists; public: class Iterator { ObjectContents *parent; std::map<uint64_t, unsigned int>::iterator iter; unsigned int current_state; int current_val; uint64_t pos; private: unsigned int get_state(uint64_t pos); public: explicit Iterator(ObjectContents *parent) : parent(parent), iter(parent->seeds.end()), current_state(0), current_val(0), pos(-1) { seek_to_first(); } char operator*() { return parent->written.contains(pos) ? static_cast<char>(current_val % 256) : '\0'; } uint64_t get_pos() { return pos; } void seek_to(uint64_t _pos) { if (pos > _pos || (iter != parent->seeds.end() && _pos >= iter->first)) { iter = parent->seeds.upper_bound(_pos); --iter; current_state = iter->second; current_val = rand_r(&current_state); pos = iter->first; ++iter; } while (pos < _pos) ++(*this); } void seek_to_first() { seek_to(0); } Iterator &operator++() { ++pos; if (iter != parent->seeds.end() && pos >= iter->first) { ceph_assert(pos == iter->first); current_state = iter->second; ++iter; } current_val = rand_r(&current_state); return *this; } bool valid() { return pos < parent->size(); } friend class ObjectContents; }; ObjectContents() : _size(0), _exists(false) { seeds[0] = 0; } explicit ObjectContents(bufferlist::const_iterator &bp) { decode(_size, bp); decode(seeds, bp); decode(written, bp); decode(_exists, bp); } void clone_range(ObjectContents &other, interval_set<uint64_t> &intervals); void write(unsigned int seed, uint64_t from, uint64_t len); Iterator get_iterator() { return Iterator(this); } uint64_t size() const { return _size; } bool exists() { return _exists; } void debug(std::ostream &out) { out << "_size is " << _size << std::endl; out << "seeds is: ("; for (std::map<uint64_t, unsigned int>::iterator i = seeds.begin(); i != seeds.end(); ++i) { out << "[" << i->first << "," << i->second << "], "; } out << ")" << std::endl; out << "written is " << written << std::endl; out << "_exists is " << _exists << std::endl; } void encode(bufferlist &bl) const { using ceph::encode; encode(_size, bl); encode(seeds, bl); encode(written, bl); encode(_exists, bl); } }; #endif
2,837
22.073171
70
h
null
ceph-main/src/test/common/Readahead.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Adam Crume <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/Readahead.h" #include "gtest/gtest.h" #include <stdint.h> #include <boost/foreach.hpp> #include <cstdarg> #define ASSERT_RA(expected_offset, expected_length, ra) \ do { \ Readahead::extent_t e = ra; \ ASSERT_EQ((uint64_t)expected_length, e.second); \ if (expected_length) { \ ASSERT_EQ((uint64_t)expected_offset, e.first); \ } \ } while(0) using namespace std; TEST(Readahead, random_access) { Readahead r; r.set_trigger_requests(2); ASSERT_RA(0, 0, r.update(1000, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1010, 10, Readahead::NO_LIMIT)); ASSERT_RA(1030, 20, r.update(1020, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1040, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1060, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1080, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1100, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1200, 10, Readahead::NO_LIMIT)); } TEST(Readahead, min_size_limit) { Readahead r; r.set_trigger_requests(2); r.set_min_readahead_size(40); ASSERT_RA(0, 0, r.update(1000, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1010, 10, Readahead::NO_LIMIT)); ASSERT_RA(1030, 40, r.update(1020, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1030, 10, Readahead::NO_LIMIT)); ASSERT_RA(1070, 80, r.update(1040, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1050, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1060, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1070, 10, Readahead::NO_LIMIT)); } TEST(Readahead, max_size_limit) { Readahead r; r.set_trigger_requests(2); r.set_max_readahead_size(50); ASSERT_RA(0, 0, r.update(1000, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1010, 10, Readahead::NO_LIMIT)); ASSERT_RA(1030, 20, r.update(1020, 10, Readahead::NO_LIMIT)); ASSERT_RA(1050, 40, r.update(1030, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1040, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1050, 10, Readahead::NO_LIMIT)); ASSERT_RA(1090, 50, r.update(1060, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1070, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1080, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1090, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1100, 10, Readahead::NO_LIMIT)); ASSERT_RA(1140, 50, r.update(1110, 10, Readahead::NO_LIMIT)); } TEST(Readahead, limit) { Readahead r; r.set_trigger_requests(2); r.set_max_readahead_size(50); uint64_t limit = 1100; ASSERT_RA(0, 0, r.update(1000, 10, limit)); ASSERT_RA(0, 0, r.update(1010, 10, limit)); ASSERT_RA(1030, 20, r.update(1020, 10, limit)); ASSERT_RA(1050, 40, r.update(1030, 10, limit)); ASSERT_RA(0, 0, r.update(1040, 10, limit)); ASSERT_RA(0, 0, r.update(1050, 10, limit)); ASSERT_RA(1090, 10, r.update(1060, 10, limit)); ASSERT_RA(0, 0, r.update(1070, 10, limit)); ASSERT_RA(0, 0, r.update(1080, 10, limit)); ASSERT_RA(0, 0, r.update(1090, 10, limit)); } TEST(Readahead, alignment) { Readahead r; r.set_trigger_requests(2); vector<uint64_t> alignment; alignment.push_back(100); r.set_alignments(alignment); ASSERT_RA(0, 0, r.update(1000, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1010, 10, Readahead::NO_LIMIT)); ASSERT_RA(1030, 20, r.update(1020, 10, Readahead::NO_LIMIT)); ASSERT_RA(1050, 50, r.update(1030, 10, Readahead::NO_LIMIT)); // internal readahead size 40 ASSERT_RA(0, 0, r.update(1040, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1050, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1060, 10, Readahead::NO_LIMIT)); ASSERT_RA(1100, 100, r.update(1070, 10, Readahead::NO_LIMIT)); // internal readahead size 80 ASSERT_RA(0, 0, r.update(1080, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1090, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1100, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1110, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1120, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1130, 10, Readahead::NO_LIMIT)); ASSERT_RA(1200, 200, r.update(1140, 10, Readahead::NO_LIMIT)); // internal readahead size 160 ASSERT_RA(0, 0, r.update(1150, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1160, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1170, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1180, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1190, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1200, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1210, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1220, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1230, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1240, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1250, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1260, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1270, 10, Readahead::NO_LIMIT)); ASSERT_RA(0, 0, r.update(1280, 10, Readahead::NO_LIMIT)); ASSERT_RA(1400, 300, r.update(1290, 10, Readahead::NO_LIMIT)); // internal readahead size 320 ASSERT_RA(0, 0, r.update(1300, 10, Readahead::NO_LIMIT)); }
5,616
41.233083
95
cc
null
ceph-main/src/test/common/Throttle.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 Cloudwatt <[email protected]> * * Author: Loic Dachary <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library Public License for more details. * */ #include <stdio.h> #include <signal.h> #include <chrono> #include <list> #include <mutex> #include <random> #include <thread> #include "gtest/gtest.h" #include "common/Thread.h" #include "common/Throttle.h" #include "common/ceph_argparse.h" using namespace std; class ThrottleTest : public ::testing::Test { protected: class Thread_get : public Thread { public: Throttle &throttle; int64_t count; bool waited = false; Thread_get(Throttle& _throttle, int64_t _count) : throttle(_throttle), count(_count) {} void *entry() override { usleep(5); waited = throttle.get(count); throttle.put(count); return nullptr; } }; }; TEST_F(ThrottleTest, Throttle) { int64_t throttle_max = 10; Throttle throttle(g_ceph_context, "throttle", throttle_max); ASSERT_EQ(throttle.get_max(), throttle_max); ASSERT_EQ(throttle.get_current(), 0); } TEST_F(ThrottleTest, take) { int64_t throttle_max = 10; Throttle throttle(g_ceph_context, "throttle", throttle_max); ASSERT_EQ(throttle.take(throttle_max), throttle_max); ASSERT_EQ(throttle.take(throttle_max), throttle_max * 2); } TEST_F(ThrottleTest, get) { int64_t throttle_max = 10; Throttle throttle(g_ceph_context, "throttle"); // test increasing max from 0 to throttle_max { ASSERT_FALSE(throttle.get(throttle_max, throttle_max)); ASSERT_EQ(throttle.get_max(), throttle_max); ASSERT_EQ(throttle.put(throttle_max), 0); } ASSERT_FALSE(throttle.get(5)); ASSERT_EQ(throttle.put(5), 0); ASSERT_FALSE(throttle.get(throttle_max)); ASSERT_FALSE(throttle.get_or_fail(1)); ASSERT_FALSE(throttle.get(1, throttle_max + 1)); ASSERT_EQ(throttle.put(throttle_max + 1), 0); ASSERT_FALSE(throttle.get(0, throttle_max)); ASSERT_FALSE(throttle.get(throttle_max)); ASSERT_FALSE(throttle.get_or_fail(1)); ASSERT_EQ(throttle.put(throttle_max), 0); useconds_t delay = 1; bool waited; do { cout << "Trying (1) with delay " << delay << "us\n"; ASSERT_FALSE(throttle.get(throttle_max)); ASSERT_FALSE(throttle.get_or_fail(throttle_max)); Thread_get t(throttle, 7); t.create("t_throttle_1"); usleep(delay); ASSERT_EQ(throttle.put(throttle_max), 0); t.join(); if (!(waited = t.waited)) delay *= 2; } while(!waited); delay = 1; do { cout << "Trying (2) with delay " << delay << "us\n"; ASSERT_FALSE(throttle.get(throttle_max / 2)); ASSERT_FALSE(throttle.get_or_fail(throttle_max)); Thread_get t(throttle, throttle_max); t.create("t_throttle_2"); usleep(delay); Thread_get u(throttle, 1); u.create("u_throttle_2"); usleep(delay); throttle.put(throttle_max / 2); t.join(); u.join(); if (!(waited = t.waited && u.waited)) delay *= 2; } while(!waited); } TEST_F(ThrottleTest, get_or_fail) { { Throttle throttle(g_ceph_context, "throttle"); ASSERT_TRUE(throttle.get_or_fail(5)); ASSERT_TRUE(throttle.get_or_fail(5)); } { int64_t throttle_max = 10; Throttle throttle(g_ceph_context, "throttle", throttle_max); ASSERT_TRUE(throttle.get_or_fail(throttle_max)); ASSERT_EQ(throttle.put(throttle_max), 0); ASSERT_TRUE(throttle.get_or_fail(throttle_max * 2)); ASSERT_FALSE(throttle.get_or_fail(1)); ASSERT_FALSE(throttle.get_or_fail(throttle_max * 2)); ASSERT_EQ(throttle.put(throttle_max * 2), 0); ASSERT_TRUE(throttle.get_or_fail(throttle_max)); ASSERT_FALSE(throttle.get_or_fail(1)); ASSERT_EQ(throttle.put(throttle_max), 0); } } TEST_F(ThrottleTest, wait) { int64_t throttle_max = 10; Throttle throttle(g_ceph_context, "throttle"); // test increasing max from 0 to throttle_max { ASSERT_FALSE(throttle.wait(throttle_max)); ASSERT_EQ(throttle.get_max(), throttle_max); } useconds_t delay = 1; bool waited; do { cout << "Trying (3) with delay " << delay << "us\n"; ASSERT_FALSE(throttle.get(throttle_max / 2)); ASSERT_FALSE(throttle.get_or_fail(throttle_max)); Thread_get t(throttle, throttle_max); t.create("t_throttle_3"); usleep(delay); // // Throttle::_reset_max(int64_t m) used to contain a test // that blocked the following statement, only if // the argument was greater than throttle_max. // Although a value lower than throttle_max would cover // the same code in _reset_max, the throttle_max * 100 // value is left here to demonstrate that the problem // has been solved. // throttle.wait(throttle_max * 100); usleep(delay); t.join(); ASSERT_EQ(throttle.get_current(), throttle_max / 2); if (!(waited = t.waited)) { delay *= 2; // undo the changes we made throttle.put(throttle_max / 2); throttle.wait(throttle_max); } } while(!waited); } std::pair<double, std::chrono::duration<double> > test_backoff( double low_threshhold, double high_threshhold, double expected_throughput, double high_multiple, double max_multiple, uint64_t max, double put_delay_per_count, unsigned getters, unsigned putters) { std::mutex l; std::condition_variable c; uint64_t total = 0; std::list<uint64_t> in_queue; bool stop_getters = false; bool stop_putters = false; auto wait_time = std::chrono::duration<double>(0); uint64_t waits = 0; uint64_t total_observed_total = 0; uint64_t total_observations = 0; BackoffThrottle throttle(g_ceph_context, "backoff_throttle_test", 5); bool valid = throttle.set_params( low_threshhold, high_threshhold, expected_throughput, high_multiple, max_multiple, max, 0); ceph_assert(valid); auto getter = [&]() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, 10); std::unique_lock<std::mutex> g(l); while (!stop_getters) { g.unlock(); uint64_t to_get = dis(gen); auto waited = throttle.get(to_get); g.lock(); wait_time += waited; waits += to_get; total += to_get; in_queue.push_back(to_get); c.notify_one(); } }; auto putter = [&]() { std::unique_lock<std::mutex> g(l); while (!stop_putters || !in_queue.empty()) { if (in_queue.empty()) { c.wait(g); continue; } uint64_t c = in_queue.front(); total_observed_total += total; total_observations++; in_queue.pop_front(); ceph_assert(total <= max); g.unlock(); std::this_thread::sleep_for( c * std::chrono::duration<double>(put_delay_per_count*putters)); g.lock(); total -= c; throttle.put(c); } }; vector<std::thread> gts(getters); for (auto &&i: gts) i = std::thread(getter); vector<std::thread> pts(putters); for (auto &&i: pts) i = std::thread(putter); std::this_thread::sleep_for(std::chrono::duration<double>(5)); { std::unique_lock<std::mutex> g(l); stop_getters = true; c.notify_all(); } for (auto &&i: gts) i.join(); gts.clear(); { std::unique_lock<std::mutex> g(l); stop_putters = true; c.notify_all(); } for (auto &&i: pts) i.join(); pts.clear(); return make_pair( ((double)total_observed_total)/((double)total_observations), wait_time / waits); } TEST(BackoffThrottle, undersaturated) { auto results = test_backoff( 0.4, 0.6, 1000, 2, 10, 100, 0.0001, 3, 6); ASSERT_LT(results.first, 45); ASSERT_GT(results.first, 35); ASSERT_LT(results.second.count(), 0.0002); ASSERT_GT(results.second.count(), 0.00005); } TEST(BackoffThrottle, balanced) { auto results = test_backoff( 0.4, 0.6, 1000, 2, 10, 100, 0.001, 7, 2); ASSERT_LT(results.first, 60); ASSERT_GT(results.first, 40); ASSERT_LT(results.second.count(), 0.002); ASSERT_GT(results.second.count(), 0.0005); } TEST(BackoffThrottle, oversaturated) { auto results = test_backoff( 0.4, 0.6, 10000000, 2, 10, 100, 0.001, 1, 3); ASSERT_LT(results.first, 101); ASSERT_GT(results.first, 85); ASSERT_LT(results.second.count(), 0.002); ASSERT_GT(results.second.count(), 0.0005); } /* * Local Variables: * compile-command: "cd ../.. ; * make unittest_throttle ; * ./unittest_throttle # --gtest_filter=ThrottleTest.take \ * --log-to-stderr=true --debug-filestore=20 * " * End: */
9,135
22.607235
71
cc
null
ceph-main/src/test/common/dns_messages.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2016 SUSE LINUX GmbH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_TEST_DNS_MESSAGES_H #define CEPH_TEST_DNS_MESSAGES_H #include "common/dns_resolve.h" #include "gmock/gmock.h" u_char ns_search_msg_ok_payload[] = { 0x00, 0x55, 0x85, 0x80, 0x00, 0x01, 0x00, 0x03, 0x00, 0x02, 0x00, 0x05, 0x09, 0x5F, 0x63, 0x65, 0x70, 0x68, 0x2D, 0x6D, 0x6F, 0x6E, 0x04, 0x5F, 0x74, 0x63, 0x70, 0x04, 0x63, 0x65, 0x70, 0x68, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0x00, 0x21, 0x00, 0x01, 0xC0, 0x0C, 0x00, 0x21, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x16, 0x00, 0x0A, 0x00, 0x28, 0x1A, 0x85, 0x03, 0x6D, 0x6F, 0x6E, 0x01, 0x61, 0x04, 0x63, 0x65, 0x70, 0x68, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0xC0, 0x0C, 0x00, 0x21, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x16, 0x00, 0x0A, 0x00, 0x19, 0x1A, 0x85, 0x03, 0x6D, 0x6F, 0x6E, 0x01, 0x63, 0x04, 0x63, 0x65, 0x70, 0x68, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0xC0, 0x0C, 0x00, 0x21, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x16, 0x00, 0x0A, 0x00, 0x23, 0x1A, 0x85, 0x03, 0x6D, 0x6F, 0x6E, 0x01, 0x62, 0x04, 0x63, 0x65, 0x70, 0x68, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0xC0, 0x85, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x32, 0xC0, 0x85, 0xC0, 0x85, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x31, 0xC0, 0x85, 0xC0, 0x5D, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x0D, 0xC0, 0x7F, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x0C, 0xC0, 0x3B, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x0B, 0xC0, 0xAD, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x59, 0xC0, 0x9B, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0xFE }; u_char ns_query_msg_mon_c_payload[] = { 0x46, 0x4D, 0x85, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, 0x03, 0x6D, 0x6F, 0x6E, 0x01, 0x63, 0x04, 0x63, 0x65, 0x70, 0x68, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0x00, 0x01, 0x00, 0x01, 0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x0D, 0xC0, 0x12, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x31, 0xC0, 0x12, 0xC0, 0x12, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x32, 0xC0, 0x12, 0xC0, 0x3C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x59, 0xC0, 0x4E, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0xFE }; u_char ns_query_msg_mon_b_payload[] = { 0x64, 0xCC, 0x85, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, 0x03, 0x6D, 0x6F, 0x6E, 0x01, 0x62, 0x04, 0x63, 0x65, 0x70, 0x68, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0x00, 0x01, 0x00, 0x01, 0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x0C, 0xC0, 0x12, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x32, 0xC0, 0x12, 0xC0, 0x12, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x31, 0xC0, 0x12, 0xC0, 0x4E, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x59, 0xC0, 0x3C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0xFE }; u_char ns_query_msg_mon_a_payload[] = { 0x86, 0xAD, 0x85, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, 0x03, 0x6D, 0x6F, 0x6E, 0x01, 0x61, 0x04, 0x63, 0x65, 0x70, 0x68, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0x00, 0x01, 0x00, 0x01, 0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x0B, 0xC0, 0x12, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x32, 0xC0, 0x12, 0xC0, 0x12, 0x00, 0x02, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x06, 0x03, 0x6E, 0x73, 0x31, 0xC0, 0x12, 0xC0, 0x4E, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0x59, 0xC0, 0x3C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x09, 0x3A, 0x80, 0x00, 0x04, 0xC0, 0xA8, 0x01, 0xFE }; class MockResolvHWrapper : public ResolvHWrapper { public: #ifdef HAVE_RES_NQUERY MOCK_METHOD6(res_nquery, int(res_state s, const char *hostname, int cls, int type, u_char *buf, int bufsz)); MOCK_METHOD6(res_nsearch, int(res_state s, const char *hostname, int cls, int type, u_char *buf, int bufsz)); #else MOCK_METHOD5(res_query, int(const char *hostname, int cls, int type, u_char *buf, int bufsz)); MOCK_METHOD5(res_search, int(const char *hostname, int cls, int type, u_char *buf, int bufsz)); #endif }; #endif
5,042
48.930693
80
h
null
ceph-main/src/test/common/dns_resolve.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2016 SUSE LINUX GmbH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <arpa/nameser_compat.h> #include "common/dns_resolve.h" #include "test/common/dns_messages.h" #include "common/debug.h" #include "gmock/gmock.h" #include <sstream> #define TEST_DEBUG 20 #define dout_subsys ceph_subsys_ using namespace std; using ::testing::Return; using ::testing::_; using ::testing::SetArrayArgument; using ::testing::DoAll; using ::testing::StrEq; class DNSResolverTest : public ::testing::Test { protected: void SetUp() override { g_ceph_context->_conf->subsys.set_log_level(dout_subsys, TEST_DEBUG); } void TearDown() override { DNSResolver::get_instance(nullptr); } }; TEST_F(DNSResolverTest, resolve_ip_addr) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); int lena = sizeof(ns_query_msg_mon_a_payload); #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); #else EXPECT_CALL(*resolvH, res_query(StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); #endif entity_addr_t addr; DNSResolver::get_instance(resolvH)->resolve_ip_addr(g_ceph_context, "mon.a.ceph.com", &addr); std::ostringstream os; os << addr; ASSERT_EQ(os.str(), "v2:192.168.1.11:0/0"); } TEST_F(DNSResolverTest, resolve_ip_addr_fail) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nquery(_,StrEq("not_exists.com"), C_IN, T_A,_,_)) .WillOnce(Return(0)); #else EXPECT_CALL(*resolvH, res_query(StrEq("not_exists.com"), C_IN, T_A,_,_)) .WillOnce(Return(0)); #endif entity_addr_t addr; int ret = DNSResolver::get_instance(resolvH)->resolve_ip_addr(g_ceph_context, "not_exists.com", &addr); ASSERT_EQ(ret, -1); std::ostringstream os; os << addr; ASSERT_EQ(os.str(), "-"); } TEST_F(DNSResolverTest, resolve_srv_hosts_empty_domain) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); int len = sizeof(ns_search_msg_ok_payload); int lena = sizeof(ns_query_msg_mon_a_payload); int lenb = sizeof(ns_query_msg_mon_b_payload); int lenc = sizeof(ns_query_msg_mon_c_payload); using ::testing::InSequence; { InSequence s; #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nsearch(_, StrEq("_cephmon._tcp"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<4>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_nquery(_, StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #else EXPECT_CALL(*resolvH, res_search(StrEq("_cephmon._tcp"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<3>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #endif } map<string, DNSResolver::Record> records; DNSResolver::get_instance(resolvH)->resolve_srv_hosts(g_ceph_context, "cephmon", DNSResolver::SRV_Protocol::TCP, &records); ASSERT_EQ(records.size(), (unsigned int)3); auto it = records.find("mon.a"); ASSERT_NE(it, records.end()); std::ostringstream os; os << it->second.addr; ASSERT_EQ(os.str(), "v2:192.168.1.11:6789/0"); os.str(""); ASSERT_EQ(it->second.priority, 10); ASSERT_EQ(it->second.weight, 40); it = records.find("mon.b"); ASSERT_NE(it, records.end()); os << it->second.addr; ASSERT_EQ(os.str(), "v2:192.168.1.12:6789/0"); os.str(""); ASSERT_EQ(it->second.priority, 10); ASSERT_EQ(it->second.weight, 35); it = records.find("mon.c"); ASSERT_NE(it, records.end()); os << it->second.addr; ASSERT_EQ(os.str(), "v2:192.168.1.13:6789/0"); ASSERT_EQ(it->second.priority, 10); ASSERT_EQ(it->second.weight, 25); } TEST_F(DNSResolverTest, resolve_srv_hosts_full_domain) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); int len = sizeof(ns_search_msg_ok_payload); int lena = sizeof(ns_query_msg_mon_a_payload); int lenb = sizeof(ns_query_msg_mon_b_payload); int lenc = sizeof(ns_query_msg_mon_c_payload); using ::testing::InSequence; { InSequence s; #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nsearch(_, StrEq("_cephmon._tcp.ceph.com"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<4>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_nquery(_, StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #else EXPECT_CALL(*resolvH, res_search(StrEq("_cephmon._tcp.ceph.com"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<3>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #endif } map<string, DNSResolver::Record> records; DNSResolver::get_instance(resolvH)->resolve_srv_hosts(g_ceph_context, "cephmon", DNSResolver::SRV_Protocol::TCP, "ceph.com", &records); ASSERT_EQ(records.size(), (unsigned int)3); auto it = records.find("mon.a"); ASSERT_NE(it, records.end()); std::ostringstream os; os << it->second.addr; ASSERT_EQ(os.str(), "v2:192.168.1.11:6789/0"); os.str(""); it = records.find("mon.b"); ASSERT_NE(it, records.end()); os << it->second.addr; ASSERT_EQ(os.str(), "v2:192.168.1.12:6789/0"); os.str(""); it = records.find("mon.c"); ASSERT_NE(it, records.end()); os << it->second.addr; ASSERT_EQ(os.str(), "v2:192.168.1.13:6789/0"); } TEST_F(DNSResolverTest, resolve_srv_hosts_fail) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); using ::testing::InSequence; { InSequence s; #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nsearch(_, StrEq("_noservice._tcp"), C_IN, T_SRV, _, _)) .WillOnce(Return(0)); #else EXPECT_CALL(*resolvH, res_search(StrEq("_noservice._tcp"), C_IN, T_SRV, _, _)) .WillOnce(Return(0)); #endif } map<string, DNSResolver::Record> records; int ret = DNSResolver::get_instance(resolvH)->resolve_srv_hosts( g_ceph_context, "noservice", DNSResolver::SRV_Protocol::TCP, "", &records); ASSERT_EQ(0, ret); ASSERT_TRUE(records.empty()); }
8,965
32.962121
93
cc
null
ceph-main/src/test/common/get_command_descriptions.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 Cloudwatt <[email protected]> * * Author: Loic Dachary <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library Public License for more details. * */ #include <stdio.h> #include <signal.h> #include "mon/Monitor.h" #include "common/ceph_argparse.h" #include "global/global_init.h" using namespace std; static void usage(ostream &out) { out << "usage: get_command_descriptions [options ...]" << std::endl; out << "print on stdout the result of JSON formatted options\n"; out << "found in mon/MonCommands.h as produced by the\n"; out << "Monitor.cc::get_command_descriptions function.\n"; out << "Designed as a helper for ceph_argparse.py unit tests.\n"; out << "\n"; out << " --all all of mon/MonCommands.h \n"; out << " --pull585 reproduce the bug fixed by #585\n"; out << "\n"; out << "Examples:\n"; out << " get_command_descriptions --all\n"; out << " get_command_descriptions --pull585\n"; } static void json_print(const std::vector<MonCommand> &mon_commands) { bufferlist rdata; auto f = Formatter::create_unique("json"); Monitor::format_command_descriptions(mon_commands, f.get(), CEPH_FEATURES_ALL, &rdata); string data(rdata.c_str(), rdata.length()); cout << data << std::endl; } static void all() { #undef FLAG #undef COMMAND #undef COMMAND_WITH_FLAG std::vector<MonCommand> mon_commands = { #define FLAG(f) (MonCommand::FLAG_##f) #define COMMAND(parsesig, helptext, modulename, req_perms) \ {parsesig, helptext, modulename, req_perms, 0}, #define COMMAND_WITH_FLAG(parsesig, helptext, modulename, req_perms, flags) \ {parsesig, helptext, modulename, req_perms, flags}, #include <mon/MonCommands.h> #undef COMMAND #undef COMMAND_WITH_FLAG #define COMMAND(parsesig, helptext, modulename, req_perms) \ {parsesig, helptext, modulename, req_perms, FLAG(MGR)}, #define COMMAND_WITH_FLAG(parsesig, helptext, modulename, req_perms, flags) \ {parsesig, helptext, modulename, req_perms, flags | FLAG(MGR)}, #include <mgr/MgrCommands.h> #undef COMMAND #undef COMMAND_WITH_FLAG }; json_print(mon_commands); } // syntax error https://github.com/ceph/ceph/pull/585 static void pull585() { std::vector<MonCommand> mon_commands = { { "osd pool create " "name=pool,type=CephPoolname " "name=pg_num,type=CephInt,range=0,req=false " "name=pgp_num,type=CephInt,range=0,req=false" // !!! missing trailing space "name=properties,type=CephString,n=N,req=false,goodchars=[A-Za-z0-9-_.=]", "create pool", "osd", "rw" } }; json_print(mon_commands); } int main(int argc, char **argv) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); if (args.empty()) { usage(cerr); exit(1); } for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ++i) { string err; if (*i == string("help") || *i == string("-h") || *i == string("--help")) { usage(cout); exit(0); } else if (*i == string("--all")) { all(); } else if (*i == string("--pull585")) { pull585(); } } } /* * Local Variables: * compile-command: "cd ../.. ; * make get_command_descriptions && * ./get_command_descriptions --all --pull585" * End: */
4,018
29.44697
83
cc
null
ceph-main/src/test/common/histogram.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Inktank <[email protected]> * * LGPL-2.1 (see COPYING-LGPL2.1) or later */ #include <iostream> #include <gtest/gtest.h> #include "common/histogram.h" #include "include/stringify.h" TEST(Histogram, Basic) { pow2_hist_t h; h.add(0); h.add(0); h.add(0); ASSERT_EQ(3, h.h[0]); ASSERT_EQ(1u, h.h.size()); h.add(1); ASSERT_EQ(3, h.h[0]); ASSERT_EQ(1, h.h[1]); ASSERT_EQ(2u, h.h.size()); h.add(2); h.add(2); ASSERT_EQ(3, h.h[0]); ASSERT_EQ(1, h.h[1]); ASSERT_EQ(2, h.h[2]); ASSERT_EQ(3u, h.h.size()); } TEST(Histogram, Set) { pow2_hist_t h; h.set_bin(0, 12); h.set_bin(2, 12); ASSERT_EQ(12, h.h[0]); ASSERT_EQ(0, h.h[1]); ASSERT_EQ(12, h.h[2]); ASSERT_EQ(3u, h.h.size()); } TEST(Histogram, Position) { pow2_hist_t h; uint64_t lb, ub; h.add(0); ASSERT_EQ(-1, h.get_position_micro(-20, &lb, &ub)); } TEST(Histogram, Position1) { pow2_hist_t h; h.add(0); uint64_t lb, ub; h.get_position_micro(0, &lb, &ub); ASSERT_EQ(0u, lb); ASSERT_EQ(1000000u, ub); h.add(0); h.add(0); h.add(0); h.get_position_micro(0, &lb, &ub); ASSERT_EQ(0u, lb); ASSERT_EQ(1000000u, ub); } TEST(Histogram, Position2) { pow2_hist_t h; h.add(1); h.add(1); uint64_t lb, ub; h.get_position_micro(0, &lb, &ub); ASSERT_EQ(0u, lb); ASSERT_EQ(0u, ub); h.add(0); h.get_position_micro(0, &lb, &ub); ASSERT_EQ(0u, lb); ASSERT_EQ(333333u, ub); h.get_position_micro(1, &lb, &ub); ASSERT_EQ(333333u, lb); ASSERT_EQ(1000000u, ub); } TEST(Histogram, Position3) { pow2_hist_t h; h.h.resize(10, 0); h.h[0] = 1; h.h[5] = 1; uint64_t lb, ub; h.get_position_micro(4, &lb, &ub); ASSERT_EQ(500000u, lb); ASSERT_EQ(500000u, ub); } TEST(Histogram, Position4) { pow2_hist_t h; h.h.resize(10, 0); h.h[0] = UINT_MAX; h.h[5] = UINT_MAX; uint64_t lb, ub; h.get_position_micro(4, &lb, &ub); ASSERT_EQ(0u, lb); ASSERT_EQ(0u, ub); } TEST(Histogram, Decay) { pow2_hist_t h; h.set_bin(0, 123); h.set_bin(3, 12); h.set_bin(5, 1); h.decay(1); ASSERT_EQ(61, h.h[0]); ASSERT_EQ(6, h.h[3]); ASSERT_EQ(4u, h.h.size()); } /* * Local Variables: * compile-command: "cd ../.. ; make -j4 && * make unittest_histogram && * valgrind --tool=memcheck --leak-check=full \ * ./unittest_histogram * " * End: */
2,478
18.069231
70
cc
null
ceph-main/src/test/common/test_allocate_unique.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/allocate_unique.h" #include <string> #include <vector> #include <gtest/gtest.h> namespace { // allocation events recorded by logging_allocator struct event { size_t size; bool allocated; // true for allocate(), false for deallocate() }; using event_log = std::vector<event>; template <typename T> struct logging_allocator { event_log *const log; using value_type = T; explicit logging_allocator(event_log *log) : log(log) {} logging_allocator(const logging_allocator& other) : log(other.log) {} template <typename U> logging_allocator(const logging_allocator<U>& other) : log(other.log) {} T* allocate(size_t n) { auto p = std::allocator<T>{}.allocate(n); log->emplace_back(event{n * sizeof(T), true}); return p; } void deallocate(T* p, size_t n) { std::allocator<T>{}.deallocate(p, n); if (p) { log->emplace_back(event{n * sizeof(T), false}); } } }; } // anonymous namespace namespace ceph { TEST(AllocateUnique, Allocate) { event_log log; auto alloc = logging_allocator<char>{&log}; { auto p = allocate_unique<char>(alloc, 'a'); static_assert(std::is_same_v<decltype(p), std::unique_ptr<char, deallocator<logging_allocator<char>>>>); ASSERT_TRUE(p); ASSERT_EQ(1, log.size()); EXPECT_EQ(1, log.front().size); EXPECT_EQ(true, log.front().allocated); } ASSERT_EQ(2, log.size()); EXPECT_EQ(1, log.back().size); EXPECT_EQ(false, log.back().allocated); } TEST(AllocateUnique, RebindAllocate) { event_log log; auto alloc = logging_allocator<char>{&log}; { auto p = allocate_unique<std::string>(alloc, "a"); static_assert(std::is_same_v<decltype(p), std::unique_ptr<std::string, deallocator<logging_allocator<std::string>>>>); ASSERT_TRUE(p); ASSERT_EQ(1, log.size()); EXPECT_EQ(sizeof(std::string), log.front().size); EXPECT_EQ(true, log.front().allocated); } ASSERT_EQ(2, log.size()); EXPECT_EQ(sizeof(std::string), log.back().size); EXPECT_EQ(false, log.back().allocated); } } // namespace ceph
2,523
24.755102
81
cc
null
ceph-main/src/test/common/test_async_completion.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/async/completion.h" #include <optional> #include <boost/intrusive/list.hpp> #include <gtest/gtest.h> namespace ceph::async { using boost::system::error_code; struct move_only { move_only() = default; move_only(move_only&&) = default; move_only& operator=(move_only&&) = default; move_only(const move_only&) = delete; move_only& operator=(const move_only&) = delete; }; TEST(AsyncCompletion, BindHandler) { auto h1 = [] (int i, char c) {}; auto b1 = bind_handler(std::move(h1), 5, 'a'); b1(); const auto& c1 = b1; c1(); std::move(b1)(); // move-only types can be forwarded with 'operator() &&' auto h2 = [] (move_only&& m) {}; auto b2 = bind_handler(std::move(h2), move_only{}); std::move(b2)(); // references bound with std::ref() can be passed to all operator() overloads auto h3 = [] (int& c) { c++; }; int count = 0; auto b3 = bind_handler(std::move(h3), std::ref(count)); EXPECT_EQ(0, count); b3(); EXPECT_EQ(1, count); const auto& c3 = b3; c3(); EXPECT_EQ(2, count); std::move(b3)(); EXPECT_EQ(3, count); } TEST(AsyncCompletion, ForwardHandler) { // move-only types can be forwarded with 'operator() &' auto h = [] (move_only&& m) {}; auto b = bind_handler(std::move(h), move_only{}); auto f = forward_handler(std::move(b)); f(); } TEST(AsyncCompletion, MoveOnly) { boost::asio::io_context context; auto ex1 = context.get_executor(); std::optional<error_code> ec1, ec2, ec3; std::optional<move_only> arg3; { // move-only user data using Completion = Completion<void(error_code), move_only>; auto c = Completion::create(ex1, [&ec1] (error_code ec) { ec1 = ec; }); Completion::post(std::move(c), boost::asio::error::operation_aborted); EXPECT_FALSE(ec1); } { // move-only handler using Completion = Completion<void(error_code)>; auto c = Completion::create(ex1, [&ec2, m=move_only{}] (error_code ec) { static_cast<void>(m); ec2 = ec; }); Completion::post(std::move(c), boost::asio::error::operation_aborted); EXPECT_FALSE(ec2); } { // move-only arg in signature using Completion = Completion<void(error_code, move_only)>; auto c = Completion::create(ex1, [&] (error_code ec, move_only m) { ec3 = ec; arg3 = std::move(m); }); Completion::post(std::move(c), boost::asio::error::operation_aborted, move_only{}); EXPECT_FALSE(ec3); } context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec1); EXPECT_EQ(boost::asio::error::operation_aborted, *ec1); ASSERT_TRUE(ec2); EXPECT_EQ(boost::asio::error::operation_aborted, *ec2); ASSERT_TRUE(ec3); EXPECT_EQ(boost::asio::error::operation_aborted, *ec3); ASSERT_TRUE(arg3); } TEST(AsyncCompletion, VoidCompletion) { boost::asio::io_context context; auto ex1 = context.get_executor(); using Completion = Completion<void(error_code)>; std::optional<error_code> ec1; auto c = Completion::create(ex1, [&ec1] (error_code ec) { ec1 = ec; }); Completion::post(std::move(c), boost::asio::error::operation_aborted); EXPECT_FALSE(ec1); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec1); EXPECT_EQ(boost::asio::error::operation_aborted, *ec1); } TEST(AsyncCompletion, CompletionList) { boost::asio::io_context context; auto ex1 = context.get_executor(); using T = AsBase<boost::intrusive::list_base_hook<>>; using Completion = Completion<void(), T>; boost::intrusive::list<Completion> completions; int completed = 0; for (int i = 0; i < 3; i++) { auto c = Completion::create(ex1, [&] { completed++; }); completions.push_back(*c.release()); } completions.clear_and_dispose([] (Completion *c) { Completion::post(std::unique_ptr<Completion>{c}); }); EXPECT_EQ(0, completed); context.poll(); EXPECT_TRUE(context.stopped()); EXPECT_EQ(3, completed); } TEST(AsyncCompletion, CompletionPair) { boost::asio::io_context context; auto ex1 = context.get_executor(); using T = std::pair<int, std::string>; using Completion = Completion<void(int, std::string), T>; std::optional<T> t; auto c = Completion::create(ex1, [&] (int first, std::string second) { t = T{first, std::move(second)}; }, 2, "hello"); auto data = std::move(c->user_data); Completion::post(std::move(c), data.first, std::move(data.second)); EXPECT_FALSE(t); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(t); EXPECT_EQ(2, t->first); EXPECT_EQ("hello", t->second); } TEST(AsyncCompletion, CompletionReference) { boost::asio::io_context context; auto ex1 = context.get_executor(); using Completion = Completion<void(int&)>; auto c = Completion::create(ex1, [] (int& i) { ++i; }); int i = 42; Completion::post(std::move(c), std::ref(i)); EXPECT_EQ(42, i); context.poll(); EXPECT_TRUE(context.stopped()); EXPECT_EQ(43, i); } struct throws_on_move { throws_on_move() = default; throws_on_move(throws_on_move&&) { throw std::runtime_error("oops"); } throws_on_move& operator=(throws_on_move&&) { throw std::runtime_error("oops"); } throws_on_move(const throws_on_move&) = default; throws_on_move& operator=(const throws_on_move&) = default; }; TEST(AsyncCompletion, ThrowOnCtor) { boost::asio::io_context context; auto ex1 = context.get_executor(); { using Completion = Completion<void(int&)>; // throw on Handler move construction EXPECT_THROW(Completion::create(ex1, [t=throws_on_move{}] (int& i) { static_cast<void>(t); ++i; }), std::runtime_error); } { using T = throws_on_move; using Completion = Completion<void(int&), T>; // throw on UserData construction EXPECT_THROW(Completion::create(ex1, [] (int& i) { ++i; }, throws_on_move{}), std::runtime_error); } } TEST(AsyncCompletion, FreeFunctions) { boost::asio::io_context context; auto ex1 = context.get_executor(); auto c1 = create_completion<void(), void>(ex1, [] {}); post(std::move(c1)); auto c2 = create_completion<void(int), int>(ex1, [] (int) {}, 5); defer(std::move(c2), c2->user_data); context.poll(); EXPECT_TRUE(context.stopped()); } } // namespace ceph::async
6,662
24.92607
87
cc
null
ceph-main/src/test/common/test_async_shared_mutex.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/async/shared_mutex.h" #include <optional> #include <gtest/gtest.h> namespace ceph::async { using executor_type = boost::asio::io_context::executor_type; using unique_lock = std::unique_lock<SharedMutex<executor_type>>; using shared_lock = std::shared_lock<SharedMutex<executor_type>>; // return a lambda that captures its error code and lock auto capture(std::optional<boost::system::error_code>& ec, unique_lock& lock) { return [&] (boost::system::error_code e, unique_lock l) { ec = e; lock = std::move(l); }; } auto capture(std::optional<boost::system::error_code>& ec, shared_lock& lock) { return [&] (boost::system::error_code e, shared_lock l) { ec = e; lock = std::move(l); }; } TEST(SharedMutex, async_exclusive) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); std::optional<boost::system::error_code> ec1, ec2, ec3; unique_lock lock1, lock2, lock3; // request three exclusive locks mutex.async_lock(capture(ec1, lock1)); mutex.async_lock(capture(ec2, lock2)); mutex.async_lock(capture(ec3, lock3)); EXPECT_FALSE(ec1); // no callbacks until poll() EXPECT_FALSE(ec2); EXPECT_FALSE(ec3); context.poll(); EXPECT_FALSE(context.stopped()); // second lock still pending ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); EXPECT_FALSE(ec2); lock1.unlock(); EXPECT_FALSE(ec2); context.poll(); EXPECT_FALSE(context.stopped()); ASSERT_TRUE(ec2); EXPECT_EQ(boost::system::errc::success, *ec2); ASSERT_TRUE(lock2); EXPECT_FALSE(ec3); lock2.unlock(); EXPECT_FALSE(ec3); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec3); EXPECT_EQ(boost::system::errc::success, *ec3); ASSERT_TRUE(lock3); } TEST(SharedMutex, async_shared) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); std::optional<boost::system::error_code> ec1, ec2; shared_lock lock1, lock2; // request two shared locks mutex.async_lock_shared(capture(ec1, lock1)); mutex.async_lock_shared(capture(ec2, lock2)); EXPECT_FALSE(ec1); // no callbacks until poll() EXPECT_FALSE(ec2); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); ASSERT_TRUE(ec2); EXPECT_EQ(boost::system::errc::success, *ec2); ASSERT_TRUE(lock2); } TEST(SharedMutex, async_exclusive_while_shared) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); std::optional<boost::system::error_code> ec1, ec2; shared_lock lock1; unique_lock lock2; // request a shared and exclusive lock mutex.async_lock_shared(capture(ec1, lock1)); mutex.async_lock(capture(ec2, lock2)); EXPECT_FALSE(ec1); // no callbacks until poll() EXPECT_FALSE(ec2); context.poll(); EXPECT_FALSE(context.stopped()); // second lock still pending ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); EXPECT_FALSE(ec2); lock1.unlock(); EXPECT_FALSE(ec2); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec2); EXPECT_EQ(boost::system::errc::success, *ec2); ASSERT_TRUE(lock2); } TEST(SharedMutex, async_shared_while_exclusive) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); std::optional<boost::system::error_code> ec1, ec2; unique_lock lock1; shared_lock lock2; // request an exclusive and shared lock mutex.async_lock(capture(ec1, lock1)); mutex.async_lock_shared(capture(ec2, lock2)); EXPECT_FALSE(ec1); // no callbacks until poll() EXPECT_FALSE(ec2); context.poll(); EXPECT_FALSE(context.stopped()); // second lock still pending ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); EXPECT_FALSE(ec2); lock1.unlock(); EXPECT_FALSE(ec2); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec2); EXPECT_EQ(boost::system::errc::success, *ec2); ASSERT_TRUE(lock2); } TEST(SharedMutex, async_prioritize_exclusive) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); std::optional<boost::system::error_code> ec1, ec2, ec3; shared_lock lock1, lock3; unique_lock lock2; // acquire a shared lock, then request an exclusive and another shared lock mutex.async_lock_shared(capture(ec1, lock1)); mutex.async_lock(capture(ec2, lock2)); mutex.async_lock_shared(capture(ec3, lock3)); EXPECT_FALSE(ec1); // no callbacks until poll() EXPECT_FALSE(ec2); EXPECT_FALSE(ec3); context.poll(); EXPECT_FALSE(context.stopped()); ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); EXPECT_FALSE(ec2); // exclusive waiter blocks the second shared lock EXPECT_FALSE(ec3); lock1.unlock(); EXPECT_FALSE(ec2); EXPECT_FALSE(ec3); context.poll(); EXPECT_FALSE(context.stopped()); ASSERT_TRUE(ec2); EXPECT_EQ(boost::system::errc::success, *ec2); ASSERT_TRUE(lock2); EXPECT_FALSE(ec3); } TEST(SharedMutex, async_cancel) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); std::optional<boost::system::error_code> ec1, ec2, ec3, ec4; unique_lock lock1, lock2; shared_lock lock3, lock4; // request 2 exclusive and shared locks mutex.async_lock(capture(ec1, lock1)); mutex.async_lock(capture(ec2, lock2)); mutex.async_lock_shared(capture(ec3, lock3)); mutex.async_lock_shared(capture(ec4, lock4)); EXPECT_FALSE(ec1); // no callbacks until poll() EXPECT_FALSE(ec2); EXPECT_FALSE(ec3); EXPECT_FALSE(ec4); context.poll(); EXPECT_FALSE(context.stopped()); ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); EXPECT_FALSE(ec2); EXPECT_FALSE(ec3); EXPECT_FALSE(ec4); mutex.cancel(); EXPECT_FALSE(ec2); EXPECT_FALSE(ec3); EXPECT_FALSE(ec4); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec2); EXPECT_EQ(boost::asio::error::operation_aborted, *ec2); EXPECT_FALSE(lock2); ASSERT_TRUE(ec3); EXPECT_EQ(boost::asio::error::operation_aborted, *ec3); EXPECT_FALSE(lock3); ASSERT_TRUE(ec4); EXPECT_EQ(boost::asio::error::operation_aborted, *ec4); EXPECT_FALSE(lock4); } TEST(SharedMutex, async_destruct) { boost::asio::io_context context; std::optional<boost::system::error_code> ec1, ec2, ec3, ec4; unique_lock lock1, lock2; shared_lock lock3, lock4; { SharedMutex mutex(context.get_executor()); // request 2 exclusive and shared locks mutex.async_lock(capture(ec1, lock1)); mutex.async_lock(capture(ec2, lock2)); mutex.async_lock_shared(capture(ec3, lock3)); mutex.async_lock_shared(capture(ec4, lock4)); } EXPECT_FALSE(ec1); // no callbacks until poll() EXPECT_FALSE(ec2); EXPECT_FALSE(ec3); EXPECT_FALSE(ec4); context.poll(); EXPECT_TRUE(context.stopped()); ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); ASSERT_TRUE(ec2); EXPECT_EQ(boost::asio::error::operation_aborted, *ec2); EXPECT_FALSE(lock2); ASSERT_TRUE(ec3); EXPECT_EQ(boost::asio::error::operation_aborted, *ec3); EXPECT_FALSE(lock3); ASSERT_TRUE(ec4); EXPECT_EQ(boost::asio::error::operation_aborted, *ec4); EXPECT_FALSE(lock4); } // return a capture() lambda that's bound to the given executor template <typename Executor, typename ...Args> auto capture_ex(const Executor& ex, Args&& ...args) { return boost::asio::bind_executor(ex, capture(std::forward<Args>(args)...)); } TEST(SharedMutex, cross_executor) { boost::asio::io_context mutex_context; SharedMutex mutex(mutex_context.get_executor()); boost::asio::io_context callback_context; auto ex2 = callback_context.get_executor(); std::optional<boost::system::error_code> ec1, ec2; unique_lock lock1, lock2; // request two exclusive locks mutex.async_lock(capture_ex(ex2, ec1, lock1)); mutex.async_lock(capture_ex(ex2, ec2, lock2)); EXPECT_FALSE(ec1); EXPECT_FALSE(ec2); mutex_context.poll(); EXPECT_FALSE(mutex_context.stopped()); // maintains work on both executors EXPECT_FALSE(ec1); // no callbacks until poll() on callback_context EXPECT_FALSE(ec2); callback_context.poll(); EXPECT_FALSE(callback_context.stopped()); // second lock still pending ASSERT_TRUE(ec1); EXPECT_EQ(boost::system::errc::success, *ec1); ASSERT_TRUE(lock1); EXPECT_FALSE(ec2); lock1.unlock(); mutex_context.poll(); EXPECT_TRUE(mutex_context.stopped()); EXPECT_FALSE(ec2); callback_context.poll(); EXPECT_TRUE(callback_context.stopped()); ASSERT_TRUE(ec2); EXPECT_EQ(boost::system::errc::success, *ec2); ASSERT_TRUE(lock2); } TEST(SharedMutex, try_exclusive) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); { std::lock_guard lock{mutex}; ASSERT_FALSE(mutex.try_lock()); // fail during exclusive } { std::shared_lock lock{mutex}; ASSERT_FALSE(mutex.try_lock()); // fail during shared } ASSERT_TRUE(mutex.try_lock()); mutex.unlock(); } TEST(SharedMutex, try_shared) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); { std::lock_guard lock{mutex}; ASSERT_FALSE(mutex.try_lock_shared()); // fail during exclusive } { std::shared_lock lock{mutex}; ASSERT_TRUE(mutex.try_lock_shared()); // succeed during shared mutex.unlock_shared(); } ASSERT_TRUE(mutex.try_lock_shared()); mutex.unlock_shared(); } TEST(SharedMutex, cancel) { boost::asio::io_context context; SharedMutex mutex(context.get_executor()); std::lock_guard l{mutex}; // exclusive lock blocks others // make synchronous lock calls in other threads auto f1 = std::async(std::launch::async, [&] { mutex.lock(); }); auto f2 = std::async(std::launch::async, [&] { mutex.lock_shared(); }); // this will race with spawned threads. just keep canceling until the // futures are ready const auto t = std::chrono::milliseconds(1); do { mutex.cancel(); } while (f1.wait_for(t) != std::future_status::ready); do { mutex.cancel(); } while (f2.wait_for(t) != std::future_status::ready); EXPECT_THROW(f1.get(), boost::system::system_error); EXPECT_THROW(f2.get(), boost::system::system_error); } } // namespace ceph::async
10,729
24.011655
78
cc
null
ceph-main/src/test/common/test_back_trace.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <boost/algorithm/string.hpp> #include <gtest/gtest.h> #include <regex> #include <sstream> #include <string> #include "common/BackTrace.h" #include "common/version.h" // a dummy function, so we can check "foo" in the backtrace. // do not mark this function as static or put it into an anonymous namespace, // otherwise it's function name will be removed in the backtrace. std::string foo() { std::ostringstream oss; oss << ceph::ClibBackTrace(1); return oss.str(); } // a typical backtrace looks like: // // ceph version Development (no_version) // 1: (foo[abi:cxx11]()+0x4a) [0x5562231cf22a] // 2: (BackTrace_Basic_Test::TestBody()+0x28) [0x5562231cf2fc] TEST(BackTrace, Basic) { std::string bt = foo(); std::vector<std::string> lines; boost::split(lines, bt, boost::is_any_of("\n")); const unsigned lineno = 1; ASSERT_GT(lines.size(), lineno); ASSERT_EQ(lines[0].find(pretty_version_to_str()), 1U); std::regex e{"^ 1: " #ifdef __FreeBSD__ "<foo.*>\\s" "at\\s.*$"}; #else "\\(foo.*\\)\\s" "\\[0x[[:xdigit:]]+\\]$"}; #endif EXPECT_TRUE(std::regex_match(lines[lineno], e)); }
1,219
26.111111
77
cc
null
ceph-main/src/test/common/test_bit_vector.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Red Hat <[email protected]> * * LGPL-2.1 (see COPYING-LGPL2.1) or later */ #include <gtest/gtest.h> #include <cmath> #include "common/bit_vector.hpp" #include <boost/assign/list_of.hpp> using namespace ceph; template <uint8_t _bit_count> class TestParams { public: static const uint8_t BIT_COUNT = _bit_count; }; template <typename T> class BitVectorTest : public ::testing::Test { public: typedef BitVector<T::BIT_COUNT> bit_vector_t; }; typedef ::testing::Types<TestParams<2> > BitVectorTypes; TYPED_TEST_SUITE(BitVectorTest, BitVectorTypes); TYPED_TEST(BitVectorTest, resize) { typename TestFixture::bit_vector_t bit_vector; size_t size = 2357; double elements_per_byte = 8 / bit_vector.BIT_COUNT; bit_vector.resize(size); ASSERT_EQ(bit_vector.size(), size); ASSERT_EQ(bit_vector.get_data().length(), static_cast<uint64_t>(std::ceil( size / elements_per_byte))); } TYPED_TEST(BitVectorTest, clear) { typename TestFixture::bit_vector_t bit_vector; bit_vector.resize(123); bit_vector.clear(); ASSERT_EQ(0ull, bit_vector.size()); ASSERT_EQ(0ull, bit_vector.get_data().length()); } TYPED_TEST(BitVectorTest, bit_order) { typename TestFixture::bit_vector_t bit_vector; bit_vector.resize(1); uint8_t value = 1; bit_vector[0] = value; value <<= (8 - bit_vector.BIT_COUNT); ASSERT_EQ(value, bit_vector.get_data()[0]); } TYPED_TEST(BitVectorTest, get_set) { typename TestFixture::bit_vector_t bit_vector; std::vector<uint64_t> ref; uint64_t radix = 1 << bit_vector.BIT_COUNT; size_t size = 1024; bit_vector.resize(size); ref.resize(size); for (size_t i = 0; i < size; ++i) { uint64_t v = rand() % radix; ref[i] = v; bit_vector[i] = v; } const typename TestFixture::bit_vector_t &const_bit_vector(bit_vector); for (size_t i = 0; i < size; ++i) { ASSERT_EQ(ref[i], bit_vector[i]); ASSERT_EQ(ref[i], const_bit_vector[i]); } } TYPED_TEST(BitVectorTest, get_buffer_extents) { typename TestFixture::bit_vector_t bit_vector; uint64_t element_count = 2 * bit_vector.BLOCK_SIZE + 51; uint64_t elements_per_byte = 8 / bit_vector.BIT_COUNT; bit_vector.resize(element_count * elements_per_byte); uint64_t offset = (bit_vector.BLOCK_SIZE + 11) * elements_per_byte; uint64_t length = (bit_vector.BLOCK_SIZE + 31) * elements_per_byte; uint64_t data_byte_offset; uint64_t object_byte_offset; uint64_t byte_length; bit_vector.get_data_extents(offset, length, &data_byte_offset, &object_byte_offset, &byte_length); ASSERT_EQ(bit_vector.BLOCK_SIZE, data_byte_offset); ASSERT_EQ(bit_vector.BLOCK_SIZE + (element_count % bit_vector.BLOCK_SIZE), byte_length); bit_vector.get_data_extents(1, 1, &data_byte_offset, &object_byte_offset, &byte_length); ASSERT_EQ(0U, data_byte_offset); ASSERT_EQ(bit_vector.get_header_length(), object_byte_offset); ASSERT_EQ(bit_vector.BLOCK_SIZE, byte_length); } TYPED_TEST(BitVectorTest, get_header_length) { typename TestFixture::bit_vector_t bit_vector; bufferlist bl; bit_vector.encode_header(bl); ASSERT_EQ(bl.length(), bit_vector.get_header_length()); } TYPED_TEST(BitVectorTest, get_footer_offset) { typename TestFixture::bit_vector_t bit_vector; bit_vector.resize(5111); uint64_t data_byte_offset; uint64_t object_byte_offset; uint64_t byte_length; bit_vector.get_data_extents(0, bit_vector.size(), &data_byte_offset, &object_byte_offset, &byte_length); ASSERT_EQ(bit_vector.get_header_length() + byte_length, bit_vector.get_footer_offset()); } TYPED_TEST(BitVectorTest, partial_decode_encode) { typename TestFixture::bit_vector_t bit_vector; uint64_t elements_per_byte = 8 / bit_vector.BIT_COUNT; bit_vector.resize(9161 * elements_per_byte); for (uint64_t i = 0; i < bit_vector.size(); ++i) { bit_vector[i] = i % 4; } bufferlist bl; encode(bit_vector, bl); bit_vector.clear(); bufferlist header_bl; header_bl.substr_of(bl, 0, bit_vector.get_header_length()); auto header_it = header_bl.cbegin(); bit_vector.decode_header(header_it); uint64_t object_byte_offset; uint64_t byte_length; bit_vector.get_header_crc_extents(&object_byte_offset, &byte_length); ASSERT_EQ(bit_vector.get_footer_offset() + 4, object_byte_offset); ASSERT_EQ(4ULL, byte_length); typedef std::pair<uint64_t, uint64_t> Extent; typedef std::list<Extent> Extents; Extents extents = boost::assign::list_of( std::make_pair(0, 1))( std::make_pair((bit_vector.BLOCK_SIZE * elements_per_byte) - 2, 4))( std::make_pair((bit_vector.BLOCK_SIZE * elements_per_byte) + 2, 2))( std::make_pair((2 * bit_vector.BLOCK_SIZE * elements_per_byte) - 2, 4))( std::make_pair((2 * bit_vector.BLOCK_SIZE * elements_per_byte) + 2, 2))( std::make_pair(2, 2 * bit_vector.BLOCK_SIZE)); for (Extents::iterator it = extents.begin(); it != extents.end(); ++it) { bufferlist footer_bl; uint64_t footer_byte_offset; uint64_t footer_byte_length; bit_vector.get_data_crcs_extents(it->first, it->second, &footer_byte_offset, &footer_byte_length); ASSERT_TRUE(footer_byte_offset + footer_byte_length <= bl.length()); footer_bl.substr_of(bl, footer_byte_offset, footer_byte_length); auto footer_it = footer_bl.cbegin(); bit_vector.decode_data_crcs(footer_it, it->first); uint64_t element_offset = it->first; uint64_t element_length = it->second; uint64_t data_byte_offset; bit_vector.get_data_extents(element_offset, element_length, &data_byte_offset, &object_byte_offset, &byte_length); bufferlist data_bl; data_bl.substr_of(bl, bit_vector.get_header_length() + data_byte_offset, byte_length); auto data_it = data_bl.cbegin(); bit_vector.decode_data(data_it, data_byte_offset); data_bl.clear(); bit_vector.encode_data(data_bl, data_byte_offset, byte_length); footer_bl.clear(); bit_vector.encode_data_crcs(footer_bl, it->first, it->second); bufferlist updated_bl; updated_bl.substr_of(bl, 0, bit_vector.get_header_length() + data_byte_offset); updated_bl.append(data_bl); if (data_byte_offset + byte_length < bit_vector.get_footer_offset()) { uint64_t tail_data_offset = bit_vector.get_header_length() + data_byte_offset + byte_length; data_bl.substr_of(bl, tail_data_offset, bit_vector.get_footer_offset() - tail_data_offset); updated_bl.append(data_bl); } bufferlist full_footer; full_footer.substr_of(bl, bit_vector.get_footer_offset(), footer_byte_offset - bit_vector.get_footer_offset()); full_footer.append(footer_bl); if (footer_byte_offset + footer_byte_length < bl.length()) { bufferlist footer_bit; auto footer_offset = footer_byte_offset + footer_byte_length; footer_bit.substr_of(bl, footer_offset, bl.length() - footer_offset); full_footer.append(footer_bit); } updated_bl.append(full_footer); ASSERT_EQ(bl, updated_bl); auto updated_it = updated_bl.cbegin(); decode(bit_vector, updated_it); } } TYPED_TEST(BitVectorTest, header_crc) { typename TestFixture::bit_vector_t bit_vector; bufferlist header; bit_vector.encode_header(header); bufferlist footer; bit_vector.encode_footer(footer); auto it = footer.cbegin(); bit_vector.decode_footer(it); bit_vector.resize(1); bit_vector.encode_header(header); it = footer.begin(); ASSERT_THROW(bit_vector.decode_footer(it), buffer::malformed_input); } TYPED_TEST(BitVectorTest, data_crc) { typename TestFixture::bit_vector_t bit_vector1; typename TestFixture::bit_vector_t bit_vector2; uint64_t elements_per_byte = 8 / bit_vector1.BIT_COUNT; bit_vector1.resize((bit_vector1.BLOCK_SIZE + 1) * elements_per_byte); bit_vector2.resize((bit_vector2.BLOCK_SIZE + 1) * elements_per_byte); uint64_t data_byte_offset; uint64_t object_byte_offset; uint64_t byte_length; bit_vector1.get_data_extents(0, bit_vector1.size(), &data_byte_offset, &object_byte_offset, &byte_length); bufferlist data; bit_vector1.encode_data(data, data_byte_offset, byte_length); auto data_it = data.cbegin(); bit_vector1.decode_data(data_it, data_byte_offset); bit_vector2[bit_vector2.size() - 1] = 1; bufferlist dummy_data; bit_vector2.encode_data(dummy_data, data_byte_offset, byte_length); data_it = data.begin(); ASSERT_THROW(bit_vector2.decode_data(data_it, data_byte_offset), buffer::malformed_input); } TYPED_TEST(BitVectorTest, iterator) { typename TestFixture::bit_vector_t bit_vector; uint64_t radix = 1 << bit_vector.BIT_COUNT; uint64_t size = 25 * (1ULL << 20); uint64_t offset = 0; // create fragmented in-memory bufferlist layout uint64_t resize = 0; while (resize < size) { resize += 4096; if (resize > size) { resize = size; } bit_vector.resize(resize); } for (auto it = bit_vector.begin(); it != bit_vector.end(); ++it, ++offset) { *it = offset % radix; } offset = 123; auto end_it = bit_vector.begin() + (size - 1024); for (auto it = bit_vector.begin() + offset; it != end_it; ++it, ++offset) { ASSERT_EQ(offset % radix, *it); } }
9,607
30.093851
80
cc
null
ceph-main/src/test/common/test_blkdev.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <string.h> #include <errno.h> #include <stdlib.h> #include <linux/kdev_t.h> #include "include/types.h" #include "common/blkdev.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include <iostream> using namespace std; using namespace testing; class MockBlkDev : public BlkDev { public: // pass 0 as fd, so it won't try to use the empty devname MockBlkDev() : BlkDev(0) {}; virtual ~MockBlkDev() {} MOCK_CONST_METHOD0(sysfsdir, const char*()); MOCK_CONST_METHOD2(wholedisk, int(char* device, size_t max)); }; class BlockDevTest : public ::testing::Test { public: string *root; protected: virtual void SetUp() { const char *sda_name = "sda"; const char *sdb_name = "sdb"; const char* env = getenv("CEPH_ROOT"); ASSERT_NE(env, nullptr) << "Environment Variable CEPH_ROOT not found!"; root = new string(env); *root += "/src/test/common/test_blkdev_sys_block/sys"; EXPECT_CALL(sda, sysfsdir()) .WillRepeatedly(Return(root->c_str())); EXPECT_CALL(sda, wholedisk(NotNull(), Ge(0ul))) .WillRepeatedly( DoAll( SetArrayArgument<0>(sda_name, sda_name + strlen(sda_name) + 1), Return(0))); EXPECT_CALL(sdb, sysfsdir()) .WillRepeatedly(Return(root->c_str())); EXPECT_CALL(sdb, wholedisk(NotNull(), Ge(0ul))) .WillRepeatedly( DoAll( SetArrayArgument<0>(sdb_name, sdb_name + strlen(sdb_name) + 1), Return(0))); } virtual void TearDown() { delete root; } MockBlkDev sda, sdb; }; TEST_F(BlockDevTest, device_model) { char model[1000] = {0}; int rc = sda.model(model, sizeof(model)); ASSERT_EQ(0, rc); ASSERT_STREQ(model, "myfancymodel"); } TEST_F(BlockDevTest, discard) { EXPECT_TRUE(sda.support_discard()); EXPECT_TRUE(sdb.support_discard()); } TEST_F(BlockDevTest, is_rotational) { EXPECT_FALSE(sda.is_rotational()); EXPECT_TRUE(sdb.is_rotational()); } TEST(blkdev, _decode_model_enc) { const char *foo[][2] = { { "WDC\\x20WDS200T2B0A-00SM50\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20\\x20", "WDC_WDS200T2B0A-00SM50" }, { 0, 0}, }; for (unsigned i = 0; foo[i][0]; ++i) { std::string d = _decode_model_enc(foo[i][0]); cout << " '" << foo[i][0] << "' -> '" << d << "'" << std::endl; ASSERT_EQ(std::string(foo[i][1]), d); } } TEST(blkdev, get_device_id) { // this doesn't really test anything; it's just a way to exercise the // get_device_id() code. for (char c = 'a'; c < 'z'; ++c) { char devname[4] = {'s', 'd', c, 0}; std::string err; auto i = get_device_id(devname, &err); cout << "devname " << devname << " -> '" << i << "' (" << err << ")" << std::endl; } }
2,842
23.721739
125
cc
null
ceph-main/src/test/common/test_blocked_completion.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <boost/asio.hpp> #include <boost/system/error_code.hpp> #include <gtest/gtest.h> #include "common/async/bind_handler.h" #include "common/async/blocked_completion.h" #include "common/async/forward_handler.h" using namespace std::literals; namespace ba = boost::asio; namespace bs = boost::system; namespace ca = ceph::async; class context_thread { ba::io_context c; ba::executor_work_guard<ba::io_context::executor_type> guard; std::thread th; public: context_thread() noexcept : guard(ba::make_work_guard(c)), th([this]() noexcept { c.run();}) {} ~context_thread() { guard.reset(); th.join(); } ba::io_context& io_context() noexcept { return c; } ba::io_context::executor_type get_executor() noexcept { return c.get_executor(); } }; struct move_only { move_only() = default; move_only(move_only&&) = default; move_only& operator=(move_only&&) = default; move_only(const move_only&) = delete; move_only& operator=(const move_only&) = delete; }; struct defaultless { int a; defaultless(int a) : a(a) {} }; template<typename Executor, typename CompletionToken, typename... Args> auto id(const Executor& executor, CompletionToken&& token, Args&& ...args) { ba::async_completion<CompletionToken, void(Args...)> init(token); auto a = ba::get_associated_allocator(init.completion_handler); executor.post(ca::forward_handler( ca::bind_handler(std::move(init.completion_handler), std::forward<Args>(args)...)), a); return init.result.get(); } TEST(BlockedCompletion, Void) { context_thread t; ba::post(t.get_executor(), ca::use_blocked); } TEST(BlockedCompletion, Timer) { context_thread t; ba::steady_timer timer(t.io_context(), 50ms); timer.async_wait(ca::use_blocked); } TEST(BlockedCompletion, NoError) { context_thread t; ba::steady_timer timer(t.io_context(), 1s); bs::error_code ec; EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{})); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{})); EXPECT_FALSE(ec); int i; EXPECT_NO_THROW(i = id(t.get_executor(), ca::use_blocked, bs::error_code{}, 5)); ASSERT_EQ(5, i); EXPECT_NO_THROW(i = id(t.get_executor(), ca::use_blocked[ec], bs::error_code{}, 7)); EXPECT_FALSE(ec); ASSERT_EQ(7, i); float j; EXPECT_NO_THROW(std::tie(i, j) = id(t.get_executor(), ca::use_blocked, 9, 3.5)); ASSERT_EQ(9, i); ASSERT_EQ(3.5, j); EXPECT_NO_THROW(std::tie(i, j) = id(t.get_executor(), ca::use_blocked[ec], 11, 2.25)); EXPECT_FALSE(ec); ASSERT_EQ(11, i); ASSERT_EQ(2.25, j); } TEST(BlockedCompletion, AnError) { context_thread t; ba::steady_timer timer(t.io_context(), 1s); bs::error_code ec; EXPECT_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{EDOM, bs::system_category()}), bs::system_error); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{EDOM, bs::system_category()})); EXPECT_EQ(bs::error_code(EDOM, bs::system_category()), ec); EXPECT_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{EDOM, bs::system_category()}, 5), bs::system_error); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{EDOM, bs::system_category()}, 5)); EXPECT_EQ(bs::error_code(EDOM, bs::system_category()), ec); EXPECT_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{EDOM, bs::system_category()}, 5, 3), bs::system_error); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{EDOM, bs::system_category()}, 5, 3)); EXPECT_EQ(bs::error_code(EDOM, bs::system_category()), ec); } TEST(BlockedCompletion, MoveOnly) { context_thread t; ba::steady_timer timer(t.io_context(), 1s); bs::error_code ec; EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{}, move_only{})); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{}, move_only{})); EXPECT_FALSE(ec); { auto [i, j] = id(t.get_executor(), ca::use_blocked, move_only{}, 5); EXPECT_EQ(j, 5); } { auto [i, j] = id(t.get_executor(), ca::use_blocked[ec], move_only{}, 5); EXPECT_EQ(j, 5); } EXPECT_FALSE(ec); EXPECT_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{EDOM, bs::system_category()}, move_only{}), bs::system_error); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{EDOM, bs::system_category()}, move_only{})); EXPECT_EQ(bs::error_code(EDOM, bs::system_category()), ec); EXPECT_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{EDOM, bs::system_category()}, move_only{}, 3), bs::system_error); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{EDOM, bs::system_category()}, move_only{}, 3)); EXPECT_EQ(bs::error_code(EDOM, bs::system_category()), ec); } TEST(BlockedCompletion, DefaultLess) { context_thread t; ba::steady_timer timer(t.io_context(), 1s); bs::error_code ec; { auto l = id(t.get_executor(), ca::use_blocked, bs::error_code{}, defaultless{5}); EXPECT_EQ(5, l.a); } { auto l = id(t.get_executor(), ca::use_blocked[ec], bs::error_code{}, defaultless{7}); EXPECT_EQ(7, l.a); } { auto [i, j] = id(t.get_executor(), ca::use_blocked, defaultless{3}, 5); EXPECT_EQ(i.a, 3); EXPECT_EQ(j, 5); } { auto [i, j] = id(t.get_executor(), ca::use_blocked[ec], defaultless{3}, 5); EXPECT_EQ(i.a, 3); EXPECT_EQ(j, 5); } EXPECT_FALSE(ec); EXPECT_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{EDOM, bs::system_category()}, move_only{}), bs::system_error); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{EDOM, bs::system_category()}, move_only{})); EXPECT_EQ(bs::error_code(EDOM, bs::system_category()), ec); EXPECT_THROW(id(t.get_executor(), ca::use_blocked, bs::error_code{EDOM, bs::system_category()}, move_only{}, 3), bs::system_error); EXPECT_NO_THROW(id(t.get_executor(), ca::use_blocked[ec], bs::error_code{EDOM, bs::system_category()}, move_only{}, 3)); EXPECT_EQ(bs::error_code(EDOM, bs::system_category()), ec); }
6,678
27.063025
89
cc
null
ceph-main/src/test/common/test_bloom_filter.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 Inktank <[email protected]> * * LGPL-2.1 (see COPYING-LGPL2.1) or later */ #include <iostream> #include <gtest/gtest.h> #include "include/stringify.h" #include "common/bloom_filter.hpp" TEST(BloomFilter, Basic) { bloom_filter bf(10, .1, 1); bf.insert("foo"); bf.insert("bar"); ASSERT_TRUE(bf.contains("foo")); ASSERT_TRUE(bf.contains("bar")); ASSERT_EQ(2U, bf.element_count()); } TEST(BloomFilter, Empty) { bloom_filter bf; for (int i=0; i<100; ++i) { ASSERT_FALSE(bf.contains((uint32_t) i)); ASSERT_FALSE(bf.contains(stringify(i))); } } TEST(BloomFilter, Sweep) { std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); std::cout << "# max\tfpp\tactual\tsize\tB/insert" << std::endl; for (int ex = 3; ex < 12; ex += 2) { for (float fpp = .001; fpp < .5; fpp *= 4.0) { int max = 2 << ex; bloom_filter bf(max, fpp, 1); bf.insert("foo"); bf.insert("bar"); ASSERT_TRUE(bf.contains("foo")); ASSERT_TRUE(bf.contains("bar")); for (int n = 0; n < max; n++) bf.insert("ok" + stringify(n)); int test = max * 100; int hit = 0; for (int n = 0; n < test; n++) if (bf.contains("asdf" + stringify(n))) hit++; ASSERT_TRUE(bf.contains("foo")); ASSERT_TRUE(bf.contains("bar")); double actual = (double)hit / (double)test; bufferlist bl; encode(bf, bl); double byte_per_insert = (double)bl.length() / (double)max; std::cout << max << "\t" << fpp << "\t" << actual << "\t" << bl.length() << "\t" << byte_per_insert << std::endl; ASSERT_TRUE(actual < fpp * 10); } } } TEST(BloomFilter, SweepInt) { unsigned int seed = 0; std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); std::cout << "# max\tfpp\tactual\tsize\tB/insert\tdensity\tapprox_element_count" << std::endl; for (int ex = 3; ex < 12; ex += 2) { for (float fpp = .001; fpp < .5; fpp *= 4.0) { int max = 2 << ex; bloom_filter bf(max, fpp, 1); bf.insert("foo"); bf.insert("bar"); ASSERT_TRUE(123); ASSERT_TRUE(456); // In Ceph code, the uint32_t input routines to the bloom filter // are used with hash values that are uniformly distributed over // the uint32_t range. To model this behavior in the test, we // pass in values generated by a pseudo-random generator. // To make the test reproducible anyway, use a fixed seed here, // but a different one in each instance. srand(seed++); for (int n = 0; n < max; n++) bf.insert((uint32_t) rand()); int test = max * 100; int hit = 0; for (int n = 0; n < test; n++) if (bf.contains((uint32_t) rand())) hit++; ASSERT_TRUE(123); ASSERT_TRUE(456); double actual = (double)hit / (double)test; bufferlist bl; encode(bf, bl); double byte_per_insert = (double)bl.length() / (double)max; std::cout << max << "\t" << fpp << "\t" << actual << "\t" << bl.length() << "\t" << byte_per_insert << "\t" << bf.density() << "\t" << bf.approx_unique_element_count() << std::endl; ASSERT_TRUE(actual < fpp * 3); ASSERT_TRUE(actual > fpp / 3); ASSERT_TRUE(bf.density() > 0.40); ASSERT_TRUE(bf.density() < 0.60); } } } TEST(BloomFilter, CompressibleSweep) { unsigned int seed = 0; std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); std::cout << "# max\tins\test ins\tafter\ttgtfpp\tactual\tsize\tb/elem\n"; float fpp = .01; int max = 1024; for (int div = 1; div < 10; div++) { compressible_bloom_filter bf(max, fpp, 1); // See the comment in SweepInt. srand(seed++); std::vector<uint32_t> values; int t = max/div; for (int n = 0; n < t; n++) { uint32_t val = (uint32_t) rand(); bf.insert(val); values.push_back(val); } unsigned est = bf.approx_unique_element_count(); if (div > 1) bf.compress(1.0 / div); for (auto val : values) ASSERT_TRUE(bf.contains(val)); int test = max * 100; int hit = 0; for (int n = 0; n < test; n++) if (bf.contains((uint32_t) rand())) hit++; double actual = (double)hit / (double)test; bufferlist bl; encode(bf, bl); double byte_per_insert = (double)bl.length() / (double)max; unsigned est_after = bf.approx_unique_element_count(); std::cout << max << "\t" << t << "\t" << est << "\t" << est_after << "\t" << fpp << "\t" << actual << "\t" << bl.length() << "\t" << byte_per_insert << std::endl; ASSERT_TRUE(actual < fpp * 2.0); ASSERT_TRUE(actual > fpp / 2.0); ASSERT_TRUE(est_after < est * 2); ASSERT_TRUE(est_after > est / 2); } } TEST(BloomFilter, BinSweep) { std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); int total_max = 16384; float total_fpp = .01; std::cout << "total_inserts " << total_max << " target-fpp " << total_fpp << std::endl; for (int bins = 1; bins < 16; ++bins) { int max = total_max / bins; float fpp = total_fpp / bins;//pow(total_fpp, bins); std::vector<std::unique_ptr<bloom_filter>> ls; bufferlist bl; for (int i=0; i<bins; i++) { ls.push_back(std::make_unique<bloom_filter>(max, fpp, i)); for (int j=0; j<max; j++) { ls.back()->insert(10000 * (i+1) + j); } encode(*ls.front(), bl); } int hit = 0; int test = max * 100; for (int i=0; i<test; ++i) { for (std::vector<std::unique_ptr<bloom_filter>>::iterator j = ls.begin(); j != ls.end(); ++j) { if ((*j)->contains(i * 732)) { // note: sequential i does not work here; the intenral int hash is weak!! hit++; break; } } } double actual = (double)hit / (double)test; std::cout << "bins " << bins << " bin-max " << max << " bin-fpp " << fpp << " actual-fpp " << actual << " total-size " << bl.length() << std::endl; } } // disable these tests; doing dual insertions in consecutive filters // appears to be equivalent to doing a single insertion in a bloom // filter that is twice as big. #if 0 // test the fpp over a sequence of bloom filters, each with unique // items inserted into it. // // we expect: actual_fpp = num_filters * per_filter_fpp TEST(BloomFilter, Sequence) { int max = 1024; double fpp = .01; for (int seq = 2; seq <= 128; seq *= 2) { std::vector<bloom_filter*> ls; for (int i=0; i<seq; i++) { ls.push_back(new bloom_filter(max*2, fpp, i)); for (int j=0; j<max; j++) { ls.back()->insert("ok" + stringify(j) + "_" + stringify(i)); if (ls.size() > 1) ls[ls.size() - 2]->insert("ok" + stringify(j) + "_" + stringify(i)); } } int hit = 0; int test = max * 100; for (int i=0; i<test; ++i) { for (std::vector<bloom_filter*>::iterator j = ls.begin(); j != ls.end(); ++j) { if ((*j)->contains("bad" + stringify(i))) { hit++; break; } } } double actual = (double)hit / (double)test; std::cout << "seq " << seq << " max " << max << " fpp " << fpp << " actual " << actual << std::endl; } } // test the ffp over a sequence of bloom filters, where actual values // are always inserted into a consecutive pair of filters. in order // to have a false positive, we need to falsely match two consecutive // filters. // // we expect: actual_fpp = num_filters * per_filter_fpp^2 TEST(BloomFilter, SequenceDouble) { int max = 1024; double fpp = .01; for (int seq = 2; seq <= 128; seq *= 2) { std::vector<bloom_filter*> ls; for (int i=0; i<seq; i++) { ls.push_back(new bloom_filter(max*2, fpp, i)); for (int j=0; j<max; j++) { ls.back()->insert("ok" + stringify(j) + "_" + stringify(i)); if (ls.size() > 1) ls[ls.size() - 2]->insert("ok" + stringify(j) + "_" + stringify(i)); } } int hit = 0; int test = max * 100; int run = 0; for (int i=0; i<test; ++i) { for (std::vector<bloom_filter*>::iterator j = ls.begin(); j != ls.end(); ++j) { if ((*j)->contains("bad" + stringify(i))) { run++; if (run >= 2) { hit++; break; } } else { run = 0; } } } double actual = (double)hit / (double)test; std::cout << "seq " << seq << " max " << max << " fpp " << fpp << " actual " << actual << " expected " << (fpp*fpp*(double)seq) << std::endl; } } #endif TEST(BloomFilter, Assignement) { bloom_filter bf1(10, .1, 1), bf2; bf1.insert("foo"); bf2 = bf1; bf1.insert("bar"); ASSERT_TRUE(bf2.contains("foo")); ASSERT_FALSE(bf2.contains("bar")); ASSERT_EQ(2U, bf1.element_count()); ASSERT_EQ(1U, bf2.element_count()); }
8,924
26.546296
119
cc
null
ceph-main/src/test/common/test_bounded_key_counter.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2015 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/bounded_key_counter.h" #include <gtest/gtest.h> namespace { // call get_highest() and return the number of callbacks template <typename Key, typename Count> size_t count_highest(BoundedKeyCounter<Key, Count>& counter, size_t count) { size_t callbacks = 0; counter.get_highest(count, [&callbacks] (const Key& key, Count count) { ++callbacks; }); return callbacks; } // call get_highest() and return the key/value pairs as a vector template <typename Key, typename Count, typename Vector = std::vector<std::pair<Key, Count>>> Vector get_highest(BoundedKeyCounter<Key, Count>& counter, size_t count) { Vector results; counter.get_highest(count, [&results] (const Key& key, Count count) { results.emplace_back(key, count); }); return results; } } // anonymous namespace TEST(BoundedKeyCounter, Insert) { BoundedKeyCounter<int, int> counter(2); EXPECT_EQ(1, counter.insert(0)); // insert new key EXPECT_EQ(2, counter.insert(0)); // increment counter EXPECT_EQ(7, counter.insert(0, 5)); // add 5 to counter EXPECT_EQ(1, counter.insert(1)); // insert new key EXPECT_EQ(0, counter.insert(2)); // reject new key } TEST(BoundedKeyCounter, Erase) { BoundedKeyCounter<int, int> counter(10); counter.erase(0); // ok to erase nonexistent key EXPECT_EQ(1, counter.insert(1, 1)); EXPECT_EQ(2, counter.insert(2, 2)); EXPECT_EQ(3, counter.insert(3, 3)); counter.erase(2); counter.erase(1); counter.erase(3); counter.erase(3); EXPECT_EQ(0u, count_highest(counter, 10)); } TEST(BoundedKeyCounter, Size) { BoundedKeyCounter<int, int> counter(4); EXPECT_EQ(0u, counter.size()); EXPECT_EQ(1, counter.insert(1, 1)); EXPECT_EQ(1u, counter.size()); EXPECT_EQ(2, counter.insert(2, 2)); EXPECT_EQ(2u, counter.size()); EXPECT_EQ(3, counter.insert(3, 3)); EXPECT_EQ(3u, counter.size()); EXPECT_EQ(4, counter.insert(4, 4)); EXPECT_EQ(4u, counter.size()); EXPECT_EQ(0, counter.insert(5, 5)); // reject new key EXPECT_EQ(4u, counter.size()); // size unchanged EXPECT_EQ(5, counter.insert(4, 1)); // update existing key EXPECT_EQ(4u, counter.size()); // size unchanged counter.erase(2); EXPECT_EQ(3u, counter.size()); counter.erase(2); // erase duplicate EXPECT_EQ(3u, counter.size()); // size unchanged counter.erase(4); EXPECT_EQ(2u, counter.size()); counter.erase(1); EXPECT_EQ(1u, counter.size()); counter.erase(3); EXPECT_EQ(0u, counter.size()); EXPECT_EQ(6, counter.insert(6, 6)); EXPECT_EQ(1u, counter.size()); counter.clear(); EXPECT_EQ(0u, counter.size()); } TEST(BoundedKeyCounter, GetHighest) { BoundedKeyCounter<int, int> counter(10); using Vector = std::vector<std::pair<int, int>>; EXPECT_EQ(0u, count_highest(counter, 0)); // ok to request 0 EXPECT_EQ(0u, count_highest(counter, 10)); // empty EXPECT_EQ(0u, count_highest(counter, 999)); // ok to request count >> 10 EXPECT_EQ(1, counter.insert(1, 1)); EXPECT_EQ(Vector({{1,1}}), get_highest(counter, 10)); EXPECT_EQ(2, counter.insert(2, 2)); EXPECT_EQ(Vector({{2,2},{1,1}}), get_highest(counter, 10)); EXPECT_EQ(3, counter.insert(3, 3)); EXPECT_EQ(Vector({{3,3},{2,2},{1,1}}), get_highest(counter, 10)); EXPECT_EQ(3, counter.insert(4, 3)); // insert duplicated count=3 // still returns 4 entries (but order of {3,3} and {4,3} is unspecified) EXPECT_EQ(4u, count_highest(counter, 10)); counter.erase(3); EXPECT_EQ(Vector({{4,3},{2,2},{1,1}}), get_highest(counter, 10)); EXPECT_EQ(0u, count_highest(counter, 0)); // requesting 0 still returns 0 } TEST(BoundedKeyCounter, Clear) { BoundedKeyCounter<int, int> counter(2); EXPECT_EQ(1, counter.insert(0)); // insert new key EXPECT_EQ(1, counter.insert(1)); // insert new key EXPECT_EQ(2u, count_highest(counter, 2)); // return 2 entries counter.clear(); EXPECT_EQ(0u, count_highest(counter, 2)); // return 0 entries EXPECT_EQ(1, counter.insert(1)); // insert new key EXPECT_EQ(1, counter.insert(2)); // insert new unique key EXPECT_EQ(2u, count_highest(counter, 2)); // return 2 entries } // tests for partial sort and invalidation TEST(BoundedKeyCounter, GetNumSorted) { struct MockCounter : public BoundedKeyCounter<int, int> { using BoundedKeyCounter<int, int>::BoundedKeyCounter; // expose as public for testing sort invalidations using BoundedKeyCounter<int, int>::get_num_sorted; }; MockCounter counter(10); EXPECT_EQ(0u, counter.get_num_sorted()); EXPECT_EQ(0u, count_highest(counter, 10)); EXPECT_EQ(0u, counter.get_num_sorted()); EXPECT_EQ(2, counter.insert(2, 2)); EXPECT_EQ(3, counter.insert(3, 3)); EXPECT_EQ(4, counter.insert(4, 4)); EXPECT_EQ(0u, counter.get_num_sorted()); EXPECT_EQ(0u, count_highest(counter, 0)); EXPECT_EQ(0u, counter.get_num_sorted()); EXPECT_EQ(1u, count_highest(counter, 1)); EXPECT_EQ(1u, counter.get_num_sorted()); EXPECT_EQ(2u, count_highest(counter, 2)); EXPECT_EQ(2u, counter.get_num_sorted()); EXPECT_EQ(3u, count_highest(counter, 10)); EXPECT_EQ(3u, counter.get_num_sorted()); EXPECT_EQ(1, counter.insert(1, 1)); // insert at bottom does not invalidate EXPECT_EQ(3u, counter.get_num_sorted()); EXPECT_EQ(4u, count_highest(counter, 10)); EXPECT_EQ(4u, counter.get_num_sorted()); EXPECT_EQ(5, counter.insert(5, 5)); // insert at top invalidates sort EXPECT_EQ(0u, counter.get_num_sorted()); EXPECT_EQ(0u, count_highest(counter, 0)); EXPECT_EQ(0u, counter.get_num_sorted()); EXPECT_EQ(1u, count_highest(counter, 1)); EXPECT_EQ(1u, counter.get_num_sorted()); EXPECT_EQ(2u, count_highest(counter, 2)); EXPECT_EQ(2u, counter.get_num_sorted()); EXPECT_EQ(3u, count_highest(counter, 3)); EXPECT_EQ(3u, counter.get_num_sorted()); EXPECT_EQ(4u, count_highest(counter, 4)); EXPECT_EQ(4u, counter.get_num_sorted()); EXPECT_EQ(5u, count_highest(counter, 10)); EXPECT_EQ(5u, counter.get_num_sorted()); // updating an existing counter only invalidates entries <= that counter EXPECT_EQ(2, counter.insert(1)); // invalidates {1,2} and {2,2} EXPECT_EQ(3u, counter.get_num_sorted()); EXPECT_EQ(5u, count_highest(counter, 10)); EXPECT_EQ(5u, counter.get_num_sorted()); counter.clear(); // invalidates sort EXPECT_EQ(0u, counter.get_num_sorted()); }
6,744
32.557214
77
cc
null
ceph-main/src/test/common/test_cdc.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <vector> #include <cstring> #include <random> #include "include/types.h" #include "include/buffer.h" #include "common/CDC.h" #include "gtest/gtest.h" using namespace std; class CDCTest : public ::testing::Test, public ::testing::WithParamInterface<const char*> { public: std::unique_ptr<CDC> cdc; CDCTest() { auto plugin = GetParam(); cdc = CDC::create(plugin, 18); } }; TEST_P(CDCTest, insert_front) { if (GetParam() == "fixed"s) return; for (int frontlen = 1; frontlen < 163840; frontlen *= 3) { bufferlist bl1, bl2; generate_buffer(4*1024*1024, &bl1); generate_buffer(frontlen, &bl2); bl2.append(bl1); bl2.rebuild(); vector<pair<uint64_t, uint64_t>> chunks1, chunks2; cdc->calc_chunks(bl1, &chunks1); cdc->calc_chunks(bl2, &chunks2); cout << "1: " << chunks1 << std::endl; cout << "2: " << chunks2 << std::endl; ASSERT_GE(chunks2.size(), chunks1.size()); int match = 0; for (unsigned i = 0; i < chunks1.size(); ++i) { unsigned j = i + (chunks2.size() - chunks1.size()); if (chunks1[i].first + frontlen == chunks2[j].first && chunks1[i].second == chunks2[j].second) { match++; } } ASSERT_GE(match, chunks1.size() - 1); } } TEST_P(CDCTest, insert_middle) { if (GetParam() == "fixed"s) return; for (int frontlen = 1; frontlen < 163840; frontlen *= 3) { bufferlist bl1, bl2; generate_buffer(4*1024*1024, &bl1); bufferlist f, m, e; generate_buffer(frontlen, &m); f.substr_of(bl1, 0, bl1.length() / 2); e.substr_of(bl1, bl1.length() / 2, bl1.length() / 2); bl2 = f; bl2.append(m); bl2.append(e); bl2.rebuild(); vector<pair<uint64_t, uint64_t>> chunks1, chunks2; cdc->calc_chunks(bl1, &chunks1); cdc->calc_chunks(bl2, &chunks2); cout << "1: " << chunks1 << std::endl; cout << "2: " << chunks2 << std::endl; ASSERT_GE(chunks2.size(), chunks1.size()); int match = 0; unsigned i; for (i = 0; i < chunks1.size()/2; ++i) { unsigned j = i; if (chunks1[i].first == chunks2[j].first && chunks1[i].second == chunks2[j].second) { match++; } } for (; i < chunks1.size(); ++i) { unsigned j = i + (chunks2.size() - chunks1.size()); if (chunks1[i].first + frontlen == chunks2[j].first && chunks1[i].second == chunks2[j].second) { match++; } } ASSERT_GE(match, chunks1.size() - 2); } } TEST_P(CDCTest, specific_result) { map<string,vector<pair<uint64_t,uint64_t>>> expected = { {"fixed", { {0, 262144}, {262144, 262144}, {524288, 262144}, {786432, 262144}, {1048576, 262144}, {1310720, 262144}, {1572864, 262144}, {1835008, 262144}, {2097152, 262144}, {2359296, 262144}, {2621440, 262144}, {2883584, 262144}, {3145728, 262144}, {3407872, 262144}, {3670016, 262144}, {3932160, 262144} }}, {"fastcdc", { {0, 151460}, {151460, 441676}, {593136, 407491}, {1000627, 425767}, {1426394, 602875}, {2029269, 327307}, {2356576, 155515}, {2512091, 159392}, {2671483, 829416}, {3500899, 539667}, {4040566, 153738}}}, }; bufferlist bl; generate_buffer(4*1024*1024, &bl); vector<pair<uint64_t,uint64_t>> chunks; cdc->calc_chunks(bl, &chunks); ASSERT_EQ(chunks, expected[GetParam()]); } void do_size_histogram(CDC& cdc, bufferlist& bl, map<int,int> *h) { vector<pair<uint64_t, uint64_t>> chunks; cdc.calc_chunks(bl, &chunks); uint64_t total = 0; uint64_t num = 0; for (auto& i : chunks) { //unsigned b = i.second & 0xfffff000; unsigned b = 1 << (cbits(i.second - 1)); (*h)[b]++; ++num; total += i.second; } (*h)[0] = total / num; } void print_histogram(map<int,int>& h) { cout << "size\tcount" << std::endl; for (auto i : h) { if (i.first) { cout << i.first << "\t" << i.second << std::endl; } else { cout << "avg\t" << i.second << std::endl; } } } TEST_P(CDCTest, chunk_random) { map<int,int> h; for (int i = 0; i < 32; ++i) { cout << "."; cout.flush(); bufferlist r; generate_buffer(16*1024*1024, &r, i); do_size_histogram(*cdc, r, &h); } cout << std::endl; print_histogram(h); } INSTANTIATE_TEST_SUITE_P( CDC, CDCTest, ::testing::Values( "fixed", // note: we skip most tests bc this is not content-based "fastcdc" ));
4,405
25.865854
313
cc
null
ceph-main/src/test/common/test_ceph_timer.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <chrono> #include <future> #include <vector> #include <gtest/gtest.h> #include "common/ceph_timer.h" using namespace std::literals; namespace { template<typename TC> void run_some() { static constexpr auto MAX_FUTURES = 5; ceph::timer<TC> timer; std::vector<std::future<void>> futures; for (auto i = 0; i < MAX_FUTURES; ++i) { auto t = TC::now() + 2s; std::promise<void> p; futures.push_back(p.get_future()); timer.add_event(t, [p = std::move(p)]() mutable { p.set_value(); }); } for (auto& f : futures) f.get(); } template<typename TC> void run_orderly() { ceph::timer<TC> timer; std::future<typename TC::time_point> first; std::future<typename TC::time_point> second; { std::promise<typename TC::time_point> p; second = p.get_future(); timer.add_event(4s, [p = std::move(p)]() mutable { p.set_value(TC::now()); }); } { std::promise<typename TC::time_point> p; first = p.get_future(); timer.add_event(2s, [p = std::move(p)]() mutable { p.set_value(TC::now()); }); } EXPECT_LT(first.get(), second.get()); } struct Destructo { bool armed = true; std::promise<void> p; Destructo(std::promise<void>&& p) : p(std::move(p)) {} Destructo(const Destructo&) = delete; Destructo& operator =(const Destructo&) = delete; Destructo(Destructo&& rhs) { p = std::move(rhs.p); armed = rhs.armed; rhs.armed = false; } Destructo& operator =(Destructo& rhs) { p = std::move(rhs.p); rhs.armed = false; armed = rhs.armed; rhs.armed = false; return *this; } ~Destructo() { if (armed) p.set_value(); } void operator ()() const { FAIL(); } }; template<typename TC> void cancel_all() { ceph::timer<TC> timer; static constexpr auto MAX_FUTURES = 5; std::vector<std::future<void>> futures; for (auto i = 0; i < MAX_FUTURES; ++i) { std::promise<void> p; futures.push_back(p.get_future()); timer.add_event(100s + i*1s, Destructo(std::move(p))); } timer.cancel_all_events(); for (auto& f : futures) f.get(); } template<typename TC> void cancellation() { ceph::timer<TC> timer; { std::promise<void> p; auto f = p.get_future(); auto e = timer.add_event(100s, Destructo(std::move(p))); EXPECT_TRUE(timer.cancel_event(e)); } { std::promise<void> p; auto f = p.get_future(); auto e = timer.add_event(1s, [p = std::move(p)]() mutable { p.set_value(); }); f.get(); EXPECT_FALSE(timer.cancel_event(e)); } } } TEST(RunSome, Steady) { run_some<std::chrono::steady_clock>(); } TEST(RunSome, Wall) { run_some<std::chrono::system_clock>(); } TEST(RunOrderly, Steady) { run_orderly<std::chrono::steady_clock>(); } TEST(RunOrderly, Wall) { run_orderly<std::chrono::system_clock>(); } TEST(CancelAll, Steady) { cancel_all<std::chrono::steady_clock>(); } TEST(CancelAll, Wall) { cancel_all<std::chrono::system_clock>(); }
3,547
20.634146
70
cc
null
ceph-main/src/test/common/test_config.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Cloudwatt <[email protected]> * * Author: Loic Dachary <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library Public License for more details. * * */ #include "common/config_proxy.h" #include "common/errno.h" #include "gtest/gtest.h" #include "common/hostname.h" using namespace std; extern std::string exec(const char* cmd); // defined in test_hostname.cc class test_config_proxy : public ConfigProxy, public ::testing::Test { public: test_config_proxy() : ConfigProxy{true}, Test() {} void test_expand_meta() { // successfull meta expansion $run_dir and ${run_dir} { ostringstream oss; std::string before = " BEFORE "; std::string after = " AFTER "; std::string val(before + "$run_dir${run_dir}" + after); early_expand_meta(val, &oss); EXPECT_EQ(before + "/var/run/ceph/var/run/ceph" + after, val); EXPECT_EQ("", oss.str()); } { ostringstream oss; std::string before = " BEFORE "; std::string after = " AFTER "; std::string val(before + "$$1$run_dir$2${run_dir}$3$" + after); early_expand_meta(val, &oss); EXPECT_EQ(before + "$$1/var/run/ceph$2/var/run/ceph$3$" + after, val); EXPECT_EQ("", oss.str()); } { ostringstream oss; std::string before = " BEFORE "; std::string after = " AFTER "; std::string val(before + "$host${host}" + after); early_expand_meta(val, &oss); std::string hostname = ceph_get_short_hostname(); EXPECT_EQ(before + hostname + hostname + after, val); EXPECT_EQ("", oss.str()); } // no meta expansion if variables are unknown { ostringstream oss; std::string expected = "expect $foo and ${bar} to not expand"; std::string val = expected; early_expand_meta(val, &oss); EXPECT_EQ(expected, val); EXPECT_EQ("", oss.str()); } // recursive variable expansion { std::string host = "localhost"; EXPECT_EQ(0, set_val("host", host.c_str())); std::string mon_host = "$cluster_network"; EXPECT_EQ(0, set_val("mon_host", mon_host.c_str())); std::string lockdep = "true"; EXPECT_EQ(0, set_val("lockdep", lockdep.c_str())); std::string cluster_network = "$public_network $public_network $lockdep $host"; EXPECT_EQ(0, set_val("cluster_network", cluster_network.c_str())); std::string public_network = "NETWORK"; EXPECT_EQ(0, set_val("public_network", public_network.c_str())); ostringstream oss; std::string val = "$mon_host"; early_expand_meta(val, &oss); EXPECT_EQ(public_network + " " + public_network + " " + lockdep + " " + "localhost", val); EXPECT_EQ("", oss.str()); } // variable expansion loops are non fatal { std::string mon_host = "$cluster_network"; EXPECT_EQ(0, set_val("mon_host", mon_host.c_str())); std::string cluster_network = "$public_network"; EXPECT_EQ(0, set_val("cluster_network", cluster_network.c_str())); std::string public_network = "$mon_host"; EXPECT_EQ(0, set_val("public_network", public_network.c_str())); ostringstream oss; std::string val = "$mon_host"; early_expand_meta(val, &oss); EXPECT_EQ("$mon_host", val); const char *expected_oss = "variable expansion loop at mon_host=$cluster_network\n" "expansion stack:\n" "public_network=$mon_host\n" "cluster_network=$public_network\n" "mon_host=$cluster_network\n"; EXPECT_EQ(expected_oss, oss.str()); } } }; TEST_F(test_config_proxy, expand_meta) { test_expand_meta(); } TEST(md_config_t, parse_env) { { ConfigProxy conf{false}; setenv("POD_MEMORY_REQUEST", "1", 1); conf.parse_env(CEPH_ENTITY_TYPE_OSD); } { ConfigProxy conf{false}; setenv("POD_MEMORY_REQUEST", "0", 1); conf.parse_env(CEPH_ENTITY_TYPE_OSD); } { ConfigProxy conf{false}; setenv("CEPH_KEYRING", "", 1); conf.parse_env(CEPH_ENTITY_TYPE_OSD); } } TEST(md_config_t, set_val) { int buf_size = 1024; ConfigProxy conf{false}; { char *run_dir = (char*)malloc(buf_size); EXPECT_EQ(0, conf.get_val("run_dir", &run_dir, buf_size)); EXPECT_EQ(0, conf.set_val("admin_socket", "$run_dir")); char *admin_socket = (char*)malloc(buf_size); EXPECT_EQ(0, conf.get_val("admin_socket", &admin_socket, buf_size)); EXPECT_EQ(std::string(run_dir), std::string(admin_socket)); free(run_dir); free(admin_socket); } // set_val should support SI conversion { auto expected = Option::size_t{512 << 20}; EXPECT_EQ(0, conf.set_val("mgr_osd_bytes", "512M", nullptr)); EXPECT_EQ(expected, conf.get_val<Option::size_t>("mgr_osd_bytes")); EXPECT_EQ(-EINVAL, conf.set_val("mgr_osd_bytes", "512 bits", nullptr)); EXPECT_EQ(expected, conf.get_val<Option::size_t>("mgr_osd_bytes")); } // set_val should support 1 days 2 hours 4 minutes { using namespace std::chrono; const string s{"1 days 2 hours 4 minutes"}; using days_t = duration<int, std::ratio<3600 * 24>>; auto expected = (duration_cast<seconds>(days_t{1}) + duration_cast<seconds>(hours{2}) + duration_cast<seconds>(minutes{4})); EXPECT_EQ(0, conf.set_val("mgr_tick_period", "1 days 2 hours 4 minutes", nullptr)); EXPECT_EQ(expected.count(), conf.get_val<seconds>("mgr_tick_period").count()); EXPECT_EQ(-EINVAL, conf.set_val("mgr_tick_period", "21 centuries", nullptr)); EXPECT_EQ(expected.count(), conf.get_val<seconds>("mgr_tick_period").count()); } using namespace std::chrono; using days_t = duration<int, std::ratio<3600 * 24>>; struct testcase { std::string s; std::chrono::seconds r; }; std::vector<testcase> good = { { "23"s, duration_cast<seconds>(seconds{23}) }, { " 23 "s, duration_cast<seconds>(seconds{23}) }, { " 23s "s, duration_cast<seconds>(seconds{23}) }, { " 23 s "s, duration_cast<seconds>(seconds{23}) }, { " 23 sec "s, duration_cast<seconds>(seconds{23}) }, { "23 second "s, duration_cast<seconds>(seconds{23}) }, { "23 seconds"s, duration_cast<seconds>(seconds{23}) }, { "2m5s"s, duration_cast<seconds>(seconds{2*60+5}) }, { "2 m 5 s "s, duration_cast<seconds>(seconds{2*60+5}) }, { "2 m5"s, duration_cast<seconds>(seconds{2*60+5}) }, { "2 min5"s, duration_cast<seconds>(seconds{2*60+5}) }, { "2 minutes 5"s, duration_cast<seconds>(seconds{2*60+5}) }, { "1w"s, duration_cast<seconds>(seconds{3600*24*7}) }, { "1wk"s, duration_cast<seconds>(seconds{3600*24*7}) }, { "1week"s, duration_cast<seconds>(seconds{3600*24*7}) }, { "1weeks"s, duration_cast<seconds>(seconds{3600*24*7}) }, { "1month"s, duration_cast<seconds>(seconds{3600*24*30}) }, { "1months"s, duration_cast<seconds>(seconds{3600*24*30}) }, { "1mo"s, duration_cast<seconds>(seconds{3600*24*30}) }, { "1y"s, duration_cast<seconds>(seconds{3600*24*365}) }, { "1yr"s, duration_cast<seconds>(seconds{3600*24*365}) }, { "1year"s, duration_cast<seconds>(seconds{3600*24*365}) }, { "1years"s, duration_cast<seconds>(seconds{3600*24*365}) }, { "1d2h3m4s"s, duration_cast<seconds>(days_t{1}) + duration_cast<seconds>(hours{2}) + duration_cast<seconds>(minutes{3}) + duration_cast<seconds>(seconds{4}) }, { "1 days 2 hours 4 minutes"s, duration_cast<seconds>(days_t{1}) + duration_cast<seconds>(hours{2}) + duration_cast<seconds>(minutes{4}) }, }; for (auto& i : good) { cout << "good: " << i.s << " -> " << i.r.count() << std::endl; EXPECT_EQ(0, conf.set_val("mgr_tick_period", i.s, nullptr)); EXPECT_EQ(i.r.count(), conf.get_val<seconds>("mgr_tick_period").count()); } std::vector<std::string> bad = { "12x", "_ 12", "1 2", "21 centuries", "1 y m", }; for (auto& i : bad) { std::stringstream err; EXPECT_EQ(-EINVAL, conf.set_val("mgr_tick_period", i, &err)); cout << "bad: " << i << " -> " << err.str() << std::endl; } for (int i = 0; i < 100; ++i) { std::chrono::seconds j = std::chrono::seconds(rand()); string s = exact_timespan_str(j); std::chrono::seconds k = parse_timespan(s); cout << "rt: " << j.count() << " -> " << s << " -> " << k.count() << std::endl; EXPECT_EQ(j.count(), k.count()); } } TEST(Option, validation) { Option opt_int("foo", Option::TYPE_INT, Option::LEVEL_BASIC); opt_int.set_min_max(5, 10); std::string msg; EXPECT_EQ(-EINVAL, opt_int.validate(Option::value_t(int64_t(4)), &msg)); EXPECT_EQ(-EINVAL, opt_int.validate(Option::value_t(int64_t(11)), &msg)); EXPECT_EQ(0, opt_int.validate(Option::value_t(int64_t(7)), &msg)); Option opt_enum("foo", Option::TYPE_STR, Option::LEVEL_BASIC); opt_enum.set_enum_allowed({"red", "blue"}); EXPECT_EQ(0, opt_enum.validate(Option::value_t(std::string("red")), &msg)); EXPECT_EQ(0, opt_enum.validate(Option::value_t(std::string("blue")), &msg)); EXPECT_EQ(-EINVAL, opt_enum.validate(Option::value_t(std::string("green")), &msg)); Option opt_validator("foo", Option::TYPE_INT, Option::LEVEL_BASIC); opt_validator.set_validator([](std::string *value, std::string *error_message){ if (*value == std::string("one")) { *value = "1"; return 0; } else if (*value == std::string("666")) { return -EINVAL; } else { return 0; } }); std::string input = "666"; // An explicitly forbidden value EXPECT_EQ(-EINVAL, opt_validator.pre_validate(&input, &msg)); EXPECT_EQ(input, "666"); input = "123"; // A permitted value with no special behaviour EXPECT_EQ(0, opt_validator.pre_validate(&input, &msg)); EXPECT_EQ(input, "123"); input = "one"; // A value that has a magic conversion EXPECT_EQ(0, opt_validator.pre_validate(&input, &msg)); EXPECT_EQ(input, "1"); } /* * Local Variables: * compile-command: "cd ../.. ; * make unittest_config && * valgrind \ * --max-stackframe=20000000 --tool=memcheck \ * ./unittest_config # --gtest_filter=md_config_t.set_val * " * End: */
10,802
33.404459
85
cc
null
ceph-main/src/test/common/test_context.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Cloudwatt <[email protected]> * * Author: Loic Dachary <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library Public License for more details. * * */ #include "gtest/gtest.h" #include "include/types.h" #include "include/msgr.h" #include "common/ceph_context.h" #include "common/config_proxy.h" #include "log/Log.h" using namespace std; TEST(CephContext, do_command) { CephContext *cct = (new CephContext(CEPH_ENTITY_TYPE_CLIENT))->get(); cct->_conf->cluster = "ceph"; string key("key"); string value("value"); cct->_conf.set_val(key.c_str(), value.c_str()); cmdmap_t cmdmap; cmdmap["var"] = key; { stringstream ss; bufferlist out; std::unique_ptr<Formatter> f{Formatter::create_unique("xml", "xml")}; cct->do_command("config get", cmdmap, f.get(), ss, &out); f->flush(out); string s(out.c_str(), out.length()); EXPECT_EQ("<config_get><key>" + value + "</key></config_get>", s); } { stringstream ss; bufferlist out; cmdmap_t bad_cmdmap; // no 'var' field std::unique_ptr<Formatter> f{Formatter::create_unique("xml", "xml")}; int r = cct->do_command("config get", bad_cmdmap, f.get(), ss, &out); if (r >= 0) { f->flush(out); } string s(out.c_str(), out.length()); EXPECT_EQ(-EINVAL, r); EXPECT_EQ("", s); EXPECT_EQ("", ss.str()); // no error string :/ } { stringstream ss; bufferlist out; cmdmap_t bad_cmdmap; bad_cmdmap["var"] = string("doesnotexist123"); std::unique_ptr<Formatter> f{Formatter::create_unique("xml", "xml")}; int r = cct->do_command("config help", bad_cmdmap, f.get(), ss, &out); if (r >= 0) { f->flush(out); } string s(out.c_str(), out.length()); EXPECT_EQ(-ENOENT, r); EXPECT_EQ("", s); EXPECT_EQ("Setting not found: 'doesnotexist123'", ss.str()); } { stringstream ss; bufferlist out; std::unique_ptr<Formatter> f{Formatter::create_unique("xml", "xml")}; cct->do_command("config diff get", cmdmap, f.get(), ss, &out); f->flush(out); string s(out.c_str(), out.length()); EXPECT_EQ("<config_diff_get><diff><key><default></default><override>" + value + "</override><final>value</final></key><rbd_default_features><default>61</default><final>61</final></rbd_default_features><rbd_qos_exclude_ops><default>0</default><final>0</final></rbd_qos_exclude_ops></diff></config_diff_get>", s); } cct->put(); } TEST(CephContext, experimental_features) { CephContext *cct = (new CephContext(CEPH_ENTITY_TYPE_CLIENT))->get(); cct->_conf->cluster = "ceph"; ASSERT_FALSE(cct->check_experimental_feature_enabled("foo")); ASSERT_FALSE(cct->check_experimental_feature_enabled("bar")); ASSERT_FALSE(cct->check_experimental_feature_enabled("baz")); cct->_conf.set_val("enable_experimental_unrecoverable_data_corrupting_features", "foo,bar"); cct->_conf.apply_changes(&cout); ASSERT_TRUE(cct->check_experimental_feature_enabled("foo")); ASSERT_TRUE(cct->check_experimental_feature_enabled("bar")); ASSERT_FALSE(cct->check_experimental_feature_enabled("baz")); cct->_conf.set_val("enable_experimental_unrecoverable_data_corrupting_features", "foo bar"); cct->_conf.apply_changes(&cout); ASSERT_TRUE(cct->check_experimental_feature_enabled("foo")); ASSERT_TRUE(cct->check_experimental_feature_enabled("bar")); ASSERT_FALSE(cct->check_experimental_feature_enabled("baz")); cct->_conf.set_val("enable_experimental_unrecoverable_data_corrupting_features", "baz foo"); cct->_conf.apply_changes(&cout); ASSERT_TRUE(cct->check_experimental_feature_enabled("foo")); ASSERT_FALSE(cct->check_experimental_feature_enabled("bar")); ASSERT_TRUE(cct->check_experimental_feature_enabled("baz")); cct->_conf.set_val("enable_experimental_unrecoverable_data_corrupting_features", "*"); cct->_conf.apply_changes(&cout); ASSERT_TRUE(cct->check_experimental_feature_enabled("foo")); ASSERT_TRUE(cct->check_experimental_feature_enabled("bar")); ASSERT_TRUE(cct->check_experimental_feature_enabled("baz")); cct->_log->flush(); } /* * Local Variables: * compile-command: "cd ../.. ; * make unittest_context && * valgrind \ * --max-stackframe=20000000 --tool=memcheck \ * ./unittest_context # --gtest_filter=CephContext.* * " * End: */
4,922
32.719178
315
cc
null
ceph-main/src/test/common/test_convenience.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2017 Red Hat, Inc. * * Author: Casey Bodley <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/convenience.h" // include first: tests that header is standalone #include <string> #include <boost/optional.hpp> #include <gtest/gtest.h> // A just god would not allow the C++ standard to make taking the // address of member functions in the standard library undefined behavior. static std::string::size_type l(const std::string& s) { return s.size(); } TEST(Convenience, MaybeDo) { boost::optional<std::string> s("qwerty"); boost::optional<std::string> t; auto r = ceph::maybe_do(s, l); EXPECT_TRUE(r); EXPECT_EQ(*r, s->size()); EXPECT_FALSE(ceph::maybe_do(t, l)); } TEST(Convenience, MaybeDoOr) { const boost::optional<std::string> s("qwerty"); const boost::optional<std::string> t; auto r = ceph::maybe_do_or(s, l, 0); EXPECT_EQ(r, s->size()); EXPECT_EQ(ceph::maybe_do_or(t, l, 0u), 0u); } TEST(Convenience, StdMaybeDo) { std::optional<std::string> s("qwerty"); std::optional<std::string> t; auto r = ceph::maybe_do(s, l); EXPECT_TRUE(r); EXPECT_EQ(*r, s->size()); EXPECT_FALSE(ceph::maybe_do(t, l)); } TEST(Convenience, StdMaybeDoOr) { const std::optional<std::string> s("qwerty"); const std::optional<std::string> t; auto r = ceph::maybe_do_or(s, l, 0); EXPECT_EQ(r, s->size()); EXPECT_EQ(ceph::maybe_do_or(t, l, 0u), 0u); }
1,756
24.1
81
cc
null
ceph-main/src/test/common/test_counter.cc
#include "common/DecayCounter.h" #include <gtest/gtest.h> #include <list> #include <cmath> TEST(DecayCounter, steady) { static const double duration = 2.0; static const double max = 2048.0; static const double rate = 3.5; DecayCounter d{DecayRate{rate}}; d.hit(max); const auto start = DecayCounter::clock::now(); double total = 0.0; while (1) { const auto now = DecayCounter::clock::now(); auto el = std::chrono::duration<double>(now-start); if (el.count() > duration) { break; } double v = d.get(); double diff = max-v; if (diff > 0.0) { d.hit(diff); total += diff; } } /* Decay function: dN/dt = -λM where λ = ln(0.5)/rate * (where M is the maximum value of the counter, not varying with time.) * Integrating over t: N = -λMt (+c) */ double expected = -1*std::log(0.5)/rate*max*duration; std::cerr << "t " << total << " e " << expected << std::endl; ASSERT_LT(std::abs(total-expected)/expected, 0.05); }
998
23.365854
74
cc
null
ceph-main/src/test/common/test_crc32c.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <iostream> #include <string.h> #include "include/types.h" #include "include/crc32c.h" #include "include/utime.h" #include "common/Clock.h" #include "gtest/gtest.h" #include "common/sctp_crc32.h" #include "common/crc32c_intel_baseline.h" #include "common/crc32c_aarch64.h" TEST(Crc32c, Small) { const char *a = "foo bar baz"; const char *b = "whiz bang boom"; ASSERT_EQ(4119623852u, ceph_crc32c(0, (unsigned char *)a, strlen(a))); ASSERT_EQ(881700046u, ceph_crc32c(1234, (unsigned char *)a, strlen(a))); ASSERT_EQ(2360230088u, ceph_crc32c(0, (unsigned char *)b, strlen(b))); ASSERT_EQ(3743019208u, ceph_crc32c(5678, (unsigned char *)b, strlen(b))); } TEST(Crc32c, PartialWord) { const char *a = (const char *)malloc(5); const char *b = (const char *)malloc(35); memset((void *)a, 1, 5); memset((void *)b, 1, 35); ASSERT_EQ(2715569182u, ceph_crc32c(0, (unsigned char *)a, 5)); ASSERT_EQ(440531800u, ceph_crc32c(0, (unsigned char *)b, 35)); free((void*)a); free((void*)b); } TEST(Crc32c, Big) { int len = 4096000; char *a = (char *)malloc(len); memset(a, 1, len); ASSERT_EQ(31583199u, ceph_crc32c(0, (unsigned char *)a, len)); ASSERT_EQ(1400919119u, ceph_crc32c(1234, (unsigned char *)a, len)); free(a); } TEST(Crc32c, Performance) { int len = 1000 * 1024 * 1024; char *a = (char *)malloc(len); std::cout << "populating large buffer" << std::endl; for (int i=0; i<len; i++) a[i] = i & 0xff; std::cout << "calculating crc" << std::endl; { utime_t start = ceph_clock_now(); unsigned val = ceph_crc32c(0, (unsigned char *)a, len); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "best choice = " << rate << " MB/sec" << std::endl; ASSERT_EQ(261108528u, val); } { utime_t start = ceph_clock_now(); unsigned val = ceph_crc32c(0xffffffff, (unsigned char *)a, len); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "best choice 0xffffffff = " << rate << " MB/sec" << std::endl; ASSERT_EQ(3895876243u, val); } { utime_t start = ceph_clock_now(); unsigned val = ceph_crc32c_sctp(0, (unsigned char *)a, len); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "sctp = " << rate << " MB/sec" << std::endl; ASSERT_EQ(261108528u, val); } { utime_t start = ceph_clock_now(); unsigned val = ceph_crc32c_intel_baseline(0, (unsigned char *)a, len); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "intel baseline = " << rate << " MB/sec" << std::endl; ASSERT_EQ(261108528u, val); } #if defined(__arm__) || defined(__aarch64__) if (ceph_arch_aarch64_crc32) // Skip if CRC32C instructions are not defined. { utime_t start = ceph_clock_now(); unsigned val = ceph_crc32c_aarch64(0, (unsigned char *)a, len); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "aarch64 = " << rate << " MB/sec" << std::endl; ASSERT_EQ(261108528u, val); } #endif free(a); } static uint32_t crc_check_table[] = { 0xcfc75c75, 0x7aa1b1a7, 0xd761a4fe, 0xd699eeb6, 0x2a136fff, 0x9782190d, 0xb5017bb0, 0xcffb76a9, 0xc79d0831, 0x4a5da87e, 0x76fb520c, 0x9e19163d, 0xe8eacd22, 0xefd4319e, 0x1eaa804b, 0x7ff41ccb, 0x94141dab, 0xb4c2588f, 0x484bf16f, 0x77725048, 0xf27d43ee, 0x3604f655, 0x20bb9b79, 0xd6ee30ba, 0xf402f02d, 0x59992eec, 0x159c0449, 0xe2d72e60, 0xc519c744, 0xf56f7995, 0x7e40be36, 0x695ccedc, 0xc95c4ae3, 0xb0d2d6bc, 0x85872e14, 0xea2c01b0, 0xe9b75f1a, 0xebb23ae3, 0x39faee13, 0x313cb413, 0xe683eb7d, 0xd22e2ae1, 0xf49731dd, 0x897a8e60, 0x923b510e, 0xe0e0f3b, 0x357dd0f, 0x63b7aa7d, 0x6f5c2a40, 0x46b09a37, 0x80324751, 0x380fd024, 0x78b122c6, 0xb29d1dde, 0x22f19ddc, 0x9d6ee6d6, 0xfb4e7e1c, 0xb9780044, 0x85feef90, 0x8e4fae11, 0x1a71394a, 0xbe21c888, 0xde2f6f47, 0x93c365f0, 0xfd1d3814, 0x6e0a23df, 0xc6739c17, 0x2d48520d, 0x3357e475, 0x5d57058a, 0x22c4b9f7, 0x5a498b58, 0x7bed8ddb, 0xcf1eb035, 0x2094f389, 0xb6a7c977, 0x289d29e2, 0x498d5b7, 0x8db77420, 0x85300608, 0x5d1c04c4, 0x5acfee62, 0x99ad4694, 0x799f9833, 0x50e76ce1, 0x72dc498, 0x70a393be, 0x905a364d, 0x1af66b95, 0x5b3eed9e, 0xa3e4da14, 0xc720fece, 0x555200df, 0x169fd3e0, 0x531c18c0, 0x6f9b6092, 0x6d16638b, 0x5a8c8b6a, 0x818ebab2, 0xd75b10bb, 0xcaa01bfa, 0x67377804, 0xf8a085ae, 0xfc7d88b8, 0x5e2debc1, 0x9759cb1f, 0x24c39b63, 0x210afbba, 0x22f7c6f7, 0xa8f8dc11, 0xf1d4550c, 0x1d2b1e47, 0x59a44605, 0x25402e97, 0x18401ea, 0xb1884203, 0xd6ef715, 0x1797b686, 0x9e7f5aa7, 0x30795e88, 0xb280b636, 0x77258b7d, 0x5f8dbff3, 0xbb57ea03, 0xa2c35cce, 0x1acce538, 0xa50be97a, 0x417f4b57, 0x6d94792f, 0x4bb6fb34, 0x3787440c, 0x9a77b0b9, 0x67ece3d0, 0x5a8450fe, 0x8e66f55b, 0x3cefce93, 0xf7ca60ab, 0xce7cd3b7, 0x97976493, 0xa05632f8, 0x77ac4546, 0xed24c705, 0x92a2f20, 0xc0b1cc9, 0x831ae4e1, 0x5b3f28b1, 0xee6fca02, 0x74acc743, 0xaf40043f, 0x5f21e837, 0x9e168fc0, 0x64e28de, 0x88ae891d, 0xac2e4ff5, 0xaeaf9c27, 0x158a2d3, 0x5226fb01, 0x9bf56ae1, 0xe4a2dd8d, 0x2599d6de, 0xe798b5ee, 0x39efe57a, 0xbb9965c7, 0x4516fde0, 0xa41831f5, 0xd7cd0797, 0xd07b7d5c, 0xb330d048, 0x3a47e35d, 0x87dd39e5, 0xa806fb31, 0xad228dd, 0xcc390816, 0x9237a4de, 0x8dfe1c20, 0x304f6bc, 0x3ad98572, 0xec13f349, 0x4e5278d7, 0x784c4bf4, 0x7b93cb23, 0xa18c87ae, 0x84ff79dd, 0x8e95061d, 0xd972f4d4, 0x4ad50380, 0x23cbc187, 0x7fa7f22c, 0x6062c18e, 0x42381901, 0x10cf51d9, 0x674e22a4, 0x28a63445, 0x6fc1b591, 0xa4dc117a, 0x744a00d0, 0x8a5470ea, 0x9539c6a7, 0xc961a584, 0x22f81498, 0xae299e51, 0x5653fcd3, 0x7bfa474f, 0x7f502c42, 0xfb41c744, 0xd478fb95, 0x7b676978, 0xb22f5610, 0xbcbe730c, 0x70ff5773, 0xde990b63, 0xebcbf9d5, 0x2d029133, 0xf39513e1, 0x56229640, 0x660529e5, 0x3b90bdf8, 0xc9822978, 0x4e3daab1, 0x2e43ce72, 0x572bb6ff, 0xdc4b17bd, 0x6c290d46, 0x7d9644ca, 0x7652fd89, 0x66d72059, 0x521e93d4, 0xd626ff95, 0xdc4eb57e, 0xb0b3307c, 0x409adbed, 0x49ae2d28, 0x8edd249a, 0x8e4fb6ec, 0x5a191fbf, 0xe1751948, 0xb4ae5d00, 0xabeb1bdd, 0xbe204b60, 0xbc97aad4, 0xb8cb5915, 0x54f33261, 0xc5d83b28, 0x99d0d099, 0xfb06f8b2, 0x57305f66, 0xf9fde17b, 0x192f143c, 0xcc3c58fd, 0x36e2e420, 0x17118208, 0xcac7e42a, 0xb45ad63d, 0x8ad5e475, 0xb7a3bc1e, 0xe03e64ad, 0x2c197d77, 0x1a0ff1fe, 0xbcd443fb, 0x7589393a, 0xd66b1f67, 0xdddf0a66, 0x4750b7c7, 0xc62a79db, 0xcf02a0d3, 0xb4012205, 0x9733d16c, 0x9a29cff8, 0xdd3d6427, 0x15c0273a, 0x97b289b, 0x358ff573, 0x73a9ceb7, 0xc3788b1a, 0xda7a5155, 0x2990a31, 0x9fa4705, 0x5eb4e2e2, 0x98465bb2, 0x74a17883, 0xe87df542, 0xe20f22f1, 0x48ffd67e, 0xc94fab5f, 0x9eb431d2, 0xffd673cb, 0xc374dc18, 0xa542fbf7, 0xb8fea538, 0x43f5431f, 0xcbe3fb7d, 0x2734e0e4, 0x5cb05a8, 0xd00fcf47, 0x248dbbae, 0x47d4de6c, 0xecc97151, 0xca8c379b, 0x49049fd, 0xeb2acd18, 0xab178ac, 0xc98ab95d, 0xb9e0be20, 0x36664a13, 0x95d81459, 0xb54973a9, 0x27f9579c, 0xa24fb6df, 0x3f6f8cea, 0xe11efdd7, 0x68166281, 0x586e0a6, 0x5fad7b57, 0xd58f50ad, 0x6e0d3be8, 0x27a00831, 0x543b3761, 0x96c862fb, 0xa823ed4f, 0xf6043f37, 0x980703eb, 0xf5e69514, 0x42a2082, 0x495732a2, 0x793eea23, 0x6a6a17fb, 0x77d75dc5, 0xb3320ec4, 0x10d4d01e, 0xa17508a6, 0x6d578355, 0xd136c445, 0xafa6acc6, 0x2307831d, 0x5bf345fd, 0xb9a04582, 0x2627a686, 0xf6f4ce3b, 0xd0ac868f, 0x78d6bdb3, 0xfe42945a, 0x8b06cbf3, 0x2b169628, 0xf072b8b7, 0x8652a0ca, 0x3f52fc42, 0xa0415b9a, 0x16e99341, 0x7394e9c7, 0xac92956c, 0x7bff7137, 0xb0e8ea5c, 0x42d8c22, 0x4318a18, 0x42097180, 0x57d17dba, 0xb1f7a567, 0x55186d60, 0xf527e0ca, 0xd58b0b48, 0x31d9155b, 0xd5fd0441, 0x6024d751, 0xe14d03c3, 0xba032e1c, 0xd6d89ae7, 0x54f1967a, 0xe401c200, 0x8ee973ff, 0x3d24277e, 0xab394cbf, 0xe3b39762, 0x87f43766, 0xe4c2bdff, 0x1234c0d7, 0x8ef3e1bd, 0xeeb00f61, 0x15d17d4b, 0x7d40ac8d, 0xada8606f, 0x7ba5e3a1, 0xcf487cf9, 0x98dda708, 0x6d7c9bea, 0xaecb321c, 0x9f7801b2, 0x53340341, 0x7ae27355, 0xbf859829, 0xa36a00b, 0x99339435, 0x8342d1e, 0x4ab4d7ea, 0x862d01cd, 0x7f94fbee, 0xe329a5a3, 0x2cb7ba81, 0x50bae57a, 0x5bbd65cf, 0xf06f60e4, 0x569ad444, 0xfa0c16c, 0xb8c2b472, 0x3ea64ea1, 0xc6dc4c18, 0x5d6d654a, 0x5369a931, 0x2163bf7f, 0xe45bd590, 0xcc826d18, 0xb4ce22f6, 0x200f7232, 0x5f2f869c, 0xffd5cc17, 0x1a578942, 0x930da3ea, 0x216377f, 0x9f07a04b, 0x1f2a777c, 0x13c95089, 0x8a64d032, 0x1eecb206, 0xc537dc4, 0x319f9ac8, 0xe2131194, 0x25d2f716, 0xa27f471a, 0xf6434ce2, 0xd51a10b9, 0x4e28a61, 0x647c888a, 0xb383d2ff, 0x93aa0d0d, 0x670d1317, 0x607f36e2, 0x73e01833, 0x2bd372b0, 0x86404ad2, 0x253d5cc4, 0x1348811c, 0x8756f2d5, 0xe1e55a59, 0x5247e2d1, 0x798ab6b, 0x181bbc57, 0xb9ea36e0, 0x66081c68, 0x9bf0bad7, 0x892b1a6, 0x8a6a9aed, 0xda955d0d, 0x170e5128, 0x81733d84, 0x6d9f6b10, 0xd60046fd, 0x7e401823, 0xf9904ce6, 0xaa765665, 0x2fd5c4ee, 0xbb9c1580, 0x391dac53, 0xbffe4270, 0x866c30b1, 0xd629f22, 0x1ee5bfee, 0x5af91c96, 0x96b613bf, 0xa65204c9, 0x9b8cb68c, 0xd08b37c1, 0xf1863f8f, 0x1e4c844a, 0x876abd30, 0x70c07eff, 0x63d8e875, 0x74351f92, 0xffe7712d, 0x58c0171d, 0x7b826b99, 0xc09afc78, 0xd81d3065, 0xccced8b1, 0xe258b1c9, 0x5659d6b, 0x1959c406, 0x53bd05e6, 0xa32f784b, 0x33351e4b, 0xb6b9d769, 0x59e5802c, 0x118c7ff7, 0x46326e0b, 0xa7376fbe, 0x7218aed1, 0x28c8f707, 0x44610a2f, 0xf8eafea1, 0xfe36fdae, 0xb4b546f1, 0x2e27ce89, 0xc1fde8a0, 0x99f2f157, 0xfde687a1, 0x40a75f50, 0x6c653330, 0xf3e38821, 0xf4663e43, 0x2f7e801e, 0xfca360af, 0x53cd3c59, 0xd20da292, 0x812a0241 }; TEST(Crc32c, Range) { int len = sizeof(crc_check_table) / sizeof(crc_check_table[0]); unsigned char *b = (unsigned char *)malloc(len); memset(b, 1, len); uint32_t crc = 0; uint32_t *check = crc_check_table; for (int i = 0 ; i < len; i++, check++) { crc = ceph_crc32c(crc, b+i, len-i); ASSERT_EQ(crc, *check); } free(b); } static uint32_t crc_zero_check_table[] = { 0xbd6f81f8, 0x6213374d, 0x72952aeb, 0x8ecb5e52, 0xa04914b4, 0xaf3aaea9, 0xb88d42d6, 0x81797724, 0xc0022634, 0x4dbf46a4, 0xc7813aa, 0x172150e0, 0x13d8d958, 0x339fd933, 0xd9e725f4, 0x20b65b14, 0x349c971c, 0x7f812818, 0x5228e357, 0x811f231f, 0xe4bdaeee, 0xcdd22442, 0x26ae3c58, 0xf9628c5e, 0x8118e80b, 0xca0ea635, 0xc5028f6d, 0xbd2270, 0x4d9171a3, 0xe810af42, 0x904c7218, 0xdc62c735, 0x3c8b3748, 0x7cae4eef, 0xed170242, 0xdc0a6a28, 0x4afb0591, 0x4643748a, 0xad28d5b, 0xeb2d60d3, 0x479d21a9, 0x2a0916c1, 0x144cd9fb, 0x2498ba7a, 0x196489f, 0x330bb594, 0x5abe491d, 0x195658fe, 0xc6ef898f, 0x94b251a1, 0x4f968332, 0xfbf5f29d, 0x7b4828ce, 0x3af20a6f, 0x653a721f, 0x6d92d018, 0xf43ca065, 0xf55da16e, 0x94af47c6, 0xf08abdc, 0x11344631, 0xb249e575, 0x1f9f992b, 0xfdb6f490, 0xbd40d84b, 0x945c69e1, 0x2a94e2e3, 0xe5aa9b91, 0x89cebb57, 0x175a3097, 0x502b7d34, 0x174f2c92, 0x2a8f01c0, 0x645a2db8, 0x9e9a4a8, 0x13adac02, 0x2759a24b, 0x8bfcb972, 0xfa1edbfe, 0x5a88365e, 0x5c107fd9, 0x91ac73a8, 0xbd40e99e, 0x513011ca, 0x97bd2841, 0x336c1c4e, 0x4e88563e, 0x6948813e, 0x96e1cbee, 0x64b2faa5, 0x9671e44, 0x7d492fcb, 0x3539d74a, 0xcbe26ad7, 0x6106e673, 0x162115d, 0x8534e6a6, 0xd28a1ea0, 0xf73beb20, 0x481bdbae, 0xcd12e442, 0x8ab52843, 0x171d72c4, 0xd97cb216, 0x60fa0ecf, 0x74336ebb, 0x4d67fd86, 0x9393e96a, 0x63670234, 0x3f2a31da, 0x4036c11f, 0x55cc2ceb, 0xf75b27dc, 0xcabdca83, 0x80699d1a, 0x228c13a1, 0x5ea7f8a9, 0xc7631f40, 0x710b867a, 0xaa6e67b9, 0x27444987, 0xd693cd2a, 0xc4e21e0c, 0xd340e1cb, 0x2a2a346f, 0xac55e843, 0xfcd2750c, 0x4529a016, 0x7ac5802, 0xa2eb291f, 0x4a0fb9ea, 0x6a58a9a0, 0x51f56797, 0xda595134, 0x267aba96, 0x8ba80ee, 0x4474659e, 0x2b7bacb, 0xba524d37, 0xb60981bb, 0x5fd43811, 0xca41594a, 0x98ace58, 0x3fc5b984, 0x6a290b91, 0x6576108a, 0x8c33c85e, 0x52622407, 0x99cf8723, 0x68198dc8, 0x18b7341d, 0x540fc0f9, 0xf4a7b6f6, 0xfade9dfa, 0x725471ca, 0x5c160723, 0x5f33b243, 0xecec5d09, 0x6f520abb, 0x139c7bca, 0x58349acb, 0x1fccef32, 0x1d01aa0f, 0x3f477a65, 0xebf55472, 0xde9ae082, 0x76d3119e, 0x937e2708, 0xba565506, 0xbe820951, 0xc1f336fa, 0xfc41afb6, 0x4ef12d88, 0xd6f6d4f, 0xb33fb3fe, 0x9c6d1ae, 0x24ae1c29, 0xf9ae57f7, 0x51d1e4c9, 0x86dc73fc, 0x54b7bf38, 0x688a141c, 0x91d4ea7a, 0xd57a0fd0, 0x5cdcd16f, 0xc59c135a, 0x5bb003b5, 0x730b52f3, 0xc1dc5b1e, 0xf083f53, 0x8159e7c8, 0xf396d2e3, 0x1c7f18ec, 0x5bedc75e, 0x2f11fbfd, 0xb4437094, 0x77c55e3, 0x1d8636e1, 0x159bf2f, 0x6cbabf5b, 0xf4d005bc, 0x39f0bc55, 0x3d525f54, 0x8422e29d, 0xfb8a413d, 0x66e78593, 0xa0e14663, 0x880b8fa1, 0x24b53713, 0x12105ff3, 0xa94dd90f, 0x3ff981bc, 0xaf2366af, 0x8e98710, 0x48eb45c6, 0xbc3aee53, 0x6933d852, 0xe236cfd3, 0x3e6c50af, 0xe309e3fd, 0x452eac88, 0x725bf633, 0xbe89339a, 0x4b54eff7, 0xa57e392f, 0x6ee15bef, 0x67630f96, 0x31656c71, 0x77fc97f0, 0x1d29682f, 0xa4b0fc5d, 0xb3fd0ee1, 0x9d10aa57, 0xf104e21, 0x478b5f75, 0xaf1ca64b, 0x13e8a297, 0x21caa105, 0xb3cb8e9d, 0xd4536cb, 0x425bdfce, 0x90462d05, 0x8cace1cf, 0xc0ab7293, 0xbcf288cb, 0x5edcdc11, 0x4ec8b5e0, 0x42738654, 0x4ba49663, 0x2b264337, 0x41d1a5ce, 0xaa8acb92, 0xe79714aa, 0x86695e7c, 0x1330c69a, 0xe0c6485f, 0xb038b81a, 0x6f823a85, 0x4eeff0e4, 0x7355d58f, 0x7cc87e83, 0xe23e4619, 0x7093faa0, 0x7328cb2f, 0x7856db5e, 0xbc38d892, 0x1e4307c8, 0x347997e1, 0xb26958, 0x997ddf1e, 0x58dc72e3, 0x4b6e9a77, 0x49eb9924, 0x36d555db, 0x59456efd, 0x904bd6d2, 0xd932837d, 0xf96a24ec, 0x525aa449, 0x5fd05bc7, 0x84778138, 0xd869bfe1, 0xe6bbd546, 0x2f796af4, 0xbaab980f, 0x7f18a176, 0x3a8e00d9, 0xb589ea81, 0x77920ee3, 0xc6730dbc, 0x8a5df534, 0xb7df9a12, 0xdc93009c, 0x215b885, 0x309104b, 0xf47e380b, 0x23f6cdef, 0xe112a923, 0x83686f38, 0xde2c7871, 0x9f728ec7, 0xeaae7af6, 0x6d7b7b0a, 0xaf0cde04, 0xfcb51a1f, 0xf0cd53cf, 0x7aa5556a, 0xa64ccf7e, 0x854c2084, 0xc493ddd4, 0x92684099, 0x913beb92, 0xe4067ea8, 0x9557605a, 0x934346d6, 0x23a3a7c7, 0x588b2805, 0xe1e755ae, 0xe4c05e84, 0x8e09d0f3, 0x1343a510, 0x6175c2c3, 0x39bb7947, 0x4a1b9b6b, 0xf0e373da, 0xe7b9a201, 0x24b7a392, 0x91a27584, 0x9ac3a10f, 0x91fc9314, 0xc495d878, 0x3fcbc776, 0x7f81d6da, 0x973edb2f, 0xa9d731c6, 0x2dc022a8, 0xa066c881, 0x7e082dff, 0xa1ff394d, 0x1cb0c2bb, 0xef87a116, 0x5179810b, 0xa1594c92, 0xe291e155, 0x3578c98f, 0xb801f82c, 0xa1778ad9, 0xbdd48b76, 0x74f1ce54, 0x46b8de63, 0x3861112c, 0x46a8920f, 0x3e1075e7, 0x220a49dd, 0x3e51d6d2, 0xbf1f22cd, 0x5d1490c5, 0x7f1e05f5, 0xa0c1691d, 0x9108debf, 0xe69899b, 0xe771d8b6, 0x878c92c1, 0x973e37c0, 0x833c4c25, 0xcffe7b03, 0x92e0921e, 0xccee9836, 0xa9739832, 0xc774f2f2, 0xf34f9467, 0x608cef83, 0x97a584d2, 0xf5218c9, 0x73eb9524, 0xb3fb4870, 0x53296e3d, 0x8836f46f, 0x9d6a40b0, 0x789b5e91, 0x62a915ba, 0x32c02d74, 0xc93de2f3, 0xefa67fc7, 0x169ee4f1, 0x72bbbe9e, 0x49357cf2, 0x219207bf, 0x12516225, 0x182df160, 0x230c9a3f, 0x137a8497, 0xa429ad30, 0x4aa66f88, 0x40319931, 0xfa241c42, 0x1e5189ec, 0xca693ada, 0xe7b923f4, 0xff546a06, 0xf01103c2, 0x99875a32, 0x4bbf55a9, 0x48abdf3e, 0x85eb3dec, 0x2d009057, 0x14c2a682, 0xfabe68af, 0x96a31fa6, 0xf52f4686, 0x73f72b61, 0x92f39e13, 0x66794863, 0x7ca4c2aa, 0x37a2fe39, 0x33be288a, 0x1ff9a59c, 0xd65e667, 0x5d7c9332, 0x8a6a2d8b, 0x37ec2d3b, 0x9f935ab9, 0x67fcd589, 0x48a09508, 0xc446e984, 0x58f69202, 0x968dfbbb, 0xc93d7626, 0x82344e, 0xf1d930a4, 0xcc3acdde, 0x20cf92bf, 0x94b7616d, 0xb0e45050, 0xdc36c072, 0x74cba0, 0x6478300a, 0x27803b97, 0xb7b2ebd0, 0xb3a691e, 0x35c2f261, 0x3fcff45a, 0x3e4b7b93, 0x86b680bd, 0x720333ce, 0x67f933ca, 0xb10256de, 0xe939bb3f, 0xb540a02f, 0x39a8b8e4, 0xb6a63aa5, 0x5e1d56ee, 0xa415a16, 0xcb5753d, 0x17fabd19, 0x90eac10d, 0x2308857d, 0xb8f6224c, 0x71790390, 0x18749d48, 0xed778f1b, 0x69f0e17c, 0xbd622f4, 0x52c3a79e, 0x9697bf51, 0xa768755c, 0x9fe860ea, 0xa852b0ac, 0x9549ec64, 0x8669c603, 0x120e289c, 0x3f0520f5, 0x9b15884, 0x2d06fa7f, 0x767b12f6, 0xcb232dd6, 0x4e2b4590, 0x97821835, 0x4506a582, 0xd974dbaa, 0x379bd22f, 0xb9d65a2f, 0x8fad14d9, 0x72a55b5f, 0x34d56c6e, 0xc0badd55, 0xc20ee31b, 0xeb567f69, 0xdadac1c, 0xb6dcc8f5, 0xc6d89117, 0x16c4999d, 0xc9b0da2a, 0xfcd6e9b3, 0x72d299ae, 0x4c2b345b, 0x5d2c06cb, 0x9b9a3ce2, 0x8e84866, 0x876d1806, 0xbaeb6183, 0xe2a89d5d, 0x4604d2fe, 0x9909c5e0, 0xf2fb7bec, 0x7e04dcd0, 0xe5b24865, 0xda96b760, 0x74a4d01, 0xb0f35bea, 0x9a2edb2, 0x5327a0d3 }; TEST(Crc32c, RangeZero) { int len = sizeof(crc_zero_check_table) / sizeof(crc_zero_check_table[0]); unsigned char *b = (unsigned char *)malloc(len); memset(b, 0, len); uint32_t crc = 1; /* when checking zero buffer we want to start with a non zero crc, otherwise all the results are going to be zero */ uint32_t *check = crc_zero_check_table; for (int i = 0 ; i < len; i++, check++) { crc = ceph_crc32c(crc, b+i, len-i); ASSERT_EQ(crc, *check); } free(b); } TEST(Crc32c, RangeNull) { int len = sizeof(crc_zero_check_table) / sizeof(crc_zero_check_table[0]); uint32_t crc = 1; /* when checking zero buffer we want to start with a non zero crc, otherwise all the results are going to be zero */ uint32_t *check = crc_zero_check_table; for (int i = 0 ; i < len; i++, check++) { crc = ceph_crc32c(crc, NULL, len-i); ASSERT_EQ(crc, *check); } } double estimate_clock_resolution() { volatile char* p = (volatile char*)malloc(1024); utime_t start; utime_t end; std::set<double> S; for(int j=10; j<200; j+=1) { start = ceph_clock_now(); for (int i=0; i<j; i++) p[i]=1; end = ceph_clock_now(); S.insert((double)(end - start)); } auto head = S.begin(); auto tail = S.end(); for (size_t i=0; i<S.size()/4; i++) { ++head; --tail; } double v = *(head++); double range=0; while (head != tail) { range = std::max(range, *head - v); v = *head; head++; } free((void*)p); return range; } TEST(Crc32c, zeros_performance_compare) { double resolution = estimate_clock_resolution(); utime_t start; utime_t pre_start; utime_t end; double time_adjusted; using namespace std::chrono; high_resolution_clock::now(); for (size_t scale=1; scale < 31; scale++) { size_t size = (1<<scale) + rand()%(1<<scale); pre_start = ceph_clock_now(); start = ceph_clock_now(); uint32_t crc_a = ceph_crc32c(111, nullptr, size); end = ceph_clock_now(); time_adjusted = (end - start) - (start - pre_start); std::cout << "regular method. size=" << size << " time= " << (double)(end-start) << " at " << (double)size/(1024*1024)/(time_adjusted) << " MB/sec" << " error=" << resolution / time_adjusted * 100 << "%" << std::endl; pre_start = ceph_clock_now(); start = ceph_clock_now(); #ifdef HAVE_POWER8 uint32_t crc_b = ceph_crc32c_zeros(111, size); #else uint32_t crc_b = ceph_crc32c_func(111, nullptr, size); #endif end = ceph_clock_now(); time_adjusted = (end - start) - (start - pre_start); #ifdef HAVE_POWER8 std::cout << "ceph_crc32c_zeros method. size=" << size << " time=" << (double)(end-start) << " at " << (double)size/(1024*1024)/(time_adjusted) << " MB/sec" << " error=" << resolution / time_adjusted * 100 << "%" << std::endl; #else std::cout << "fallback method. size=" << size << " time=" << (double)(end-start) << " at " << (double)size/(1024*1024)/(time_adjusted) << " MB/sec" << " error=" << resolution / time_adjusted * 100 << "%" << std::endl; #endif EXPECT_EQ(crc_a, crc_b); } } TEST(Crc32c, zeros_performance) { constexpr size_t ITER=100000; utime_t start; utime_t end; start = ceph_clock_now(); for (size_t i=0; i<ITER; i++) { for (size_t scale=1; scale < 31; scale++) { size_t size = (1<<scale) + rand() % (1<<scale); ceph_crc32c(rand(), nullptr, size); } } end = ceph_clock_now(); std::cout << "iterations="<< ITER*31 << " time=" << (double)(end-start) << std::endl; }
19,624
52.620219
97
cc
null
ceph-main/src/test/common/test_fair_mutex.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:nil -*- #include <array> #include <mutex> #include <numeric> #include <future> #include <gtest/gtest.h> #include "common/fair_mutex.h" TEST(FairMutex, simple) { ceph::fair_mutex mutex{"fair::simple"}; { std::unique_lock lock{mutex}; ASSERT_TRUE(mutex.is_locked()); // fair_mutex does not recursive ownership semantics ASSERT_FALSE(mutex.try_lock()); } // re-acquire the lock { std::unique_lock lock{mutex}; ASSERT_TRUE(mutex.is_locked()); } ASSERT_FALSE(mutex.is_locked()); } TEST(FairMutex, fair) { // waiters are queued in FIFO order, and they are woken up in the same order // we have a marathon participated by multiple teams: // - each team is represented by a thread. // - each team should have equal chance of being selected and scoring, assuming // the runners in each team are distributed evenly in the waiting queue. ceph::fair_mutex mutex{"fair::fair"}; const int NR_TEAMS = 2; std::array<unsigned, NR_TEAMS> scoreboard{0, 0}; const int NR_ROUNDS = 512; auto play = [&](int team) { for (int i = 0; i < NR_ROUNDS; i++) { std::unique_lock lock{mutex}; // pretent that i am running.. and it takes time std::this_thread::sleep_for(std::chrono::microseconds(20)); // score! scoreboard[team]++; // fair? unsigned total = std::accumulate(scoreboard.begin(), scoreboard.end(), 0); for (unsigned score : scoreboard) { if (total < NR_ROUNDS) { // not quite statistically significant. to reduce the false positive, // just consider it fair continue; } // check if any team is donimating the game. unsigned avg = total / scoreboard.size(); // leave at least half of the average to other teams ASSERT_LE(score, total - avg / 2); // don't treat myself too bad ASSERT_GT(score, avg / 2); }; } }; std::array<std::future<void>, NR_TEAMS> completed; for (int team = 0; team < NR_TEAMS; team++) { completed[team] = std::async(std::launch::async, play, team); } }
2,229
31.318841
81
cc
null
ceph-main/src/test/common/test_fault_injector.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/fault_injector.h" #include "common/common_init.h" #include "common/ceph_argparse.h" #include <gtest/gtest.h> TEST(FaultInjectorDeathTest, InjectAbort) { constexpr FaultInjector f{false, InjectAbort{}}; EXPECT_EQ(f.check(true), 0); EXPECT_DEATH([[maybe_unused]] int r = f.check(false), "FaultInjector"); } TEST(FaultInjectorDeathTest, AssignAbort) { FaultInjector<bool> f; ASSERT_EQ(f.check(false), 0); f.inject(false, InjectAbort{}); EXPECT_DEATH([[maybe_unused]] int r = f.check(false), "FaultInjector"); } // death tests have to run in single-threaded mode, so we can't initialize a // CephContext until after those have run (gtest automatically runs them first) class Fixture : public testing::Test { boost::intrusive_ptr<CephContext> cct; std::optional<NoDoutPrefix> prefix; protected: void SetUp() override { CephInitParameters params(CEPH_ENTITY_TYPE_CLIENT); cct = common_preinit(params, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); prefix.emplace(cct.get(), ceph_subsys_context); } void TearDown() override { prefix.reset(); cct.reset(); } const DoutPrefixProvider* dpp() { return &*prefix; } }; // test int as a Key type using FaultInjectorInt = Fixture; TEST_F(FaultInjectorInt, Default) { constexpr FaultInjector<int> f; EXPECT_EQ(f.check(0), 0); EXPECT_EQ(f.check(1), 0); EXPECT_EQ(f.check(2), 0); EXPECT_EQ(f.check(3), 0); } TEST_F(FaultInjectorInt, InjectError) { constexpr FaultInjector f{2, InjectError{-EINVAL}}; EXPECT_EQ(f.check(0), 0); EXPECT_EQ(f.check(1), 0); EXPECT_EQ(f.check(2), -EINVAL); EXPECT_EQ(f.check(3), 0); } TEST_F(FaultInjectorInt, InjectErrorMessage) { FaultInjector f{2, InjectError{-EINVAL, dpp()}}; EXPECT_EQ(f.check(0), 0); EXPECT_EQ(f.check(1), 0); EXPECT_EQ(f.check(2), -EINVAL); EXPECT_EQ(f.check(3), 0); } TEST_F(FaultInjectorInt, AssignError) { FaultInjector<int> f; ASSERT_EQ(f.check(0), 0); f.inject(0, InjectError{-EINVAL}); EXPECT_EQ(f.check(0), -EINVAL); } TEST_F(FaultInjectorInt, AssignErrorMessage) { FaultInjector<int> f; ASSERT_EQ(f.check(0), 0); f.inject(0, InjectError{-EINVAL, dpp()}); EXPECT_EQ(f.check(0), -EINVAL); } // test std::string_view as a Key type using FaultInjectorString = Fixture; TEST_F(FaultInjectorString, Default) { constexpr FaultInjector<std::string_view> f; EXPECT_EQ(f.check("Red"), 0); EXPECT_EQ(f.check("Green"), 0); EXPECT_EQ(f.check("Blue"), 0); } TEST_F(FaultInjectorString, InjectError) { FaultInjector<std::string_view> f{"Red", InjectError{-EIO}}; EXPECT_EQ(f.check("Red"), -EIO); EXPECT_EQ(f.check("Green"), 0); EXPECT_EQ(f.check("Blue"), 0); } TEST_F(FaultInjectorString, InjectErrorMessage) { FaultInjector<std::string_view> f{"Red", InjectError{-EIO, dpp()}}; EXPECT_EQ(f.check("Red"), -EIO); EXPECT_EQ(f.check("Green"), 0); EXPECT_EQ(f.check("Blue"), 0); } TEST_F(FaultInjectorString, AssignError) { FaultInjector<std::string_view> f; ASSERT_EQ(f.check("Red"), 0); f.inject("Red", InjectError{-EINVAL}); EXPECT_EQ(f.check("Red"), -EINVAL); } TEST_F(FaultInjectorString, AssignErrorMessage) { FaultInjector<std::string_view> f; ASSERT_EQ(f.check("Red"), 0); f.inject("Red", InjectError{-EINVAL, dpp()}); EXPECT_EQ(f.check("Red"), -EINVAL); } // test enum class as a Key type using FaultInjectorEnum = Fixture; enum class Color { Red, Green, Blue }; static std::ostream& operator<<(std::ostream& out, const Color& c) { switch (c) { case Color::Red: return out << "Red"; case Color::Green: return out << "Green"; case Color::Blue: return out << "Blue"; } return out; } TEST_F(FaultInjectorEnum, Default) { constexpr FaultInjector<Color> f; EXPECT_EQ(f.check(Color::Red), 0); EXPECT_EQ(f.check(Color::Green), 0); EXPECT_EQ(f.check(Color::Blue), 0); } TEST_F(FaultInjectorEnum, InjectError) { FaultInjector f{Color::Red, InjectError{-EIO}}; EXPECT_EQ(f.check(Color::Red), -EIO); EXPECT_EQ(f.check(Color::Green), 0); EXPECT_EQ(f.check(Color::Blue), 0); } TEST_F(FaultInjectorEnum, InjectErrorMessage) { FaultInjector f{Color::Red, InjectError{-EIO, dpp()}}; EXPECT_EQ(f.check(Color::Red), -EIO); EXPECT_EQ(f.check(Color::Green), 0); EXPECT_EQ(f.check(Color::Blue), 0); } TEST_F(FaultInjectorEnum, AssignError) { FaultInjector<Color> f; ASSERT_EQ(f.check(Color::Red), 0); f.inject(Color::Red, InjectError{-EINVAL}); EXPECT_EQ(f.check(Color::Red), -EINVAL); } TEST_F(FaultInjectorEnum, AssignErrorMessage) { FaultInjector<Color> f; ASSERT_EQ(f.check(Color::Red), 0); f.inject(Color::Red, InjectError{-EINVAL, dpp()}); EXPECT_EQ(f.check(Color::Red), -EINVAL); } // test custom move-only Key type using FaultInjectorMoveOnly = Fixture; struct MoveOnlyKey { MoveOnlyKey() = default; MoveOnlyKey(const MoveOnlyKey&) = delete; MoveOnlyKey& operator=(const MoveOnlyKey&) = delete; MoveOnlyKey(MoveOnlyKey&&) = default; MoveOnlyKey& operator=(MoveOnlyKey&&) = default; ~MoveOnlyKey() = default; }; static bool operator==(const MoveOnlyKey&, const MoveOnlyKey&) { return true; // all keys are equal } static std::ostream& operator<<(std::ostream& out, const MoveOnlyKey&) { return out; } TEST_F(FaultInjectorMoveOnly, Default) { constexpr FaultInjector<MoveOnlyKey> f; EXPECT_EQ(f.check(MoveOnlyKey{}), 0); } TEST_F(FaultInjectorMoveOnly, InjectError) { FaultInjector f{MoveOnlyKey{}, InjectError{-EIO}}; EXPECT_EQ(f.check(MoveOnlyKey{}), -EIO); } TEST_F(FaultInjectorMoveOnly, InjectErrorMessage) { FaultInjector f{MoveOnlyKey{}, InjectError{-EIO, dpp()}}; EXPECT_EQ(f.check(MoveOnlyKey{}), -EIO); } TEST_F(FaultInjectorMoveOnly, AssignError) { FaultInjector<MoveOnlyKey> f; ASSERT_EQ(f.check({}), 0); f.inject({}, InjectError{-EINVAL}); EXPECT_EQ(f.check({}), -EINVAL); } TEST_F(FaultInjectorMoveOnly, AssignErrorMessage) { FaultInjector<MoveOnlyKey> f; ASSERT_EQ(f.check({}), 0); f.inject({}, InjectError{-EINVAL, dpp()}); EXPECT_EQ(f.check({}), -EINVAL); }
6,477
25.016064
79
cc
null
ceph-main/src/test/common/test_global_doublefree.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2016 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ /* * This test is linked against librados and libcephfs to try and detect issues * with global, static, non-POD variables as seen in the following trackers. * http://tracker.ceph.com/issues/16504 * http://tracker.ceph.com/issues/16686 * In those trackers such variables caused segfaults with glibc reporting * "double free or corruption". * * Don't be fooled by its emptiness. It does serve a purpose :) */ int main(int, char**) { return 0; }
863
26.870968
78
cc
null
ceph-main/src/test/common/test_hobject.cc
#include "common/hobject.h" #include "gtest/gtest.h" TEST(HObject, cmp) { hobject_t c{object_t{"fooc"}, "food", CEPH_NOSNAP, 42, 0, "nspace"}; hobject_t d{object_t{"food"}, "", CEPH_NOSNAP, 42, 0, "nspace"}; hobject_t e{object_t{"fooe"}, "food", CEPH_NOSNAP, 42, 0, "nspace"}; ASSERT_EQ(-1, cmp(c, d)); ASSERT_EQ(-1, cmp(d, e)); }
346
27.916667
70
cc
null
ceph-main/src/test/common/test_hostname.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "gtest/gtest.h" #include "common/hostname.h" #include "common/SubProcess.h" #include "stdio.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "unistd.h" #include <array> #include <iostream> #include <stdexcept> #include <stdio.h> #include <string> #include <memory> std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != NULL) result += buffer.data(); } // remove \n return result.substr(0, result.size()-1);; } TEST(Hostname, full) { std::string hn = ceph_get_hostname(); if (const char *nn = getenv("NODE_NAME")) { // we are in a container std::cout << "we are in a container on " << nn << ", reporting " << hn << std::endl; ASSERT_EQ(hn, nn); } else { ASSERT_EQ(hn, exec("hostname")) ; } } TEST(Hostname, short) { std::string shn = ceph_get_short_hostname(); if (const char *nn = getenv("NODE_NAME")) { // we are in a container std::cout << "we are in a container on " << nn << ", reporting short " << shn << ", skipping test because env var may or may not be short form" << std::endl; } else { #ifdef _WIN32 ASSERT_EQ(shn, exec("hostname")); #else ASSERT_EQ(shn, exec("hostname -s")); #endif } }
1,907
25.5
81
cc
null
ceph-main/src/test/common/test_interval_map.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2016 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <gtest/gtest.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/mpl/apply.hpp> #include "include/buffer.h" #include "common/interval_map.h" using namespace std; template<typename T> class IntervalMapTest : public ::testing::Test { public: using TestType = T; }; template <typename _key> struct bufferlist_test_type { using key = _key; using value = bufferlist; struct make_splitter { template <typename merge_t> struct apply { bufferlist split( key offset, key len, bufferlist &bu) const { bufferlist bl; bl.substr_of(bu, offset, len); return bl; } bool can_merge(const bufferlist &left, const bufferlist &right) const { return merge_t::value; } bufferlist merge(bufferlist &&left, bufferlist &&right) const { bufferlist bl; left.claim_append(right); return std::move(left); } uint64_t length(const bufferlist &r) const { return r.length(); } }; }; struct generate_random { bufferlist operator()(key len) { bufferlist bl; boost::random::mt19937 rng; boost::random::uniform_int_distribution<> chr(0,255); for (key i = 0; i < len; ++i) { bl.append((char)chr(rng)); } return bl; } }; }; using IntervalMapTypes = ::testing::Types< bufferlist_test_type<uint64_t> >; TYPED_TEST_SUITE(IntervalMapTest, IntervalMapTypes); #define USING(_can_merge) \ using TT = typename TestFixture::TestType; \ using key = typename TT::key; (void)key(0); \ using val = typename TT::value; (void)val(0); \ using splitter = typename boost::mpl::apply< \ typename TT::make_splitter, \ _can_merge>; \ using imap = interval_map<key, val, splitter>; (void)imap(); \ typename TT::generate_random gen; \ val v(gen(5)); \ splitter split; (void)split.split(0, 0, v); #define USING_NO_MERGE USING(std::false_type) #define USING_WITH_MERGE USING(std::true_type) TYPED_TEST(IntervalMapTest, empty) { USING_NO_MERGE; imap m; ASSERT_TRUE(m.empty()); } TYPED_TEST(IntervalMapTest, insert) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5)}; m.insert(0, 5, vals[0]); m.insert(10, 5, vals[2]); m.insert(5, 5, vals[1]); ASSERT_EQ(m.ext_count(), 3u); unsigned i = 0; for (auto &&ext: m) { ASSERT_EQ(ext.get_len(), 5u); ASSERT_EQ(ext.get_off(), 5u * i); ASSERT_EQ(ext.get_val(), vals[i]); ++i; } ASSERT_EQ(i, m.ext_count()); } TYPED_TEST(IntervalMapTest, insert_begin_overlap) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5)}; m.insert(5, 5, vals[1]); m.insert(10, 5, vals[2]); m.insert(1, 5, vals[0]); auto iter = m.begin(); ASSERT_EQ(iter.get_off(), 1u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[0]); ++iter; ASSERT_EQ(iter.get_off(), 6u); ASSERT_EQ(iter.get_len(), 4u); ASSERT_EQ(iter.get_val(), split.split(1, 4, vals[1])); ++iter; ASSERT_EQ(iter.get_off(), 10u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[2]); ++iter; ASSERT_EQ(iter, m.end()); } TYPED_TEST(IntervalMapTest, insert_end_overlap) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5)}; m.insert(0, 5, vals[0]); m.insert(5, 5, vals[1]); m.insert(8, 5, vals[2]); auto iter = m.begin(); ASSERT_EQ(iter.get_off(), 0u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[0]); ++iter; ASSERT_EQ(iter.get_off(), 5u); ASSERT_EQ(iter.get_len(), 3u); ASSERT_EQ(iter.get_val(), split.split(0, 3, vals[1])); ++iter; ASSERT_EQ(iter.get_off(), 8u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[2]); ++iter; ASSERT_EQ(iter, m.end()); } TYPED_TEST(IntervalMapTest, insert_middle_overlap) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(7), gen(5)}; m.insert(0, 5, vals[0]); m.insert(10, 5, vals[2]); m.insert(4, 7, vals[1]); auto iter = m.begin(); ASSERT_EQ(iter.get_off(), 0u); ASSERT_EQ(iter.get_len(), 4u); ASSERT_EQ(iter.get_val(), split.split(0, 4, vals[0])); ++iter; ASSERT_EQ(iter.get_off(), 4u); ASSERT_EQ(iter.get_len(), 7u); ASSERT_EQ(iter.get_val(), vals[1]); ++iter; ASSERT_EQ(iter.get_off(), 11u); ASSERT_EQ(iter.get_len(), 4u); ASSERT_EQ(iter.get_val(), split.split(1, 4, vals[2])); ++iter; ASSERT_EQ(iter, m.end()); } TYPED_TEST(IntervalMapTest, insert_single_exact_overlap) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5)}; m.insert(0, 5, gen(5)); m.insert(5, 5, vals[1]); m.insert(10, 5, vals[2]); m.insert(0, 5, vals[0]); auto iter = m.begin(); ASSERT_EQ(iter.get_off(), 0u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[0]); ++iter; ASSERT_EQ(iter.get_off(), 5u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[1]); ++iter; ASSERT_EQ(iter.get_off(), 10u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[2]); ++iter; ASSERT_EQ(iter, m.end()); } TYPED_TEST(IntervalMapTest, insert_single_exact_overlap_end) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5)}; m.insert(0, 5, vals[0]); m.insert(5, 5, vals[1]); m.insert(10, 5, gen(5)); m.insert(10, 5, vals[2]); auto iter = m.begin(); ASSERT_EQ(iter.get_off(), 0u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[0]); ++iter; ASSERT_EQ(iter.get_off(), 5u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[1]); ++iter; ASSERT_EQ(iter.get_off(), 10u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[2]); ++iter; ASSERT_EQ(iter, m.end()); } TYPED_TEST(IntervalMapTest, erase) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5)}; m.insert(0, 5, vals[0]); m.insert(5, 5, vals[1]); m.insert(10, 5, vals[2]); m.erase(3, 5); auto iter = m.begin(); ASSERT_EQ(iter.get_off(), 0u); ASSERT_EQ(iter.get_len(), 3u); ASSERT_EQ(iter.get_val(), split.split(0, 3, vals[0])); ++iter; ASSERT_EQ(iter.get_off(), 8u); ASSERT_EQ(iter.get_len(), 2u); ASSERT_EQ(iter.get_val(), split.split(3, 2, vals[1])); ++iter; ASSERT_EQ(iter.get_off(), 10u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[2]); ++iter; ASSERT_EQ(iter, m.end()); } TYPED_TEST(IntervalMapTest, erase_exact) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5)}; m.insert(0, 5, vals[0]); m.insert(5, 5, vals[1]); m.insert(10, 5, vals[2]); m.erase(5, 5); auto iter = m.begin(); ASSERT_EQ(iter.get_off(), 0u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[0]); ++iter; ASSERT_EQ(iter.get_off(), 10u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[2]); ++iter; ASSERT_EQ(iter, m.end()); } TYPED_TEST(IntervalMapTest, get_containing_range) { USING_NO_MERGE; imap m; vector<val> vals{gen(5), gen(5), gen(5), gen(5)}; m.insert(0, 5, vals[0]); m.insert(10, 5, vals[1]); m.insert(20, 5, vals[2]); m.insert(30, 5, vals[3]); auto rng = m.get_containing_range(5, 21); auto iter = rng.first; ASSERT_EQ(iter.get_off(), 10u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[1]); ++iter; ASSERT_EQ(iter.get_off(), 20u); ASSERT_EQ(iter.get_len(), 5u); ASSERT_EQ(iter.get_val(), vals[2]); ++iter; ASSERT_EQ(iter, rng.second); } TYPED_TEST(IntervalMapTest, merge) { USING_WITH_MERGE; imap m; m.insert(10, 4, gen(4)); m.insert(11, 1, gen(1)); }
8,143
23.094675
77
cc
null
ceph-main/src/test/common/test_interval_set.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2015 Mirantis, Inc. * * Author: Igor Fedotov <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <gtest/gtest.h> #include <boost/container/flat_map.hpp> #include "include/interval_set.h" #include "include/btree_map.h" using namespace ceph; typedef uint64_t IntervalValueType; template<typename T> // tuple<type to test on, test array size> class IntervalSetTest : public ::testing::Test { public: typedef T ISet; }; typedef ::testing::Types< interval_set<IntervalValueType>, interval_set<IntervalValueType, btree::btree_map>, interval_set<IntervalValueType, boost::container::flat_map> > IntervalSetTypes; TYPED_TEST_SUITE(IntervalSetTest, IntervalSetTypes); TYPED_TEST(IntervalSetTest, compare) { typedef typename TestFixture::ISet ISet; ISet iset1, iset2; ASSERT_TRUE(iset1 == iset1); ASSERT_TRUE(iset1 == iset2); iset1.insert(1); ASSERT_FALSE(iset1 == iset2); iset2.insert(1); ASSERT_TRUE(iset1 == iset2); iset1.insert(2, 3); iset2.insert(2, 4); ASSERT_FALSE(iset1 == iset2); iset2.erase(2, 4); iset2.erase(1); iset2.insert(2, 3); iset2.insert(1); ASSERT_TRUE(iset1 == iset2); iset1.insert(100, 10); iset2.insert(100, 5); ASSERT_FALSE(iset1 == iset2); iset2.insert(105, 5); ASSERT_TRUE(iset1 == iset2); iset1.insert(200, 10); iset2.insert(205, 5); ASSERT_FALSE(iset1 == iset2); iset2.insert(200, 1); iset2.insert(202, 3); ASSERT_FALSE(iset1 == iset2); iset2.insert(201, 1); ASSERT_TRUE(iset1 == iset2); iset1.clear(); ASSERT_FALSE(iset1 == iset2); iset2.clear(); ASSERT_TRUE(iset1 == iset2); } TYPED_TEST(IntervalSetTest, contains) { typedef typename TestFixture::ISet ISet; ISet iset1; ASSERT_FALSE(iset1.contains( 1 )); ASSERT_FALSE(iset1.contains( 0, 1 )); iset1.insert(1); ASSERT_TRUE(iset1.contains( 1 )); ASSERT_FALSE(iset1.contains( 0 )); ASSERT_FALSE(iset1.contains( 2 )); ASSERT_FALSE(iset1.contains( 0, 1 )); ASSERT_FALSE(iset1.contains( 0, 2 )); ASSERT_TRUE(iset1.contains( 1, 1 )); ASSERT_FALSE(iset1.contains( 1, 2 )); iset1.insert(2, 3); ASSERT_TRUE(iset1.contains( 1 )); ASSERT_FALSE(iset1.contains( 0 )); ASSERT_TRUE(iset1.contains( 2 )); ASSERT_FALSE(iset1.contains( 0, 1 )); ASSERT_FALSE(iset1.contains( 0, 2 )); ASSERT_TRUE(iset1.contains( 1, 1 )); ASSERT_TRUE(iset1.contains( 1, 2 )); ASSERT_TRUE(iset1.contains( 1, 3 )); ASSERT_TRUE(iset1.contains( 1, 4 )); ASSERT_FALSE(iset1.contains( 1, 5 )); ASSERT_TRUE(iset1.contains( 2, 1 )); ASSERT_TRUE(iset1.contains( 2, 2 )); ASSERT_TRUE(iset1.contains( 2, 3 )); ASSERT_FALSE(iset1.contains( 2, 4 )); ASSERT_TRUE(iset1.contains( 3, 2 )); ASSERT_TRUE(iset1.contains( 4, 1 )); ASSERT_FALSE(iset1.contains( 4, 2 )); iset1.insert(10, 10); ASSERT_TRUE(iset1.contains( 1, 4 )); ASSERT_FALSE(iset1.contains( 1, 5 )); ASSERT_TRUE(iset1.contains( 2, 2 )); ASSERT_FALSE(iset1.contains( 2, 4 )); ASSERT_FALSE(iset1.contains( 1, 10 )); ASSERT_FALSE(iset1.contains( 9, 1 )); ASSERT_FALSE(iset1.contains( 9 )); ASSERT_FALSE(iset1.contains( 9, 11 )); ASSERT_TRUE(iset1.contains( 10, 1 )); ASSERT_TRUE(iset1.contains( 11, 9 )); ASSERT_TRUE(iset1.contains( 11, 2 )); ASSERT_TRUE(iset1.contains( 18, 2 )); ASSERT_TRUE(iset1.contains( 18, 2 )); ASSERT_TRUE(iset1.contains( 10 )); ASSERT_TRUE(iset1.contains( 19 )); ASSERT_FALSE(iset1.contains( 20 )); ASSERT_FALSE(iset1.contains( 21 )); ASSERT_FALSE(iset1.contains( 11, 11 )); ASSERT_FALSE(iset1.contains( 18, 9 )); iset1.clear(); ASSERT_FALSE(iset1.contains( 1 )); ASSERT_FALSE(iset1.contains( 0 )); ASSERT_FALSE(iset1.contains( 2 )); ASSERT_FALSE(iset1.contains( 0, 1 )); ASSERT_FALSE(iset1.contains( 0, 2 )); ASSERT_FALSE(iset1.contains( 1, 1 )); ASSERT_FALSE(iset1.contains( 10, 2 )); } TYPED_TEST(IntervalSetTest, intersects) { typedef typename TestFixture::ISet ISet; ISet iset1; ASSERT_FALSE(iset1.intersects( 1, 1 )); ASSERT_FALSE(iset1.intersects( 0, 1 )); ASSERT_FALSE(iset1.intersects( 0, 10 )); iset1.insert(1); ASSERT_TRUE(iset1.intersects( 1, 1 )); ASSERT_FALSE(iset1.intersects( 0, 1 )); ASSERT_FALSE(iset1.intersects( 2, 1 )); ASSERT_TRUE(iset1.intersects( 0, 2 )); ASSERT_TRUE(iset1.intersects( 0, 20 )); ASSERT_TRUE(iset1.intersects( 1, 2 )); ASSERT_TRUE(iset1.intersects( 1, 20 )); iset1.insert(2, 3); ASSERT_FALSE(iset1.intersects( 0, 1 )); ASSERT_TRUE(iset1.intersects( 0, 2 )); ASSERT_TRUE(iset1.intersects( 0, 200 )); ASSERT_TRUE(iset1.intersects( 1, 1 )); ASSERT_TRUE(iset1.intersects( 1, 4 )); ASSERT_TRUE(iset1.intersects( 1, 5 )); ASSERT_TRUE(iset1.intersects( 2, 1 )); ASSERT_TRUE(iset1.intersects( 2, 2 )); ASSERT_TRUE(iset1.intersects( 2, 3 )); ASSERT_TRUE(iset1.intersects( 2, 4 )); ASSERT_TRUE(iset1.intersects( 3, 2 )); ASSERT_TRUE(iset1.intersects( 4, 1 )); ASSERT_TRUE(iset1.intersects( 4, 2 )); ASSERT_FALSE(iset1.intersects( 5, 2 )); iset1.insert(10, 10); ASSERT_TRUE(iset1.intersects( 1, 4 )); ASSERT_TRUE(iset1.intersects( 1, 5 )); ASSERT_TRUE(iset1.intersects( 1, 10 )); ASSERT_TRUE(iset1.intersects( 2, 2 )); ASSERT_TRUE(iset1.intersects( 2, 4 )); ASSERT_FALSE(iset1.intersects( 5, 1 )); ASSERT_FALSE(iset1.intersects( 5, 2 )); ASSERT_FALSE(iset1.intersects( 5, 5 )); ASSERT_TRUE(iset1.intersects( 5, 12 )); ASSERT_TRUE(iset1.intersects( 5, 20 )); ASSERT_FALSE(iset1.intersects( 9, 1 )); ASSERT_TRUE(iset1.intersects( 9, 2 )); ASSERT_TRUE(iset1.intersects( 9, 11 )); ASSERT_TRUE(iset1.intersects( 10, 1 )); ASSERT_TRUE(iset1.intersects( 11, 9 )); ASSERT_TRUE(iset1.intersects( 11, 2 )); ASSERT_TRUE(iset1.intersects( 11, 11 )); ASSERT_TRUE(iset1.intersects( 18, 2 )); ASSERT_TRUE(iset1.intersects( 18, 9 )); ASSERT_FALSE(iset1.intersects( 20, 1 )); ASSERT_FALSE(iset1.intersects( 21, 12 )); iset1.clear(); ASSERT_FALSE(iset1.intersects( 0, 1 )); ASSERT_FALSE(iset1.intersects( 0, 2 )); ASSERT_FALSE(iset1.intersects( 1, 1 )); ASSERT_FALSE(iset1.intersects( 5, 2 )); ASSERT_FALSE(iset1.intersects( 10, 2 )); } TYPED_TEST(IntervalSetTest, insert_erase) { typedef typename TestFixture::ISet ISet; ISet iset1, iset2; IntervalValueType start, len; iset1.insert(3, 5, &start, &len); ASSERT_EQ(3, start); ASSERT_EQ(5, len); ASSERT_EQ(1, iset1.num_intervals()); ASSERT_EQ(5, iset1.size()); //adding standalone interval iset1.insert(15, 10, &start, &len); ASSERT_EQ(15, start); ASSERT_EQ(10, len); ASSERT_EQ(2, iset1.num_intervals()); ASSERT_EQ(15, iset1.size()); //adding leftmost standalone interval iset1.insert(1, 1, &start, &len); ASSERT_EQ(1, start); ASSERT_EQ(1, len); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(16, iset1.size()); //adding leftmost adjucent interval iset1.insert(0, 1, &start, &len); ASSERT_EQ(0, start); ASSERT_EQ(2, len); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(17, iset1.size()); //adding interim interval that merges leftmost and subseqent intervals iset1.insert(2, 1, &start, &len); ASSERT_EQ(0, start); ASSERT_EQ(8, len); ASSERT_EQ(2, iset1.num_intervals()); ASSERT_EQ(18, iset1.size()); //adding rigtmost standalone interval iset1.insert(30, 5, &start, &len); ASSERT_EQ(30, start); ASSERT_EQ(5, len); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(23, iset1.size()); //adding rigtmost adjusent interval iset1.insert(35, 10, &start, &len); ASSERT_EQ(30, start); ASSERT_EQ(15, len ); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(33, iset1.size()); //adding interim interval that merges with the interval preceeding the rightmost iset1.insert(25, 1, &start, &len); ASSERT_EQ(15, start); ASSERT_EQ(11, len); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(34, iset1.size()); //adding interim interval that merges with the rightmost and preceeding intervals iset1.insert(26, 4, &start, &len); ASSERT_EQ(15, start); ASSERT_EQ(30, len); ASSERT_EQ(2, iset1.num_intervals()); ASSERT_EQ(38, iset1.size()); //and finally build single interval filling the gap at 8-15 using different interval set iset2.insert( 8, 1 ); iset2.insert( 14, 1 ); iset2.insert( 9, 4 ); iset1.insert( iset2 ); iset1.insert(13, 1, &start, &len); ASSERT_EQ(0, start); ASSERT_EQ(45, len); ASSERT_EQ(1, iset1.num_intervals()); ASSERT_EQ(45, iset1.size()); //now reverses the process using subtract & erase iset1.subtract( iset2 ); iset1.erase(13, 1); ASSERT_EQ( 2, iset1.num_intervals() ); ASSERT_EQ(38, iset1.size()); ASSERT_TRUE( iset1.contains( 7, 1 )); ASSERT_FALSE( iset1.contains( 8, 7 )); ASSERT_TRUE( iset1.contains( 15, 1 )); ASSERT_TRUE( iset1.contains( 26, 4 )); iset1.erase(26, 4); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(34, iset1.size()); ASSERT_TRUE( iset1.contains( 7, 1 )); ASSERT_FALSE( iset1.intersects( 8, 7 )); ASSERT_TRUE( iset1.contains( 15, 1 )); ASSERT_TRUE( iset1.contains( 25, 1 )); ASSERT_FALSE( iset1.contains( 26, 4 )); ASSERT_TRUE( iset1.contains( 30, 1 )); iset1.erase(25, 1); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(33, iset1.size()); ASSERT_TRUE( iset1.contains( 24, 1 )); ASSERT_FALSE( iset1.contains( 25, 1 )); ASSERT_FALSE( iset1.intersects( 26, 4 )); ASSERT_TRUE( iset1.contains( 30, 1 )); ASSERT_TRUE( iset1.contains( 35, 10 )); iset1.erase(35, 10); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(23, iset1.size()); ASSERT_TRUE( iset1.contains( 30, 5 )); ASSERT_TRUE( iset1.contains( 34, 1 )); ASSERT_FALSE( iset1.contains( 35, 10 )); ASSERT_FALSE(iset1.contains( 45, 1 )); iset1.erase(30, 5); ASSERT_EQ(2, iset1.num_intervals()); ASSERT_EQ(18, iset1.size()); ASSERT_TRUE( iset1.contains( 2, 1 )); ASSERT_TRUE( iset1.contains( 24, 1 )); ASSERT_FALSE( iset1.contains( 25, 1 )); ASSERT_FALSE( iset1.contains( 29, 1 )); ASSERT_FALSE( iset1.contains( 30, 5 )); ASSERT_FALSE( iset1.contains( 35, 1 )); iset1.erase(2, 1); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ( iset1.size(), 17 ); ASSERT_TRUE( iset1.contains( 0, 1 )); ASSERT_TRUE( iset1.contains( 1, 1 )); ASSERT_FALSE( iset1.contains( 2, 1 )); ASSERT_TRUE( iset1.contains( 3, 1 )); ASSERT_TRUE( iset1.contains( 15, 1 )); ASSERT_FALSE( iset1.contains( 25, 1 )); iset1.erase( 0, 1); ASSERT_EQ(3, iset1.num_intervals()); ASSERT_EQ(16, iset1.size()); ASSERT_FALSE( iset1.contains( 0, 1 )); ASSERT_TRUE( iset1.contains( 1, 1 )); ASSERT_FALSE( iset1.contains( 2, 1 )); ASSERT_TRUE( iset1.contains( 3, 1 )); ASSERT_TRUE( iset1.contains( 15, 1 )); iset1.erase(1, 1); ASSERT_EQ(2, iset1.num_intervals()); ASSERT_EQ(15, iset1.size()); ASSERT_FALSE( iset1.contains( 1, 1 )); ASSERT_TRUE( iset1.contains( 15, 10 )); ASSERT_TRUE( iset1.contains( 3, 5 )); iset1.erase(15, 10); ASSERT_EQ(1, iset1.num_intervals()); ASSERT_EQ(5, iset1.size()); ASSERT_FALSE( iset1.contains( 1, 1 )); ASSERT_FALSE( iset1.contains( 15, 10 )); ASSERT_FALSE( iset1.contains( 25, 1 )); ASSERT_TRUE( iset1.contains( 3, 5 )); iset1.erase( 3, 1); ASSERT_EQ(1, iset1.num_intervals()); ASSERT_EQ(4, iset1.size()); ASSERT_FALSE( iset1.contains( 1, 1 )); ASSERT_FALSE( iset1.contains( 15, 10 )); ASSERT_FALSE( iset1.contains( 25, 1 )); ASSERT_TRUE( iset1.contains( 4, 4 )); ASSERT_FALSE( iset1.contains( 3, 5 )); iset1.erase( 4, 4); ASSERT_EQ(0, iset1.num_intervals()); ASSERT_EQ(0, iset1.size()); ASSERT_FALSE( iset1.contains( 1, 1 )); ASSERT_FALSE( iset1.contains( 15, 10 )); ASSERT_FALSE( iset1.contains( 25, 1 )); ASSERT_FALSE( iset1.contains( 3, 4 )); ASSERT_FALSE( iset1.contains( 3, 5 )); ASSERT_FALSE( iset1.contains( 4, 4 )); } TYPED_TEST(IntervalSetTest, intersect_of) { typedef typename TestFixture::ISet ISet; ISet iset1, iset2, iset3; iset1.intersection_of( iset2, iset3 ); ASSERT_TRUE( iset1.num_intervals() == 0); ASSERT_TRUE( iset1.size() == 0); iset2.insert( 0, 1 ); iset2.insert( 5, 10 ); iset2.insert( 30, 10 ); iset3.insert( 0, 2 ); iset3.insert( 15, 1 ); iset3.insert( 20, 5 ); iset3.insert( 29, 3 ); iset3.insert( 35, 3 ); iset3.insert( 39, 3 ); iset1.intersection_of( iset2, iset3 ); ASSERT_TRUE( iset1.num_intervals() == 4); ASSERT_TRUE( iset1.size() == 7); ASSERT_TRUE( iset1.contains( 0, 1 )); ASSERT_FALSE( iset1.contains( 0, 2 )); ASSERT_FALSE( iset1.contains( 5, 11 )); ASSERT_FALSE( iset1.contains( 4, 1 )); ASSERT_FALSE( iset1.contains( 16, 1 )); ASSERT_FALSE( iset1.contains( 20, 5 )); ASSERT_FALSE( iset1.contains( 29, 1 )); ASSERT_FALSE( iset1.contains( 30, 10 )); ASSERT_TRUE( iset1.contains( 30, 2 )); ASSERT_TRUE( iset1.contains( 35, 3 )); ASSERT_FALSE( iset1.contains( 35, 4 )); ASSERT_TRUE( iset1.contains( 39, 1 )); ASSERT_FALSE( iset1.contains( 38, 2 )); ASSERT_FALSE( iset1.contains( 39, 2 )); iset3=iset1; iset1.intersection_of(iset2); ASSERT_TRUE( iset1 == iset3); iset2.clear(); iset2.insert(0,1); iset1.intersection_of(iset2); ASSERT_TRUE( iset1.num_intervals() == 1); ASSERT_TRUE( iset1.size() == 1); iset1 = iset3; iset2.clear(); iset1.intersection_of(iset2); ASSERT_TRUE( iset1.num_intervals() == 0); ASSERT_TRUE( iset1.size() == 0); } TYPED_TEST(IntervalSetTest, union_of) { typedef typename TestFixture::ISet ISet; ISet iset1, iset2, iset3; iset1.union_of( iset2, iset3 ); ASSERT_TRUE( iset1.num_intervals() == 0); ASSERT_TRUE( iset1.size() == 0); iset2.insert( 0, 1 ); iset2.insert( 5, 10 ); iset2.insert( 30, 10 ); iset3.insert( 0, 2 ); iset3.insert( 15, 1 ); iset3.insert( 20, 5 ); iset3.insert( 29, 3 ); iset3.insert( 39, 3 ); iset1.union_of( iset2, iset3 ); ASSERT_TRUE( iset1.num_intervals() == 4); ASSERT_EQ( iset1.size(), 31); ASSERT_TRUE( iset1.contains( 0, 2 )); ASSERT_FALSE( iset1.contains( 0, 3 )); ASSERT_TRUE( iset1.contains( 5, 11 )); ASSERT_FALSE( iset1.contains( 4, 1 )); ASSERT_FALSE( iset1.contains( 16, 1 )); ASSERT_TRUE( iset1.contains( 20, 5 )); ASSERT_TRUE( iset1.contains( 30, 10 )); ASSERT_TRUE( iset1.contains( 29, 13 )); ASSERT_FALSE( iset1.contains( 29, 14 )); ASSERT_FALSE( iset1.contains( 42, 1 )); iset2.clear(); iset1.union_of(iset2); ASSERT_TRUE( iset1.num_intervals() == 4); ASSERT_EQ( iset1.size(), 31); iset3.clear(); iset3.insert( 29, 3 ); iset3.insert( 39, 2 ); iset1.union_of(iset3); ASSERT_TRUE( iset1.num_intervals() == 4); ASSERT_EQ( iset1.size(), 31); //actually we added nothing ASSERT_TRUE( iset1.contains( 29, 13 )); ASSERT_FALSE( iset1.contains( 29, 14 )); ASSERT_FALSE( iset1.contains( 42, 1 )); } TYPED_TEST(IntervalSetTest, subset_of) { typedef typename TestFixture::ISet ISet; ISet iset1, iset2; ASSERT_TRUE(iset1.subset_of(iset2)); iset1.insert(5,10); ASSERT_FALSE(iset1.subset_of(iset2)); iset2.insert(6,8); ASSERT_FALSE(iset1.subset_of(iset2)); iset2.insert(5,1); ASSERT_FALSE(iset1.subset_of(iset2)); iset2.insert(14,10); ASSERT_TRUE(iset1.subset_of(iset2)); iset1.insert( 20, 4); ASSERT_TRUE(iset1.subset_of(iset2)); iset1.insert( 24, 1); ASSERT_FALSE(iset1.subset_of(iset2)); iset2.insert( 24, 1); ASSERT_TRUE(iset1.subset_of(iset2)); iset1.insert( 30, 5); ASSERT_FALSE(iset1.subset_of(iset2)); iset2.insert( 30, 5); ASSERT_TRUE(iset1.subset_of(iset2)); iset2.erase( 30, 1); ASSERT_FALSE(iset1.subset_of(iset2)); iset1.erase( 30, 1); ASSERT_TRUE(iset1.subset_of(iset2)); iset2.erase( 34, 1); ASSERT_FALSE(iset1.subset_of(iset2)); iset1.erase( 34, 1); ASSERT_TRUE(iset1.subset_of(iset2)); iset1.insert( 40, 5); ASSERT_FALSE(iset1.subset_of(iset2)); iset2.insert( 39, 7); ASSERT_TRUE(iset1.subset_of(iset2)); iset1.insert( 50, 5); iset2.insert( 55, 2); ASSERT_FALSE(iset1.subset_of(iset2)); } TYPED_TEST(IntervalSetTest, span_of) { typedef typename TestFixture::ISet ISet; ISet iset1, iset2; iset2.insert(5,5); iset2.insert(20,5); iset1.span_of( iset2, 8, 5 ); ASSERT_EQ( iset1.num_intervals(), 2); ASSERT_EQ( iset1.size(), 5); ASSERT_TRUE( iset1.contains( 8, 2 )); ASSERT_TRUE( iset1.contains( 20, 3 )); iset1.span_of( iset2, 3, 5 ); ASSERT_EQ( iset1.num_intervals(), 1); ASSERT_EQ( iset1.size(), 5); ASSERT_TRUE( iset1.contains( 5, 5 )); iset1.span_of( iset2, 10, 7 ); ASSERT_EQ( iset1.num_intervals(), 1); ASSERT_EQ( iset1.size(), 5); ASSERT_TRUE( iset1.contains( 20, 5 )); ASSERT_FALSE( iset1.contains( 20, 6 )); iset1.span_of( iset2, 5, 10); ASSERT_EQ( iset1.num_intervals(), 2); ASSERT_EQ( iset1.size(), 10); ASSERT_TRUE( iset1.contains( 5, 5 )); ASSERT_TRUE( iset1.contains( 20, 5 )); iset1.span_of( iset2, 100, 5 ); ASSERT_EQ( iset1.num_intervals(), 0); ASSERT_EQ( iset1.size(), 0); }
17,188
27.600666
91
cc
null
ceph-main/src/test/common/test_intrusive_lru.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <stdio.h> #include "gtest/gtest.h" #include "common/intrusive_lru.h" template <typename TestLRUItem> struct item_to_unsigned { using type = unsigned; const type &operator()(const TestLRUItem &item) { return item.key; } }; struct TestLRUItem : public ceph::common::intrusive_lru_base< ceph::common::intrusive_lru_config< unsigned, TestLRUItem, item_to_unsigned<TestLRUItem>>> { unsigned key = 0; int value = 0; TestLRUItem(unsigned key) : key(key) {} }; class LRUTest : public TestLRUItem::lru_t { public: auto add(unsigned int key, int value) { auto [ref, key_existed] = get_or_create(key); if (!key_existed) { ref->value = value; } return std::pair(ref, key_existed); } }; TEST(LRU, add_immediate_evict) { LRUTest cache; unsigned int key = 1; int value1 = 2; int value2 = 3; { auto [ref, existed] = cache.add(key, value1); ASSERT_TRUE(ref); ASSERT_EQ(value1, ref->value); ASSERT_FALSE(existed); } { auto [ref2, existed] = cache.add(key, value2); ASSERT_EQ(value2, ref2->value); ASSERT_FALSE(existed); } } TEST(LRU, lookup_lru_size) { LRUTest cache; int key = 1; int value = 1; cache.set_target_size(1); { auto [ref, existed] = cache.add(key, value); ASSERT_TRUE(ref); ASSERT_FALSE(existed); } { auto [ref, existed] = cache.add(key, value); ASSERT_TRUE(ref); ASSERT_TRUE(existed); } cache.set_target_size(0); auto [ref2, existed2] = cache.add(key, value); ASSERT_TRUE(ref2); ASSERT_FALSE(existed2); { auto [ref, existed] = cache.add(key, value); ASSERT_TRUE(ref); ASSERT_TRUE(existed); } } TEST(LRU, eviction) { const unsigned SIZE = 3; LRUTest cache; cache.set_target_size(SIZE); for (unsigned i = 0; i < SIZE; ++i) { auto [ref, existed] = cache.add(i, i); ASSERT_TRUE(ref && !existed); } { auto [ref, existed] = cache.add(0, 0); ASSERT_TRUE(ref && existed); } for (unsigned i = SIZE; i < (2*SIZE) - 1; ++i) { auto [ref, existed] = cache.add(i, i); ASSERT_TRUE(ref && !existed); } { auto [ref, existed] = cache.add(0, 0); ASSERT_TRUE(ref && existed); } for (unsigned i = 1; i < SIZE; ++i) { auto [ref, existed] = cache.add(i, i); ASSERT_TRUE(ref && !existed); } } TEST(LRU, eviction_live_ref) { const unsigned SIZE = 3; LRUTest cache; cache.set_target_size(SIZE); auto [live_ref, existed2] = cache.add(1, 1); ASSERT_TRUE(live_ref && !existed2); for (unsigned i = 0; i < SIZE; ++i) { auto [ref, existed] = cache.add(i, i); ASSERT_TRUE(ref); if (i == 1) { ASSERT_TRUE(existed); } else { ASSERT_FALSE(existed); } } { auto [ref, existed] = cache.add(0, 0); ASSERT_TRUE(ref && existed); } for (unsigned i = SIZE; i < (2*SIZE) - 1; ++i) { auto [ref, existed] = cache.add(i, i); ASSERT_TRUE(ref && !existed); } for (unsigned i = 0; i < SIZE; ++i) { auto [ref, existed] = cache.add(i, i); ASSERT_TRUE(ref); if (i == 1) { ASSERT_TRUE(existed); } else { ASSERT_FALSE(existed); } } } TEST(LRU, clear_range) { LRUTest cache; const unsigned SIZE = 10; cache.set_target_size(SIZE); { auto [ref, existed] = cache.add(1, 4); ASSERT_FALSE(existed); } { auto [ref, existed] = cache.add(2, 4); ASSERT_FALSE(existed); } { auto [ref, existed] = cache.add(3, 4); ASSERT_FALSE(existed); } // Unlike above, the reference is not being destroyed auto [live_ref1, existed1] = cache.add(4, 4); ASSERT_FALSE(existed1); auto [live_ref2, existed2] = cache.add(5, 4); ASSERT_FALSE(existed2); cache.clear_range(0,4); // Should not exists (Unreferenced): { auto [ref, existed] = cache.add(1, 4); ASSERT_FALSE(existed); } { auto [ref, existed] = cache.add(2, 4); ASSERT_FALSE(existed); } { auto [ref, existed] = cache.add(3, 4); ASSERT_FALSE(existed); } // Should exist (Still being referenced): { auto [ref, existed] = cache.add(4, 4); ASSERT_TRUE(existed); } // Should exists (Still being referenced and wasn't removed) { auto [ref, existed] = cache.add(5, 4); ASSERT_TRUE(existed); } // Test out of bound deletion: { cache.clear_range(3,8); auto [ref, existed] = cache.add(4, 4); ASSERT_TRUE(existed); } { auto [ref, existed] = cache.add(3, 4); ASSERT_FALSE(existed); } }
4,551
20.779904
70
cc
null
ceph-main/src/test/common/test_iso_8601.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2017 Red Hat <[email protected]> * * LGPL-2.1 (see COPYING-LGPL2.1) or later */ #include <chrono> #include <gtest/gtest.h> #include "common/ceph_time.h" #include "common/iso_8601.h" using std::chrono::minutes; using std::chrono::seconds; using std::chrono::time_point_cast; using ceph::from_iso_8601; using ceph::iso_8601_format; using ceph::real_clock; using ceph::real_time; using ceph::to_iso_8601; TEST(iso_8601, epoch) { const auto epoch = real_clock::from_time_t(0); ASSERT_EQ("1970", to_iso_8601(epoch, iso_8601_format::Y)); ASSERT_EQ("1970-01", to_iso_8601(epoch, iso_8601_format::YM)); ASSERT_EQ("1970-01-01", to_iso_8601(epoch, iso_8601_format::YMD)); ASSERT_EQ("1970-01-01T00Z", to_iso_8601(epoch, iso_8601_format::YMDh)); ASSERT_EQ("1970-01-01T00:00Z", to_iso_8601(epoch, iso_8601_format::YMDhm)); ASSERT_EQ("1970-01-01T00:00:00Z", to_iso_8601(epoch, iso_8601_format::YMDhms)); ASSERT_EQ("1970-01-01T00:00:00.000000000Z", to_iso_8601(epoch, iso_8601_format::YMDhmsn)); ASSERT_EQ(epoch, *from_iso_8601("1970")); ASSERT_EQ(epoch, *from_iso_8601("1970-01")); ASSERT_EQ(epoch, *from_iso_8601("1970-01-01")); ASSERT_EQ(epoch, *from_iso_8601("1970-01-01T00:00Z")); ASSERT_EQ(epoch, *from_iso_8601("1970-01-01T00:00:00Z")); ASSERT_EQ(epoch, *from_iso_8601("1970-01-01T00:00:00.000000000Z")); } TEST(iso_8601, now) { const auto now = real_clock::now(); ASSERT_EQ(real_time(time_point_cast<minutes>(now)), *from_iso_8601(to_iso_8601(now, iso_8601_format::YMDhm))); ASSERT_EQ(real_time(time_point_cast<seconds>(now)), *from_iso_8601( to_iso_8601(now, iso_8601_format::YMDhms))); ASSERT_EQ(now, *from_iso_8601( to_iso_8601(now, iso_8601_format::YMDhmsn))); }
1,913
30.377049
77
cc
null
ceph-main/src/test/common/test_journald_logger.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <cerrno> #include <gtest/gtest.h> #include <sys/stat.h> #include "common/Journald.h" #include "log/Entry.h" #include "log/SubsystemMap.h" using namespace ceph::logging; class JournaldLoggerTest : public ::testing::Test { protected: SubsystemMap subs; JournaldLogger journald = {&subs}; MutableEntry entry = {0, 0}; void SetUp() override { struct stat buffer; if (stat("/run/systemd/journal/socket", &buffer) < 0) { if (errno == ENOENT) { GTEST_SKIP() << "No journald socket present."; } FAIL() << "Unexpected stat error: " << strerror(errno); } } }; TEST_F(JournaldLoggerTest, Log) { entry.get_ostream() << "This is a testing regular log message."; EXPECT_EQ(journald.log_entry(entry), 0); } TEST_F(JournaldLoggerTest, VeryLongLog) { entry.get_ostream() << std::string(16 * 1024 * 1024, 'a'); EXPECT_EQ(journald.log_entry(entry), 0); }
1,007
23
70
cc
null
ceph-main/src/test/common/test_json_formattable.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * */ #include <errno.h> #include <gtest/gtest.h> #include "common/ceph_json.h" #include <sstream> using namespace std; static void get_jf(const string& s, JSONFormattable *f) { JSONParser p; bool result = p.parse(s.c_str(), s.size()); if (!result) { cout << "Failed to parse: '" << s << "'" << std::endl; } ASSERT_EQ(true, result); try { decode_json_obj(*f, &p); } catch (JSONDecoder::err& e) { ASSERT_TRUE(0 == "Failed to decode JSON object"); } } TEST(formatable, str) { JSONFormattable f; get_jf("{ \"foo\": \"bar\" }", &f); ASSERT_EQ((string)f["foo"], "bar"); ASSERT_EQ((string)f["fooz"], ""); ASSERT_EQ((string)f["fooz"]("lala"), "lala"); } TEST(formatable, str2) { JSONFormattable f; get_jf("{ \"foo\": \"bar\" }", &f); ASSERT_EQ((string)f["foo"], "bar"); ASSERT_EQ((string)f["fooz"], ""); ASSERT_EQ((string)f["fooz"]("lala"), "lala"); JSONFormattable f2; get_jf("{ \"foo\": \"bar\", \"fooz\": \"zzz\" }", &f2); ASSERT_EQ((string)f2["foo"], "bar"); ASSERT_NE((string)f2["fooz"], ""); ASSERT_EQ((string)f2["fooz"], "zzz"); ASSERT_EQ((string)f2["fooz"]("lala"), "zzz"); } TEST(formatable, str3) { JSONFormattable f; get_jf("{ \"foo\": \"1234bar56\" }", &f); ASSERT_EQ((string)f["foo"], "1234bar56"); } TEST(formatable, int) { JSONFormattable f; get_jf("{ \"foo\": 1 }", &f); ASSERT_EQ((int)f["foo"], 1); ASSERT_EQ((int)f["fooz"], 0); ASSERT_EQ((int)f["fooz"](3), 3); JSONFormattable f2; get_jf("{ \"foo\": \"bar\", \"fooz\": \"123\" }", &f2); ASSERT_EQ((string)f2["foo"], "bar"); ASSERT_NE((int)f2["fooz"], 0); ASSERT_EQ((int)f2["fooz"], 123); ASSERT_EQ((int)f2["fooz"](111), 123); } TEST(formatable, bool) { JSONFormattable f; get_jf("{ \"foo\": \"true\" }", &f); ASSERT_EQ((bool)f["foo"], true); ASSERT_EQ((bool)f["fooz"], false); ASSERT_EQ((bool)f["fooz"](true), true); JSONFormattable f2; get_jf("{ \"foo\": \"false\" }", &f); ASSERT_EQ((bool)f["foo"], false); } TEST(formatable, nested) { JSONFormattable f; get_jf("{ \"obj\": { \"foo\": 1, \"inobj\": { \"foo\": 2 } } }", &f); ASSERT_EQ((int)f["foo"], 0); ASSERT_EQ((int)f["obj"]["foo"], 1); ASSERT_EQ((int)f["obj"]["inobj"]["foo"], 2); } TEST(formatable, array) { JSONFormattable f; get_jf("{ \"arr\": [ { \"foo\": 1, \"inobj\": { \"foo\": 2 } }," "{ \"foo\": 2 } ] }", &f); int i = 1; for (auto a : f.array()) { ASSERT_EQ((int)a["foo"], i); ++i; } JSONFormattable f2; get_jf("{ \"arr\": [ 0, 1, 2, 3, 4 ]}", &f2); i = 0; for (auto a : f2.array()) { ASSERT_EQ((int)a, i); ++i; } } TEST(formatable, bin_encode) { JSONFormattable f, f2; get_jf("{ \"arr\": [ { \"foo\": 1, \"bar\": \"aaa\", \"inobj\": { \"foo\": 2 } }," "{ \"foo\": 2, \"inobj\": { \"foo\": 3 } } ] }", &f); int i = 1; for (auto a : f.array()) { ASSERT_EQ((int)a["foo"], i); ASSERT_EQ((int)a["foo"]["inobj"], i + 1); ASSERT_EQ((string)a["bar"], "aaa"); ++i; } bufferlist bl; ::encode(f, bl); auto iter = bl.cbegin(); try { ::decode(f2, iter); } catch (buffer::error& err) { ASSERT_TRUE(0 == "Failed to decode object"); } i = 1; for (auto a : f2.array()) { ASSERT_EQ((int)a["foo"], i); ASSERT_EQ((int)a["foo"]["inobj"], i + 1); ASSERT_EQ((string)a["bar"], "aaa"); ++i; } } TEST(formatable, json_encode) { JSONFormattable f, f2; get_jf("{ \"arr\": [ { \"foo\": 1, \"bar\": \"aaa\", \"inobj\": { \"foo\": 2 } }," "{ \"foo\": 2, \"inobj\": { \"foo\": 3 } } ] }", &f); JSONFormatter formatter; formatter.open_object_section("bla"); ::encode_json("f", f, &formatter); formatter.close_section(); stringstream ss; formatter.flush(ss); get_jf(ss.str(), &f2); int i = 1; for (auto a : f2.array()) { ASSERT_EQ((int)a["foo"], i); ASSERT_EQ((int)a["foo"]["inobj"], i + 1); ASSERT_EQ((string)a["bar"], "aaa"); ++i; } } TEST(formatable, set) { JSONFormattable f, f2; f.set("", "{ \"abc\": \"xyz\"}"); ASSERT_EQ((string)f["abc"], "xyz"); f.set("aaa", "111"); ASSERT_EQ((string)f["abc"], "xyz"); ASSERT_EQ((int)f["aaa"], 111); f.set("obj", "{ \"a\": \"10\", \"b\": \"20\"}"); ASSERT_EQ((int)f["obj"]["a"], 10); ASSERT_EQ((int)f["obj"]["b"], 20); f.set("obj.c", "30"); ASSERT_EQ((int)f["obj"]["c"], 30); } TEST(formatable, set2) { JSONFormattable f; f.set("foo", "1234bar56"); ASSERT_EQ((string)f["foo"], "1234bar56"); } TEST(formatable, erase) { JSONFormattable f, f2; f.set("", "{ \"abc\": \"xyz\"}"); ASSERT_EQ((string)f["abc"], "xyz"); f.set("aaa", "111"); ASSERT_EQ((string)f["abc"], "xyz"); ASSERT_EQ((int)f["aaa"], 111); f.erase("aaa"); ASSERT_EQ((int)f["aaa"], 0); f.set("obj", "{ \"a\": \"10\", \"b\": \"20\"}"); ASSERT_EQ((int)f["obj"]["a"], 10); ASSERT_EQ((int)f["obj"]["b"], 20); f.erase("obj.a"); ASSERT_EQ((int)f["obj"]["a"], 0); ASSERT_EQ((int)f["obj"]["b"], 20); } template <class T> static void dumpt(const T& t, const char *n) { JSONFormatter formatter; formatter.open_object_section("bla"); ::encode_json(n, t, &formatter); formatter.close_section(); formatter.flush(cout); } static void dumpf(const JSONFormattable& f) { dumpt(f, "f"); } TEST(formatable, set_array) { JSONFormattable f, f2; f.set("asd[0]", "\"xyz\""); ASSERT_EQ(1u, f["asd"].array().size()); ASSERT_EQ((string)f["asd"][0], "xyz"); f.set("bbb[0][0]", "10"); f.set("bbb[0][1]", "20"); ASSERT_EQ(1u, f["bbb"].array().size()); ASSERT_EQ(2u, f["bbb"][0].array().size()); ASSERT_EQ("10", (string)f["bbb"][0][0]); ASSERT_EQ(20, (int)f["bbb"][0][1]); f.set("bbb[0][1]", "25"); ASSERT_EQ(2u, f["bbb"][0].array().size()); ASSERT_EQ(25, (int)f["bbb"][0][1]); f.set("bbb[0][]", "26"); /* append operation */ ASSERT_EQ(26, (int)f["bbb"][0][2]); f.set("bbb[0][-1]", "27"); /* replace last */ ASSERT_EQ(27, (int)f["bbb"][0][2]); ASSERT_EQ(3u, f["bbb"][0].array().size()); f.set("foo.asd[0][0]", "{ \"field\": \"xyz\"}"); ASSERT_EQ((string)f["foo"]["asd"][0][0]["field"], "xyz"); ASSERT_EQ(f.set("foo[0]", "\"zzz\""), -EINVAL); /* can't assign array to an obj entity */ f2.set("[0]", "{ \"field\": \"xyz\"}"); ASSERT_EQ((string)f2[0]["field"], "xyz"); } TEST(formatable, erase_array) { JSONFormattable f; f.set("asd[0]", "\"xyz\""); ASSERT_EQ(1u, f["asd"].array().size()); ASSERT_EQ("xyz", (string)f["asd"][0]); ASSERT_TRUE(f["asd"].exists(0)); f.erase("asd[0]"); ASSERT_FALSE(f["asd"].exists(0)); f.set("asd[0]", "\"xyz\""); ASSERT_TRUE(f["asd"].exists(0)); f["asd"].erase("[0]"); ASSERT_FALSE(f["asd"].exists(0)); f.set("asd[0]", "\"xyz\""); ASSERT_TRUE(f["asd"].exists(0)); f.erase("asd"); ASSERT_FALSE(f["asd"].exists(0)); ASSERT_FALSE(f.exists("asd")); f.set("bbb[]", "10"); f.set("bbb[]", "20"); f.set("bbb[]", "30"); ASSERT_EQ((int)f["bbb"][0], 10); ASSERT_EQ((int)f["bbb"][1], 20); ASSERT_EQ((int)f["bbb"][2], 30); f.erase("bbb[-2]"); ASSERT_FALSE(f.exists("bbb[2]")); ASSERT_EQ((int)f["bbb"][0], 10); ASSERT_EQ((int)f["bbb"][1], 30); if (0) { /* for debugging when needed */ dumpf(f); } } void formatter_convert(JSONFormatter& formatter, JSONFormattable *dest) { stringstream ss; formatter.flush(ss); get_jf(ss.str(), dest); } TEST(formatable, encode_simple) { JSONFormattable f; encode_json("foo", "bar", &f); ASSERT_EQ((string)f["foo"], "bar"); JSONFormatter formatter; { Formatter::ObjectSection s(formatter, "os"); encode_json("f", f, &formatter); } JSONFormattable jf2; formatter_convert(formatter, &jf2); ASSERT_EQ((string)jf2["f"]["foo"], "bar"); } struct struct1 { long i; string s; bool b; struct1() { void *p = (void *)this; i = (long)p; char buf[32]; snprintf(buf, sizeof(buf), "%p", p); s = buf; b = (bool)(i % 2); } void dump(Formatter *f) const { encode_json("i", i, f); encode_json("s", s, f); encode_json("b", b, f); } void decode_json(JSONObj *obj) { JSONDecoder::decode_json("i", i, obj); JSONDecoder::decode_json("s", s, obj); JSONDecoder::decode_json("b", b, obj); } bool compare(const JSONFormattable& jf) const { bool ret = (s == (string)jf["s"] && i == (long)jf["i"] && b == (bool)jf["b"]); if (!ret) { cout << "failed comparison: s=" << s << " jf[s]=" << (string)jf["s"] << " i=" << i << " jf[i]=" << (long)jf["i"] << " b=" << b << " jf[b]=" << (bool)jf["b"] << std::endl; dumpf(jf); } return ret; } }; struct struct2 { struct1 s1; vector<struct1> v; struct2() { void *p = (void *)this; long i = (long)p; v.resize((i >> 16) % 16 + 1); } void dump(Formatter *f) const { encode_json("s1", s1, f); encode_json("v", v, f); } void decode_json(JSONObj *obj) { JSONDecoder::decode_json("s1", s1, obj); JSONDecoder::decode_json("v", v, obj); } bool compare(const JSONFormattable& jf) const { if (!s1.compare(jf["s1"])) { cout << "s1.compare(jf[s1] failed" << std::endl; return false; } if (v.size() != jf["v"].array().size()) { cout << "v.size()=" << v.size() << " jf[v].array().size()=" << jf["v"].array().size() << std::endl; return false; } auto viter = v.begin(); auto jiter = jf["v"].array().begin(); for (; viter != v.end(); ++viter, ++jiter) { if (!viter->compare(*jiter)) { return false; } } return true; } }; TEST(formatable, encode_struct) { JSONFormattable f; struct2 s2; { Formatter::ObjectSection s(f, "section"); encode_json("foo", "bar", &f); encode_json("s2", s2, &f); } dumpt(s2, "s2"); cout << std::endl; cout << std::endl; ASSERT_EQ((string)f["foo"], "bar"); ASSERT_TRUE(s2.compare(f["s2"])); JSONFormatter formatter; encode_json("f", f, &formatter); JSONFormattable jf2; formatter_convert(formatter, &jf2); ASSERT_EQ((string)jf2["foo"], "bar"); ASSERT_TRUE(s2.compare(jf2["s2"])); }
10,548
22.235683
106
cc
null
ceph-main/src/test/common/test_json_formatter.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * */ #include <errno.h> #include <gtest/gtest.h> #include "common/ceph_json.h" #include "common/Clock.h" #include <sstream> using namespace std; TEST(formatter, bug_37706) { vector<std::string> pgs; string outstring = "{\"pg_ready\":true, \"pg_stats\":[ { \"pgid\":\"1.0\", \"version\":\"16'56\",\"reported_seq\":\"62\",\"reported_epoch\":\"20\",\"state\":\"active+clean+inconsistent\",\"last_fresh\":\"2018-12-18 15:21:22.173804\",\"last_change\":\"2018-12-18 15:21:22.173804\",\"last_active\":\"2018-12-18 15:21:22.173804\",\"last_peered\":\"2018-12-18 15:21:22.173804\",\"last_clean\":\"2018-12-18 15:21:22.173804\",\"last_became_active\":\"2018-12-18 15:21:21.347685\",\"last_became_peered\":\"2018-12-18 15:21:21.347685\",\"last_unstale\":\"2018-12-18 15:21:22.173804\",\"last_undegraded\":\"2018-12-18 15:21:22.173804\",\"last_fullsized\":\"2018-12-18 15:21:22.173804\",\"mapping_epoch\":19,\"log_start\":\"0'0\",\"ondisk_log_start\":\"0'0\",\"created\":7,\"last_epoch_clean\":20,\"parent\":\"0.0\",\"parent_split_bits\":0,\"last_scrub\":\"16'56\",\"last_scrub_stamp\":\"2018-12-18 15:21:22.173684\",\"last_deep_scrub\":\"0'0\",\"last_deep_scrub_stamp\":\"2018-12-18 15:21:06.514438\",\"last_clean_scrub_stamp\":\"2018-12-18 15:21:06.514438\",\"log_size\":56,\"ondisk_log_size\":56,\"stats_invalid\":false,\"dirty_stats_invalid\":false,\"omap_stats_invalid\":false,\"hitset_stats_invalid\":false,\"hitset_bytes_stats_invalid\":false,\"pin_stats_invalid\":false,\"manifest_stats_invalid\":false,\"snaptrimq_len\":0,\"stat_sum\":{\"num_bytes\":24448,\"num_objects\":36,\"num_object_clones\":20,\"num_object_copies\":36,\"num_objects_missing_on_primary\":0,\"num_objects_missing\":0,\"num_objects_degraded\":0,\"num_objects_misplaced\":0,\"num_objects_unfound\":0,\"num_objects_dirty\":36,\"num_whiteouts\":3,\"num_read\":0,\"num_read_kb\":0,\"num_write\":36,\"num_write_kb\":50,\"num_scrub_errors\":20,\"num_shallow_scrub_errors\":20,\"num_deep_scrub_errors\":0,\"num_objects_recovered\":0,\"num_bytes_recovered\":0,\"num_keys_recovered\":0,\"num_objects_omap\":0,\"num_objects_hit_set_archive\":0,\"num_bytes_hit_set_archive\":0,\"num_flush\":0,\"num_flush_kb\":0,\"num_evict\":0,\"num_evict_kb\":0,\"num_promote\":0,\"num_flush_mode_high\":0,\"num_flush_mode_low\":0,\"num_evict_mode_some\":0,\"num_evict_mode_full\":0,\"num_objects_pinned\":0,\"num_legacy_snapsets\":0,\"num_large_omap_objects\":0,\"num_objects_manifest\":0},\"up\":[0],\"acting\":[0],\"blocked_by\":[],\"up_primary\":0,\"acting_primary\":0,\"purged_snaps\":[] }]}"; JSONParser parser; ASSERT_TRUE(parser.parse(outstring.c_str(), outstring.size())); vector<string> v; ASSERT_TRUE (!parser.is_array()); JSONObj *pgstat_obj = parser.find_obj("pg_stats"); ASSERT_TRUE (!!pgstat_obj); auto s = pgstat_obj->get_data(); ASSERT_TRUE(!s.empty()); JSONParser pg_stats; ASSERT_TRUE(pg_stats.parse(s.c_str(), s.length())); v = pg_stats.get_array_elements(); for (auto i : v) { JSONParser pg_json; ASSERT_TRUE(pg_json.parse(i.c_str(), i.length())); string pgid; JSONDecoder::decode_json("pgid", pgid, &pg_json); pgs.emplace_back(std::move(pgid)); } ASSERT_EQ(pgs.back(), "1.0"); } TEST(formatter, utime) { JSONFormatter formatter; utime_t input = ceph_clock_now(); input.gmtime_nsec(formatter.dump_stream("timestamp")); bufferlist bl; formatter.flush(bl); JSONParser parser; EXPECT_TRUE(parser.parse(bl.c_str(), bl.length())); cout << input << " -> '" << std::string(bl.c_str(), bl.length()) << std::endl; utime_t output; decode_json_obj(output, &parser); cout << " -> " << output << std::endl; EXPECT_EQ(input.sec(), output.sec()); EXPECT_EQ(input.nsec(), output.nsec()); }
4,218
50.45122
2,322
cc
null
ceph-main/src/test/common/test_lockdep.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "gtest/gtest.h" #include "common/ceph_argparse.h" #include "common/ceph_context.h" #include "common/ceph_mutex.h" #include "common/common_init.h" #include "common/lockdep.h" #include "include/util.h" #include "include/coredumpctl.h" #include "log/Log.h" class lockdep : public ::testing::Test { protected: void SetUp() override { #ifndef CEPH_DEBUG_MUTEX GTEST_SKIP() << "WARNING: CEPH_DEBUG_MUTEX is not defined, lockdep will not work"; #endif CephInitParameters params(CEPH_ENTITY_TYPE_CLIENT); cct = common_preinit(params, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); cct->_conf->cluster = "ceph"; cct->_conf.set_val("lockdep", "true"); cct->_conf.apply_changes(nullptr); ASSERT_TRUE(g_lockdep); } void TearDown() final { if (cct) { cct->put(); cct = nullptr; } } protected: CephContext *cct = nullptr; }; TEST_F(lockdep, abba) { ceph::mutex a(ceph::make_mutex("a")), b(ceph::make_mutex("b")); a.lock(); ASSERT_TRUE(ceph_mutex_is_locked(a)); ASSERT_TRUE(ceph_mutex_is_locked_by_me(a)); b.lock(); ASSERT_TRUE(ceph_mutex_is_locked(b)); ASSERT_TRUE(ceph_mutex_is_locked_by_me(b)); a.unlock(); b.unlock(); b.lock(); PrCtl unset_dumpable; EXPECT_DEATH(a.lock(), ""); b.unlock(); } TEST_F(lockdep, recursive) { ceph::mutex a(ceph::make_mutex("a")); a.lock(); PrCtl unset_dumpable; EXPECT_DEATH(a.lock(), ""); a.unlock(); ceph::recursive_mutex b(ceph::make_recursive_mutex("b")); b.lock(); ASSERT_TRUE(ceph_mutex_is_locked(b)); ASSERT_TRUE(ceph_mutex_is_locked_by_me(b)); b.lock(); b.unlock(); b.unlock(); }
1,749
22.333333
86
cc
null
ceph-main/src/test/common/test_lru.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Cloudwatt <[email protected]> * * Author: Sahid Orentino Ferdjaoui <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * */ #include <errno.h> #include <gtest/gtest.h> #include "include/lru.h" class Item : public LRUObject { public: int id; Item() : id(0) {} explicit Item(int i) : id(i) {} void set(int i) {id = i;} }; TEST(lru, InsertTop) { LRU lru; static const int n = 100; Item items[n]; lru.lru_set_midpoint(.5); // 50% of elements. for (int i=0; i<n; i++) { items[i].set(i); lru.lru_insert_top(&items[i]); } ASSERT_EQ(50U, lru.lru_get_top()); ASSERT_EQ(50U, lru.lru_get_bot()); ASSERT_EQ(100U, lru.lru_get_size()); ASSERT_EQ(0, (static_cast<Item*>(lru.lru_expire()))->id); } TEST(lru, InsertMid) { LRU lru; static const int n = 102; Item items[n]; lru.lru_set_midpoint(.7); // 70% of elements. for (int i=0; i<n; i++) { items[i].set(i); lru.lru_insert_mid(&items[i]); } ASSERT_EQ(71U, lru.lru_get_top()); ASSERT_EQ(31U, lru.lru_get_bot()); ASSERT_EQ(102U, lru.lru_get_size()); ASSERT_EQ(0, (static_cast<Item*>(lru.lru_expire()))->id); } TEST(lru, InsertBot) { LRU lru; static const int n = 100; Item items[n]; lru.lru_set_midpoint(.7); // 70% of elements. for (int i=0; i<n; i++) { items[i].set(i); lru.lru_insert_bot(&items[i]); } ASSERT_EQ(70U, lru.lru_get_top()); ASSERT_EQ(30U, lru.lru_get_bot()); ASSERT_EQ(100U, lru.lru_get_size()); ASSERT_EQ(99, (static_cast<Item*>(lru.lru_expire()))->id); } TEST(lru, Adjust) { LRU lru; static const int n = 100; Item items[n]; lru.lru_set_midpoint(.6); // 60% of elements. for (int i=0; i<n; i++) { items[i].set(i); lru.lru_insert_top(&items[i]); if (i % 5 == 0) items[i].lru_pin(); } ASSERT_EQ(48U, lru.lru_get_top()); /* 60% of unpinned */ ASSERT_EQ(52U, lru.lru_get_bot()); ASSERT_EQ(100U, lru.lru_get_size()); ASSERT_EQ(1, (static_cast<Item*>(lru.lru_expire()))->id); ASSERT_EQ(1U, lru.lru_get_pintail()); ASSERT_EQ(47U, lru.lru_get_top()); /* 60% of unpinned */ ASSERT_EQ(51U, lru.lru_get_bot()); ASSERT_EQ(99U, lru.lru_get_size()); ASSERT_EQ(2, (static_cast<Item*>(lru.lru_expire()))->id); ASSERT_EQ(1U, lru.lru_get_pintail()); ASSERT_EQ(46U, lru.lru_get_top()); /* 60% of unpinned */ ASSERT_EQ(51U, lru.lru_get_bot()); ASSERT_EQ(98U, lru.lru_get_size()); ASSERT_EQ(3, (static_cast<Item*>(lru.lru_expire()))->id); ASSERT_EQ(4, (static_cast<Item*>(lru.lru_expire()))->id); ASSERT_EQ(6, (static_cast<Item*>(lru.lru_expire()))->id); ASSERT_EQ(2U, lru.lru_get_pintail()); ASSERT_EQ(45U, lru.lru_get_top()); /* 60% of unpinned */ ASSERT_EQ(48U, lru.lru_get_bot()); ASSERT_EQ(95U, lru.lru_get_size()); } TEST(lru, Pinning) { LRU lru; Item ob0(0), ob1(1); // test before ob1 are in a LRU ob1.lru_pin(); ASSERT_FALSE(ob1.lru_is_expireable()); ob1.lru_unpin(); ASSERT_TRUE(ob1.lru_is_expireable()); // test when ob1 are in a LRU lru.lru_insert_top(&ob0); lru.lru_insert_top(&ob1); ob1.lru_pin(); ob1.lru_pin(); // Verify that, one incr. ASSERT_EQ(1U, lru.lru_get_num_pinned()); ASSERT_FALSE(ob1.lru_is_expireable()); ob1.lru_unpin(); ob1.lru_unpin(); // Verify that, one decr. ASSERT_EQ(0U, lru.lru_get_num_pinned()); ASSERT_TRUE(ob1.lru_is_expireable()); ASSERT_EQ(0, (static_cast<Item*>(lru.lru_expire()))->id); ob0.lru_pin(); ASSERT_EQ(1, (static_cast<Item*>(lru.lru_expire()))->id); } /* * Local Variables: * compile-command: "cd ../.. ; make -j4 && * make unittest_lru && * valgrind --tool=memcheck --leak-check=full \ * ./unittest_lru * " * End: */
4,085
24.698113
70
cc
null
ceph-main/src/test/common/test_lruset.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 Inktank <[email protected]> * * LGPL-2.1 (see COPYING-LGPL2.1) or later */ #include <iostream> #include <gtest/gtest.h> #include "common/LRUSet.h" struct thing { int a; thing(int i) : a(i) {} friend bool operator==(const thing &a, const thing &b) { return a.a == b.a; } friend std::size_t hash_value(const thing &value) { return value.a; } }; namespace std { template<> struct hash<thing> { size_t operator()(const thing& r) const { return r.a; } }; } TEST(LRUSet, insert_complex) { LRUSet<thing> s; s.insert(thing(1)); s.insert(thing(2)); ASSERT_TRUE(s.contains(thing(1))); ASSERT_TRUE(s.contains(thing(2))); ASSERT_FALSE(s.contains(thing(3))); } TEST(LRUSet, insert) { LRUSet<int> s; s.insert(1); s.insert(2); ASSERT_TRUE(s.contains(1)); ASSERT_TRUE(s.contains(2)); ASSERT_FALSE(s.contains(3)); } TEST(LRUSet, erase) { LRUSet<int> s; s.insert(1); s.insert(2); s.insert(3); s.erase(2); ASSERT_TRUE(s.contains(1)); ASSERT_FALSE(s.contains(2)); ASSERT_TRUE(s.contains(3)); s.prune(1); ASSERT_TRUE(s.contains(3)); ASSERT_FALSE(s.contains(1)); } TEST(LRUSet, prune) { LRUSet<int> s; int max = 1000; for (int i=0; i<max; ++i) { s.insert(i); s.prune(max / 10); } s.prune(0); ASSERT_TRUE(s.empty()); } TEST(LRUSet, lru) { LRUSet<int> s; s.insert(1); s.insert(2); s.insert(3); s.prune(2); ASSERT_FALSE(s.contains(1)); ASSERT_TRUE(s.contains(2)); ASSERT_TRUE(s.contains(3)); s.insert(2); s.insert(4); s.prune(2); ASSERT_FALSE(s.contains(3)); ASSERT_TRUE(s.contains(2)); ASSERT_TRUE(s.contains(4)); } TEST(LRUSet, copy) { LRUSet<int> a, b; a.insert(1); b.insert(2); b.insert(3); a = b; ASSERT_FALSE(a.contains(1)); ASSERT_TRUE(a.contains(2)); ASSERT_TRUE(a.contains(3)); }
1,998
17.172727
70
cc
null
ceph-main/src/test/common/test_mclock_priority_queue.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2017 Red Hat Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <thread> #include <chrono> #include <iostream> #include "gtest/gtest.h" #include "common/mClockPriorityQueue.h" struct Request { int value; Request() : value(0) {} Request(const Request& o) = default; explicit Request(int value) : value(value) {} }; struct Client { int client_num; Client() : Client(-1) {} Client(int client_num) : client_num(client_num) {} friend bool operator<(const Client& r1, const Client& r2) { return r1.client_num < r2.client_num; } friend bool operator==(const Client& r1, const Client& r2) { return r1.client_num == r2.client_num; } }; const crimson::dmclock::ClientInfo* client_info_func(const Client& c) { static const crimson::dmclock::ClientInfo the_info(10.0, 10.0, 10.0); return &the_info; } TEST(mClockPriorityQueue, Create) { ceph::mClockQueue<Request,Client> q(&client_info_func); } TEST(mClockPriorityQueue, Sizes) { ceph::mClockQueue<Request,Client> q(&client_info_func); ASSERT_TRUE(q.empty()); ASSERT_EQ(0u, q.get_size_slow()); Client c1(1); Client c2(2); q.enqueue_strict(c1, 1, Request(1)); q.enqueue_strict(c2, 2, Request(2)); q.enqueue_strict(c1, 2, Request(3)); q.enqueue(c2, 1, 1u, Request(4)); q.enqueue(c1, 2, 1u, Request(5)); q.enqueue_strict(c2, 1, Request(6)); ASSERT_FALSE(q.empty()); ASSERT_EQ(6u, q.get_size_slow()); for (int i = 0; i < 6; ++i) { (void) q.dequeue(); } ASSERT_TRUE(q.empty()); ASSERT_EQ(0u, q.get_size_slow()); } TEST(mClockPriorityQueue, JustStrict) { ceph::mClockQueue<Request,Client> q(&client_info_func); Client c1(1); Client c2(2); q.enqueue_strict(c1, 1, Request(1)); q.enqueue_strict(c2, 2, Request(2)); q.enqueue_strict(c1, 2, Request(3)); q.enqueue_strict(c2, 1, Request(4)); Request r; r = q.dequeue(); ASSERT_EQ(2, r.value); r = q.dequeue(); ASSERT_EQ(3, r.value); r = q.dequeue(); ASSERT_EQ(1, r.value); r = q.dequeue(); ASSERT_EQ(4, r.value); } TEST(mClockPriorityQueue, StrictPriorities) { ceph::mClockQueue<Request,Client> q(&client_info_func); Client c1(1); Client c2(2); q.enqueue_strict(c1, 1, Request(1)); q.enqueue_strict(c2, 2, Request(2)); q.enqueue_strict(c1, 3, Request(3)); q.enqueue_strict(c2, 4, Request(4)); Request r; r = q.dequeue(); ASSERT_EQ(4, r.value); r = q.dequeue(); ASSERT_EQ(3, r.value); r = q.dequeue(); ASSERT_EQ(2, r.value); r = q.dequeue(); ASSERT_EQ(1, r.value); } TEST(mClockPriorityQueue, JustNotStrict) { ceph::mClockQueue<Request,Client> q(&client_info_func); Client c1(1); Client c2(2); // non-strict queue ignores priorites, but will divide between // clients evenly and maintain orders between clients q.enqueue(c1, 1, 1u, Request(1)); q.enqueue(c1, 2, 1u, Request(2)); q.enqueue(c2, 3, 1u, Request(3)); q.enqueue(c2, 4, 1u, Request(4)); Request r1, r2; r1 = q.dequeue(); ASSERT_TRUE(1 == r1.value || 3 == r1.value); r2 = q.dequeue(); ASSERT_TRUE(1 == r2.value || 3 == r2.value); ASSERT_NE(r1.value, r2.value); r1 = q.dequeue(); ASSERT_TRUE(2 == r1.value || 4 == r1.value); r2 = q.dequeue(); ASSERT_TRUE(2 == r2.value || 4 == r2.value); ASSERT_NE(r1.value, r2.value); } TEST(mClockPriorityQueue, EnqueuFront) { ceph::mClockQueue<Request,Client> q(&client_info_func); Client c1(1); Client c2(2); // non-strict queue ignores priorites, but will divide between // clients evenly and maintain orders between clients q.enqueue(c1, 1, 1u, Request(1)); q.enqueue(c1, 2, 1u, Request(2)); q.enqueue(c2, 3, 1u, Request(3)); q.enqueue(c2, 4, 1u, Request(4)); q.enqueue_strict(c2, 6, Request(6)); q.enqueue_strict(c1, 7, Request(7)); std::list<Request> reqs; for (uint i = 0; i < 4; ++i) { reqs.emplace_back(q.dequeue()); } for (uint i = 0; i < 4; ++i) { Request& r = reqs.front(); if (r.value > 5) { q.enqueue_strict_front(r.value == 6 ? c2 : 1, r.value, std::move(r)); } else { q.enqueue_front(r.value <= 2 ? c1 : c2, r.value, 0, std::move(r)); } reqs.pop_front(); } Request r; r = q.dequeue(); ASSERT_EQ(7, r.value); r = q.dequeue(); ASSERT_EQ(6, r.value); r = q.dequeue(); ASSERT_TRUE(1 == r.value || 3 == r.value); r = q.dequeue(); ASSERT_TRUE(1 == r.value || 3 == r.value); r = q.dequeue(); ASSERT_TRUE(2 == r.value || 4 == r.value); r = q.dequeue(); ASSERT_TRUE(2 == r.value || 4 == r.value); } TEST(mClockPriorityQueue, RemoveByClass) { ceph::mClockQueue<Request,Client> q(&client_info_func); Client c1(1); Client c2(2); Client c3(3); q.enqueue(c1, 1, 1u, Request(1)); q.enqueue(c2, 1, 1u, Request(2)); q.enqueue(c3, 1, 1u, Request(4)); q.enqueue_strict(c1, 2, Request(8)); q.enqueue_strict(c2, 1, Request(16)); q.enqueue_strict(c3, 3, Request(32)); q.enqueue(c3, 1, 1u, Request(64)); q.enqueue(c2, 1, 1u, Request(128)); q.enqueue(c1, 1, 1u, Request(256)); int out_mask = 2 | 16 | 128; int in_mask = 1 | 8 | 256; std::list<Request> out; q.remove_by_class(c2, &out); ASSERT_EQ(3u, out.size()); while (!out.empty()) { ASSERT_TRUE((out.front().value & out_mask) > 0) << "had value that was not expected after first removal"; out.pop_front(); } ASSERT_EQ(6u, q.get_size_slow()) << "after removal of three from client c2"; q.remove_by_class(c3); ASSERT_EQ(3u, q.get_size_slow()) << "after removal of three from client c3"; while (!q.empty()) { Request r = q.dequeue(); ASSERT_TRUE((r.value & in_mask) > 0) << "had value that was not expected after two removals"; } } TEST(mClockPriorityQueue, RemoveByFilter) { ceph::mClockQueue<Request,Client> q(&client_info_func); Client c1(1); Client c2(2); Client c3(3); q.enqueue(c1, 1, 1u, Request(1)); q.enqueue(c2, 1, 1u, Request(2)); q.enqueue(c3, 1, 1u, Request(3)); q.enqueue_strict(c1, 2, Request(4)); q.enqueue_strict(c2, 1, Request(5)); q.enqueue_strict(c3, 3, Request(6)); q.enqueue(c3, 1, 1u, Request(7)); q.enqueue(c2, 1, 1u, Request(8)); q.enqueue(c1, 1, 1u, Request(9)); std::list<Request> filtered; q.remove_by_filter([&](const Request& r) -> bool { if (r.value & 2) { filtered.push_back(r); return true; } else { return false; } }); ASSERT_EQ(4u, filtered.size()) << "filter should have removed four elements"; while (!filtered.empty()) { ASSERT_TRUE((filtered.front().value & 2) > 0) << "expect this value to have been filtered out"; filtered.pop_front(); } ASSERT_EQ(5u, q.get_size_slow()) << "filter should have left five remaining elements"; while (!q.empty()) { Request r = q.dequeue(); ASSERT_TRUE((r.value & 2) == 0) << "expect this value to have been left in"; } }
7,214
21.476636
78
cc
null
ceph-main/src/test/common/test_mutex_debug.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 &smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License version 2, as published by the Free Software * Foundation. See file COPYING. * */ #include <future> #include <mutex> #include <thread> #include "common/mutex_debug.h" #include "gtest/gtest.h" template<typename Mutex> static bool test_try_lock(Mutex* m) { if (!m->try_lock()) return false; m->unlock(); return true; } template<typename Mutex> static void test_lock() { Mutex m("mutex"); auto ttl = &test_try_lock<Mutex>; m.lock(); ASSERT_TRUE(m.is_locked()); auto f1 = std::async(std::launch::async, ttl, &m); ASSERT_FALSE(f1.get()); ASSERT_TRUE(m.is_locked()); ASSERT_TRUE(!!m); m.unlock(); ASSERT_FALSE(m.is_locked()); ASSERT_FALSE(!!m); auto f3 = std::async(std::launch::async, ttl, &m); ASSERT_TRUE(f3.get()); ASSERT_FALSE(m.is_locked()); ASSERT_FALSE(!!m); } TEST(MutexDebug, Lock) { test_lock<ceph::mutex_debug>(); } TEST(MutexDebug, NotRecursive) { ceph::mutex_debug m("foo"); auto ttl = &test_try_lock<mutex_debug>; ASSERT_NO_THROW(m.lock()); ASSERT_TRUE(m.is_locked()); ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get()); ASSERT_THROW(m.lock(), std::system_error); ASSERT_TRUE(m.is_locked()); ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get()); ASSERT_NO_THROW(m.unlock()); ASSERT_FALSE(m.is_locked()); ASSERT_TRUE(std::async(std::launch::async, ttl, &m).get()); } TEST(MutexRecursiveDebug, Lock) { test_lock<ceph::mutex_recursive_debug>(); } TEST(MutexRecursiveDebug, Recursive) { ceph::mutex_recursive_debug m("m"); auto ttl = &test_try_lock<mutex_recursive_debug>; ASSERT_NO_THROW(m.lock()); ASSERT_TRUE(m.is_locked()); ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get()); ASSERT_NO_THROW(m.lock()); ASSERT_TRUE(m.is_locked()); ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get()); ASSERT_NO_THROW(m.unlock()); ASSERT_TRUE(m.is_locked()); ASSERT_FALSE(std::async(std::launch::async, ttl, &m).get()); ASSERT_NO_THROW(m.unlock()); ASSERT_FALSE(m.is_locked()); ASSERT_TRUE(std::async(std::launch::async, ttl, &m).get()); }
2,399
22.529412
70
cc
null
ceph-main/src/test/common/test_numa.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "gtest/gtest.h" #include "common/numa.h" TEST(cpu_set, parse_list) { cpu_set_t cpu_set; size_t size; ASSERT_EQ(0, parse_cpu_set_list("0-3", &size, &cpu_set)); ASSERT_EQ(size, 4u); for (unsigned i = 0; i < size; ++i) { ASSERT_TRUE(CPU_ISSET(i, &cpu_set)); } ASSERT_EQ(0, parse_cpu_set_list("0-3,6-7", &size, &cpu_set)); ASSERT_EQ(size, 8u); for (unsigned i = 0; i < 4; ++i) { ASSERT_TRUE(CPU_ISSET(i, &cpu_set)); } for (unsigned i = 4; i < 6; ++i) { ASSERT_FALSE(CPU_ISSET(i, &cpu_set)); } for (unsigned i = 6; i < 8; ++i) { ASSERT_TRUE(CPU_ISSET(i, &cpu_set)); } ASSERT_EQ(0, parse_cpu_set_list("0-31", &size, &cpu_set)); ASSERT_EQ(size, 32u); for (unsigned i = 0; i < size; ++i) { ASSERT_TRUE(CPU_ISSET(i, &cpu_set)); } } TEST(cpu_set, to_str_list) { cpu_set_t cpu_set; CPU_ZERO(&cpu_set); CPU_SET(0, &cpu_set); ASSERT_EQ(std::string("0"), cpu_set_to_str_list(8, &cpu_set)); CPU_SET(1, &cpu_set); CPU_SET(2, &cpu_set); CPU_SET(3, &cpu_set); ASSERT_EQ(std::string("0-3"), cpu_set_to_str_list(8, &cpu_set)); CPU_SET(5, &cpu_set); ASSERT_EQ(std::string("0-3,5"), cpu_set_to_str_list(8, &cpu_set)); CPU_SET(6, &cpu_set); CPU_SET(7, &cpu_set); ASSERT_EQ(std::string("0-3,5-7"), cpu_set_to_str_list(8, &cpu_set)); } TEST(cpu_set, round_trip_list) { for (unsigned i = 0; i < 100; ++i) { cpu_set_t cpu_set; size_t size = 32; CPU_ZERO(&cpu_set); for (unsigned i = 0; i < 32; ++i) { if (rand() % 1) { CPU_SET(i, &cpu_set); } } std::string v = cpu_set_to_str_list(size, &cpu_set); cpu_set_t cpu_set_2; size_t size2; ASSERT_EQ(0, parse_cpu_set_list(v.c_str(), &size2, &cpu_set_2)); for (unsigned i = 0; i < 32; ++i) { ASSERT_TRUE(CPU_ISSET(i, &cpu_set) == CPU_ISSET(i, &cpu_set_2)); } } }
1,942
25.616438
70
cc
null
ceph-main/src/test/common/test_option.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:nil -*- // vim: ts=8 sw=2 smarttab expandtab #include <string.h> #include <errno.h> #include <stdlib.h> #include <gtest/gtest.h> #include "common/options.h" using namespace std; TEST(Option, validate_min_max) { auto opt = Option{"foo", Option::TYPE_MILLISECS, Option::LEVEL_ADVANCED} .set_default(42) .set_min_max(10, 128); struct test_t { unsigned new_val; int expected_retval; }; test_t tests[] = {{9, -EINVAL}, {10, 0}, {11, 0}, {128, 0}, {1024, -EINVAL} }; for (auto& test : tests) { Option::value_t new_value = std::chrono::milliseconds{test.new_val}; std::string err; GTEST_ASSERT_EQ(test.expected_retval, opt.validate(new_value, &err)); } } TEST(Option, parse) { auto opt = Option{"foo", Option::TYPE_MILLISECS, Option::LEVEL_ADVANCED} .set_default(42) .set_min_max(10, 128); struct test_t { string new_val; int expected_retval; unsigned expected_parsed_val; }; test_t tests[] = {{"9", -EINVAL, 0}, {"10", 0, 10}, {"11", 0, 11}, {"128", 0, 128}, {"1024", -EINVAL, 0} }; for (auto& test : tests) { Option::value_t parsed_val; std::string err; GTEST_ASSERT_EQ(test.expected_retval, opt.parse_value(test.new_val, &parsed_val, &err)); if (test.expected_retval == 0) { Option::value_t expected_parsed_val = std::chrono::milliseconds{test.expected_parsed_val}; GTEST_ASSERT_EQ(parsed_val, expected_parsed_val); } } } /* * Local Variables: * compile-command: "cd ../../../build ; * ninja unittest_option && bin/unittest_option * " * End: */
1,707
22.081081
74
cc
null
ceph-main/src/test/common/test_perf_counters_key.cc
#include "common/perf_counters_key.h" #include <gtest/gtest.h> namespace ceph::perf_counters { TEST(PerfCounters, key_create) { EXPECT_EQ(key_create(""), std::string_view("\0", 1)); EXPECT_EQ(key_create("perf"), std::string_view("perf\0", 5)); EXPECT_EQ(key_create("perf", {{"",""}}), std::string_view("perf\0\0\0", 7)); EXPECT_EQ(key_create("perf", {{"","a"}, {"",""}}), std::string_view("perf\0\0a\0", 8)); EXPECT_EQ(key_create("perf", {{"a","b"}}), std::string_view("perf\0a\0b\0", 9)); EXPECT_EQ(key_create("perf", {{"y","z"}, {"a","b"}}), std::string_view("perf\0a\0b\0y\0z\0", 13)); EXPECT_EQ(key_create("perf", {{"a","b"}, {"a","c"}}), std::string_view("perf\0a\0b\0", 9)); EXPECT_EQ(key_create("perf", {{"a","z"}, {"a","b"}}), std::string_view("perf\0a\0z\0", 9)); EXPECT_EQ(key_create("perf", {{"d",""}, {"c",""}, {"b",""}, {"a",""}}), std::string_view("perf\0a\0\0b\0\0c\0\0d\0\0", 17)); } TEST(PerfCounters, key_insert) { EXPECT_EQ(key_insert("", {{"",""}}), std::string_view("\0\0\0", 3)); EXPECT_EQ(key_insert("", {{"",""}, {"",""}}), std::string_view("\0\0\0", 3)); EXPECT_EQ(key_insert(std::string_view{"\0\0\0", 3}, {{"",""}}), std::string_view("\0\0\0", 3)); EXPECT_EQ(key_insert(std::string_view{"\0", 1}, {{"",""}}), std::string_view("\0\0\0", 3)); EXPECT_EQ(key_insert("", {{"a","b"}}), std::string_view("\0a\0b\0", 5)); EXPECT_EQ(key_insert(std::string_view{"\0", 1}, {{"a","b"}}), std::string_view("\0a\0b\0", 5)); EXPECT_EQ(key_insert("a", {{"",""}}), std::string_view("a\0\0\0", 4)); EXPECT_EQ(key_insert(std::string_view{"a\0", 2}, {{"",""}}), std::string_view("a\0\0\0", 4)); EXPECT_EQ(key_insert(std::string_view{"p\0", 2}, {{"a","b"}}), std::string_view("p\0a\0b\0", 6)); EXPECT_EQ(key_insert(std::string_view{"p\0a\0a\0", 6}, {{"a","b"}}), std::string_view("p\0a\0b\0", 6)); EXPECT_EQ(key_insert(std::string_view{"p\0a\0z\0", 6}, {{"a","b"}}), std::string_view("p\0a\0b\0", 6)); EXPECT_EQ(key_insert(std::string_view{"p\0z\0z\0", 6}, {{"a","b"}}), std::string_view("p\0a\0b\0z\0z\0", 10)); EXPECT_EQ(key_insert(std::string_view{"p\0b\0b\0", 6}, {{"a","a"}, {"c","c"}}), std::string_view("p\0a\0a\0b\0b\0c\0c\0", 14)); EXPECT_EQ(key_insert(std::string_view{"p\0a\0a\0b\0b\0c\0c\0", 14}, {{"z","z"}, {"b","z"}}), std::string_view("p\0a\0a\0b\0z\0c\0c\0z\0z\0", 18)); } TEST(PerfCounters, key_name) { EXPECT_EQ(key_name(""), ""); EXPECT_EQ(key_name({"\0", 1}), ""); EXPECT_EQ(key_name({"perf\0", 5}), "perf"); EXPECT_EQ(key_name({"perf\0\0\0", 7}), "perf"); } TEST(PerfCounters, key_labels) { { auto labels = key_labels(""); EXPECT_EQ(labels.begin(), labels.end()); } { auto labels = key_labels({"\0", 1}); EXPECT_EQ(labels.begin(), labels.end()); } { auto labels = key_labels({"perf\0", 5}); EXPECT_EQ(labels.begin(), labels.end()); } { auto labels = key_labels({"\0\0\0", 3}); ASSERT_EQ(1, std::distance(labels.begin(), labels.end())); EXPECT_EQ(label_pair("", ""), *labels.begin()); } { auto labels = key_labels({"\0a\0b\0", 5}); ASSERT_EQ(1, std::distance(labels.begin(), labels.end())); EXPECT_EQ(label_pair("a", "b"), *labels.begin()); EXPECT_EQ(std::next(labels.begin()), labels.end()); } { auto labels = key_labels({"\0a\0b\0c\0d\0", 9}); ASSERT_EQ(2, std::distance(labels.begin(), labels.end())); EXPECT_EQ(label_pair("a", "b"), *labels.begin()); EXPECT_EQ(label_pair("c", "d"), *std::next(labels.begin())); EXPECT_EQ(std::next(labels.begin(), 2), labels.end()); } } } // namespace ceph::perf_counters
3,984
29.653846
73
cc