kyototycoon-0.9.56/ 0000755 0001750 0001750 00000000000 11757471603 013231 5 ustar mikio mikio kyototycoon-0.9.56/ktremotedb.cc 0000644 0001750 0001750 00000002251 11757471602 015677 0 ustar mikio mikio /*************************************************************************************************
* Remote database
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#include "ktremotedb.h"
#include "myconf.h"
namespace kyototycoon { // common namespace
// There is no implementation now.
} // common namespace
// END OF FILE
kyototycoon-0.9.56/README 0000644 0001750 0001750 00000001733 11577640524 014115 0 ustar mikio mikio ================================================================
Kyoto Tycoon: a handy cache/storage server
Copyright (C) 2009-2010 FAL Labs
================================================================
Please read the following documents with a WWW browser.
How to install Kyoto Tycoon is explained in the specification.
README - this file
COPYING - license (GPLv3)
ChangeLog - history of enhancement
doc/index.html - index of documents
Contents of the directory tree is below.
./ - sources of Kyoto Tycoon
./doc/ - manuals and specifications
./man/ - manuals for nroff
./example/ - sample code for tutorial
./lab/ - for test and experiment
Kyoto Tycoon is released under the terms of the GNU General Public
License version 3. See the file `COPYING' for details.
Kyoto Tycoon was written by FAL Labs. You can contact the author
by e-mail to `info@fallabs.com'.
Thanks.
== END OF FILE ==
kyototycoon-0.9.56/ktremotetest.cc 0000644 0001750 0001750 00000162622 11757471602 016302 0 ustar mikio mikio /*************************************************************************************************
* The test cases of the remote database
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#include
#include "cmdcommon.h"
// global variables
const char* g_progname; // program name
uint32_t g_randseed; // random seed
int64_t g_memusage; // memory usage
// function prototypes
int main(int argc, char** argv);
static void usage();
static void dberrprint(kt::RemoteDB* db, int32_t line, const char* func);
static void dbmetaprint(kt::RemoteDB* db, bool verbose);
static int32_t runorder(int argc, char** argv);
static int32_t runbulk(int argc, char** argv);
static int32_t runwicked(int argc, char** argv);
static int32_t runusual(int argc, char** argv);
static int32_t procorder(int64_t rnum, int32_t thnum, bool rnd, int32_t mode,
const char* host, int32_t port, double tout);
static int32_t procbulk(int64_t rnum, int32_t thnum, bool bin, bool rnd, int32_t mode,
int32_t bulk, const char* host, int32_t port, double tout,
int32_t bopts);
static int32_t procwicked(int64_t rnum, int32_t thnum, int32_t itnum,
const char* host, int32_t port, double tout);
static int32_t procusual(int64_t rnum, int32_t thnum, int32_t itnum,
const char* host, int32_t port, double tout,
int64_t kp, int64_t vs, int64_t xt, double iv);
// main routine
int main(int argc, char** argv) {
g_progname = argv[0];
const char* ebuf = kc::getenv("KTRNDSEED");
g_randseed = ebuf ? (uint32_t)kc::atoi(ebuf) : (uint32_t)(kc::time() * 1000);
mysrand(g_randseed);
g_memusage = memusage();
kc::setstdiobin();
if (argc < 2) usage();
int32_t rv = 0;
if (!std::strcmp(argv[1], "order")) {
rv = runorder(argc, argv);
} else if (!std::strcmp(argv[1], "bulk")) {
rv = runbulk(argc, argv);
} else if (!std::strcmp(argv[1], "wicked")) {
rv = runwicked(argc, argv);
} else if (!std::strcmp(argv[1], "usual")) {
rv = runusual(argc, argv);
} else {
usage();
}
if (rv != 0) {
oprintf("FAILED: KTRNDSEED=%u PID=%ld", g_randseed, (long)kc::getpid());
for (int32_t i = 0; i < argc; i++) {
oprintf(" %s", argv[i]);
}
oprintf("\n\n");
}
return rv;
}
// print the usage and exit
static void usage() {
eprintf("%s: test cases of the remote database of Kyoto Tycoon\n", g_progname);
eprintf("\n");
eprintf("usage:\n");
eprintf(" %s order [-th num] [-rnd] [-set|-get|-rem|-etc]"
" [-host str] [-port num] [-tout num] rnum\n", g_progname);
eprintf(" %s bulk [-th num] [-bin] [-rnd] [-set|-get|-rem|-etc] [-bulk num]"
" [-host str] [-port num] [-tout num] [-bnr] rnum\n", g_progname);
eprintf(" %s wicked [-th num] [-it num] [-host str] [-port num] [-tout num] rnum\n",
g_progname);
eprintf(" %s usual [-th num] [-host str] [-port num] [-tout num]"
" [-kp num] [-vs num] [-xt num] [-iv num] rnum\n", g_progname);
eprintf("\n");
std::exit(1);
}
// print the error message of a database
static void dberrprint(kt::RemoteDB* db, int32_t line, const char* func) {
const kt::RemoteDB::Error& err = db->error();
oprintf("%s: %d: %s: %s: %d: %s: %s\n",
g_progname, line, func, db->expression().c_str(),
err.code(), err.name(), err.message());
}
// print members of a database
static void dbmetaprint(kt::RemoteDB* db, bool verbose) {
if (verbose) {
std::map status;
if (db->status(&status)) {
std::map::iterator it = status.begin();
std::map::iterator itend = status.end();
while (it != itend) {
oprintf("%s: %s\n", it->first.c_str(), it->second.c_str());
++it;
}
}
} else {
oprintf("count: %lld\n", (long long)db->count());
oprintf("size: %lld\n", (long long)db->size());
}
int64_t musage = memusage();
if (musage > 0) oprintf("memory: %lld\n", (long long)(musage - g_memusage));
}
// parse arguments of order command
static int32_t runorder(int argc, char** argv) {
bool argbrk = false;
const char* rstr = NULL;
int32_t thnum = 1;
bool rnd = false;
int32_t mode = 0;
const char* host = "";
int32_t port = kt::DEFPORT;
double tout = 0;
for (int32_t i = 2; i < argc; i++) {
if (!argbrk && argv[i][0] == '-') {
if (!std::strcmp(argv[i], "--")) {
argbrk = true;
} else if (!std::strcmp(argv[i], "-th")) {
if (++i >= argc) usage();
thnum = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-rnd")) {
rnd = true;
} else if (!std::strcmp(argv[i], "-set")) {
mode = 's';
} else if (!std::strcmp(argv[i], "-get")) {
mode = 'g';
} else if (!std::strcmp(argv[i], "-rem")) {
mode = 'r';
} else if (!std::strcmp(argv[i], "-etc")) {
mode = 'e';
} else if (!std::strcmp(argv[i], "-host")) {
if (++i >= argc) usage();
host = argv[i];
} else if (!std::strcmp(argv[i], "-port")) {
if (++i >= argc) usage();
port = kc::atoi(argv[i]);
} else if (!std::strcmp(argv[i], "-tout")) {
if (++i >= argc) usage();
tout = kc::atof(argv[i]);
} else {
usage();
}
} else if (!rstr) {
argbrk = false;
rstr = argv[i];
} else {
usage();
}
}
if (!rstr) usage();
int64_t rnum = kc::atoix(rstr);
if (rnum < 1 || thnum < 1 || port < 1) usage();
if (thnum > THREADMAX) thnum = THREADMAX;
int32_t rv = procorder(rnum, thnum, rnd, mode, host, port, tout);
return rv;
}
// parse arguments of bulk command
static int32_t runbulk(int argc, char** argv) {
bool argbrk = false;
const char* rstr = NULL;
int32_t thnum = 1;
bool bin = false;
bool rnd = false;
int32_t mode = 0;
int32_t bulk = 1;
const char* host = "";
int32_t port = kt::DEFPORT;
double tout = 0;
int32_t bopts = 0;
for (int32_t i = 2; i < argc; i++) {
if (!argbrk && argv[i][0] == '-') {
if (!std::strcmp(argv[i], "--")) {
argbrk = true;
} else if (!std::strcmp(argv[i], "-th")) {
if (++i >= argc) usage();
thnum = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-bin")) {
bin = true;
} else if (!std::strcmp(argv[i], "-rnd")) {
rnd = true;
} else if (!std::strcmp(argv[i], "-set")) {
mode = 's';
} else if (!std::strcmp(argv[i], "-get")) {
mode = 'g';
} else if (!std::strcmp(argv[i], "-rem")) {
mode = 'r';
} else if (!std::strcmp(argv[i], "-etc")) {
mode = 'e';
} else if (!std::strcmp(argv[i], "-bulk")) {
if (++i >= argc) usage();
bulk = kc::atoi(argv[i]);
} else if (!std::strcmp(argv[i], "-host")) {
if (++i >= argc) usage();
host = argv[i];
} else if (!std::strcmp(argv[i], "-port")) {
if (++i >= argc) usage();
port = kc::atoi(argv[i]);
} else if (!std::strcmp(argv[i], "-tout")) {
if (++i >= argc) usage();
tout = kc::atof(argv[i]);
} else if (!std::strcmp(argv[i], "-bnr")) {
bopts |= kt::RemoteDB::BONOREPLY;
} else {
usage();
}
} else if (!rstr) {
argbrk = false;
rstr = argv[i];
} else {
usage();
}
}
if (!rstr) usage();
int64_t rnum = kc::atoix(rstr);
if (rnum < 1 || thnum < 1 || bulk < 1 || port < 1) usage();
if (thnum > THREADMAX) thnum = THREADMAX;
int32_t rv = procbulk(rnum, thnum, bin, rnd, mode, bulk, host, port, tout, bopts);
return rv;
}
// parse arguments of wicked command
static int32_t runwicked(int argc, char** argv) {
bool argbrk = false;
const char* rstr = NULL;
int32_t thnum = 1;
int32_t itnum = 1;
const char* host = "";
int32_t port = kt::DEFPORT;
double tout = 0;
for (int32_t i = 2; i < argc; i++) {
if (!argbrk && argv[i][0] == '-') {
if (!std::strcmp(argv[i], "--")) {
argbrk = true;
} else if (!std::strcmp(argv[i], "-th")) {
if (++i >= argc) usage();
thnum = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-it")) {
if (++i >= argc) usage();
itnum = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-host")) {
if (++i >= argc) usage();
host = argv[i];
} else if (!std::strcmp(argv[i], "-port")) {
if (++i >= argc) usage();
port = kc::atoi(argv[i]);
} else if (!std::strcmp(argv[i], "-tout")) {
if (++i >= argc) usage();
tout = kc::atof(argv[i]);
} else {
usage();
}
} else if (!rstr) {
argbrk = false;
rstr = argv[i];
} else {
usage();
}
}
if (!rstr) usage();
int64_t rnum = kc::atoix(rstr);
if (rnum < 1 || thnum < 1 || port < 1) usage();
if (thnum > THREADMAX) thnum = THREADMAX;
int32_t rv = procwicked(rnum, thnum, itnum, host, port, tout);
return rv;
}
// parse arguments of usual command
static int32_t runusual(int argc, char** argv) {
bool argbrk = false;
const char* rstr = NULL;
int32_t thnum = 1;
int32_t itnum = 1;
const char* host = "";
int32_t port = kt::DEFPORT;
double tout = 0;
int64_t kp = 0;
int64_t vs = 0;
int64_t xt = 0;
double iv = 0;
for (int32_t i = 2; i < argc; i++) {
if (!argbrk && argv[i][0] == '-') {
if (!std::strcmp(argv[i], "--")) {
argbrk = true;
} else if (!std::strcmp(argv[i], "-th")) {
if (++i >= argc) usage();
thnum = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-it")) {
if (++i >= argc) usage();
itnum = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-host")) {
if (++i >= argc) usage();
host = argv[i];
} else if (!std::strcmp(argv[i], "-port")) {
if (++i >= argc) usage();
port = kc::atoi(argv[i]);
} else if (!std::strcmp(argv[i], "-tout")) {
if (++i >= argc) usage();
tout = kc::atof(argv[i]);
} else if (!std::strcmp(argv[i], "-kp")) {
if (++i >= argc) usage();
kp = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-vs")) {
if (++i >= argc) usage();
vs = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-xt")) {
if (++i >= argc) usage();
xt = kc::atoix(argv[i]);
} else if (!std::strcmp(argv[i], "-iv")) {
if (++i >= argc) usage();
iv = kc::atof(argv[i]);
} else {
usage();
}
} else if (!rstr) {
argbrk = false;
rstr = argv[i];
} else {
usage();
}
}
if (!rstr) usage();
int64_t rnum = kc::atoix(rstr);
if (rnum < 1 || thnum < 1 || port < 1) usage();
if (thnum > THREADMAX) thnum = THREADMAX;
if (kp < 1) kp = rnum * thnum;
int32_t rv = procusual(rnum, thnum, itnum, host, port, tout, kp, vs, xt, iv);
return rv;
}
// perform order command
static int32_t procorder(int64_t rnum, int32_t thnum, bool rnd, int32_t mode,
const char* host, int32_t port, double tout) {
oprintf("\n seed=%u rnum=%lld thnum=%d rnd=%d mode=%d host=%s port=%d"
" tout=%f\n\n", g_randseed, (long long)rnum, thnum, rnd, mode, host, port, tout);
bool err = false;
oprintf("opening the database:\n");
double stime = kc::time();
kt::RemoteDB* dbs = new kt::RemoteDB[thnum];
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].open(host, port, tout)) {
dberrprint(dbs + i, __LINE__, "DB::open");
err = true;
}
}
if (mode != 'g' && mode != 'r' && !dbs[0].clear()) {
dberrprint(dbs, __LINE__, "DB::clear");
err = true;
}
double etime = kc::time();
oprintf("time: %.3f\n", etime - stime);
if (mode == 0 || mode == 's' || mode == 'e') {
oprintf("setting records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), rnd_(false), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool rnd, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
rnd_ = rnd;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
int64_t xt = rnd_ ? myrand(600) + 1 : kc::INT64MAX;
if (!db_->set(kbuf, ksiz, kbuf, ksiz, xt)) {
dberrprint(db_, __LINE__, "DB::set");
err_ = true;
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool rnd_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, rnd, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, mode == 's');
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 'e') {
oprintf("adding records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), rnd_(false), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool rnd, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
rnd_ = rnd;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
int64_t xt = rnd_ ? myrand(600) + 1 : kc::INT64MAX;
if (!db_->add(kbuf, ksiz, kbuf, ksiz, xt) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::add");
err_ = true;
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool rnd_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, rnd, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, false);
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 'e') {
oprintf("appending records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), rnd_(false), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool rnd, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
rnd_ = rnd;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
int64_t xt = rnd_ ? myrand(600) + 1 : kc::INT64MAX;
if (!db_->append(kbuf, ksiz, kbuf, ksiz, xt)) {
dberrprint(db_, __LINE__, "DB::set");
err_ = true;
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool rnd_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, rnd, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, false);
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 0 || mode == 'g' || mode == 'e') {
oprintf("geting records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), rnd_(false), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool rnd, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
rnd_ = rnd;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
size_t vsiz;
char* vbuf = db_->get(kbuf, ksiz, &vsiz);
if (vbuf) {
if (vsiz < ksiz || std::memcmp(vbuf, kbuf, ksiz)) {
dberrprint(db_, __LINE__, "DB::get");
err_ = true;
}
delete[] vbuf;
} else if (!rnd_ || db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::get");
err_ = true;
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool rnd_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, rnd, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, mode == 'g');
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 'e') {
oprintf("traversing the database by the outer cursor:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), rnd_(false), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool rnd, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
rnd_ = rnd;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
kt::RemoteDB::Cursor* cur = db_->cursor();
if (!cur->jump() && cur->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::jump");
err_ = true;
}
int64_t cnt = 0;
const char* kbuf;
size_t ksiz;
while ((kbuf = cur->get_key(&ksiz)) != NULL) {
cnt++;
if (rnd_) {
switch (myrand(5)) {
case 0: {
char vbuf[RECBUFSIZ];
size_t vsiz = std::sprintf(vbuf, "%lld", (long long)cnt);
if (!cur->set_value(vbuf, vsiz, myrand(600) + 1, myrand(2) == 0) &&
cur->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::set_value");
err_ = true;
}
break;
}
case 1: {
if (!cur->remove() && cur->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::remove");
err_ = true;
}
break;
}
case 2: {
size_t rsiz, vsiz;
const char* vbuf;
int64_t xt;
char* rbuf = cur->get(&rsiz, &vbuf, &vsiz, &xt, myrand(2) == 0);
if (rbuf ) {
delete[] rbuf;
} else if (cur->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::et");
err_ = true;
}
break;
}
}
} else {
size_t vsiz;
char* vbuf = cur->get_value(&vsiz);
if (vbuf) {
delete[] vbuf;
} else {
dberrprint(db_, __LINE__, "Cursor::get_value");
err_ = true;
}
}
delete[] kbuf;
if (!cur->step() && cur->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::step");
err_ = true;
}
if (id_ < 1 && rnum_ > 250 && cnt % (rnum_ / 250) == 0) {
oputchar('.');
if (cnt == rnum_ || cnt % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)cnt);
}
}
if (cur->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::get_key");
err_ = true;
}
if (!rnd_ && cnt != db_->count()) {
dberrprint(db_, __LINE__, "Cursor::get_key");
err_ = true;
}
if (id_ < 1) oprintf(" (end)\n");
delete cur;
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool rnd_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, rnd, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, false);
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 0 || mode == 'r' || mode == 'e') {
oprintf("removing records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), rnd_(false), mode_(0), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool rnd, int32_t mode,
kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
rnd_ = rnd;
mode_ = mode;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
if (!db_->remove(kbuf, ksiz) &&
((!rnd_ && mode_ != 'e') || db_->error() != kt::RemoteDB::Error::LOGIC)) {
dberrprint(db_, __LINE__, "DB::remove");
err_ = true;
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool rnd_;
int32_t mode_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, rnd, mode, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, mode == 'r' || mode == 'e');
oprintf("time: %.3f\n", etime - stime);
}
oprintf("closing the database:\n");
stime = kc::time();
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].close()) {
dberrprint(dbs + i, __LINE__, "DB::close");
err = true;
}
}
etime = kc::time();
oprintf("time: %.3f\n", etime - stime);
delete[] dbs;
oprintf("%s\n\n", err ? "error" : "ok");
return err ? 1 : 0;
}
// perform bulk command
static int32_t procbulk(int64_t rnum, int32_t thnum, bool bin, bool rnd, int32_t mode,
int32_t bulk, const char* host, int32_t port, double tout,
int32_t bopts) {
oprintf("\n seed=%u rnum=%lld thnum=%d bin=%d rnd=%d mode=%d bulk=%d"
" host=%s port=%d tout=%f bopts=%d\n\n",
g_randseed, (long long)rnum, thnum, bin, rnd, mode, bulk, host, port, tout, bopts);
bool err = false;
oprintf("opening the database:\n");
double stime = kc::time();
kt::RemoteDB* dbs = new kt::RemoteDB[thnum];
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].open(host, port, tout)) {
dberrprint(dbs + i, __LINE__, "DB::open");
err = true;
}
}
if (mode != 'g' && mode != 'r' && !dbs[0].clear()) {
dberrprint(dbs, __LINE__, "DB::clear");
err = true;
}
double etime = kc::time();
oprintf("time: %.3f\n", etime - stime);
if (mode == 0 || mode == 's') {
oprintf("setting records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), bin_(false), rnd_(false), bulk_(0),
bopts_(0), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool bin, bool rnd, int32_t bulk,
int32_t bopts, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
bin_ = bin;
rnd_ = rnd;
bulk_ = bulk;
bopts_ = bopts;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
std::map recs;
std::vector bulkrecs;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
std::string key(kbuf, ksiz);
int64_t xt = rnd_ ? myrand(600) + 1 : kc::INT64MAX;
if (bin_) {
kt::RemoteDB::BulkRecord rec = { 0, key, key, xt };
bulkrecs.push_back(rec);
if (bulkrecs.size() >= (size_t)bulk_) {
if (db_->set_bulk_binary(bulkrecs, bopts_) < 0) {
dberrprint(db_, __LINE__, "DB::set_bulk_binary");
err_ = true;
}
bulkrecs.clear();
}
} else {
recs[key] = key;
if (recs.size() >= (size_t)bulk_) {
if (db_->set_bulk(recs, xt) != (int64_t)recs.size()) {
dberrprint(db_, __LINE__, "DB::set_bulk");
err_ = true;
}
recs.clear();
}
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
if (bulkrecs.size() > 0) {
if (db_->set_bulk_binary(bulkrecs, bopts_) < 0) {
dberrprint(db_, __LINE__, "DB::set_bulk_binary");
err_ = true;
}
bulkrecs.clear();
}
if (recs.size() > 0) {
int64_t xt = rnd_ ? myrand(600) + 1 : kc::INT64MAX;
if (db_->set_bulk(recs, xt) != (int64_t)recs.size()) {
dberrprint(db_, __LINE__, "DB::set_bulk");
err_ = true;
}
recs.clear();
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool bin_;
bool rnd_;
int32_t bulk_;
int32_t bopts_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, bin, rnd, bulk, bopts, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, mode == 's');
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 0 || mode == 'g') {
oprintf("getting records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), bin_(false), rnd_(false), bulk_(0),
db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool bin, bool rnd, int32_t bulk,
int32_t bopts, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
bin_ = bin;
rnd_ = rnd;
bulk_ = bulk;
bopts_ = bopts;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
std::vector keys;
std::vector bulkrecs;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
std::string key(kbuf, ksiz);
if (bin_) {
kt::RemoteDB::BulkRecord rec = { 0, key, "", 0 };
bulkrecs.push_back(rec);
if (bulkrecs.size() >= (size_t)bulk_) {
if (db_->get_bulk_binary(&bulkrecs) < 0) {
dberrprint(db_, __LINE__, "DB::get_bulk_binary");
err_ = true;
}
bulkrecs.clear();
}
} else {
keys.push_back(key);
if (keys.size() >= (size_t)bulk_) {
std::map recs;
if (db_->get_bulk(keys, &recs) < 0) {
dberrprint(db_, __LINE__, "DB::get_bulk");
err_ = true;
}
keys.clear();
}
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
if (bulkrecs.size() > 0) {
if (db_->get_bulk_binary(&bulkrecs) < 0) {
dberrprint(db_, __LINE__, "DB::get_bulk_binary");
err_ = true;
}
bulkrecs.clear();
}
if (keys.size() > 0) {
std::map recs;
if (db_->get_bulk(keys, &recs) < 0) {
dberrprint(db_, __LINE__, "DB::get_bulk");
err_ = true;
}
keys.clear();
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool bin_;
bool rnd_;
int32_t bulk_;
int32_t bopts_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, bin, rnd, bulk, bopts, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, mode == 'g');
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 0 || mode == 'r') {
oprintf("removing records:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), bin_(false), rnd_(false), bulk_(0),
db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool bin, bool rnd, int32_t bulk,
int32_t bopts, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
bin_ = bin;
rnd_ = rnd;
bulk_ = bulk;
bopts_ = bopts;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
int64_t base = id_ * rnum_;
int64_t range = rnum_ * thnum_;
std::vector keys;
std::vector bulkrecs;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(range) + 1 : base + i));
std::string key(kbuf, ksiz);
if (bin_) {
kt::RemoteDB::BulkRecord rec = { 0, key, "", 0 };
bulkrecs.push_back(rec);
if (bulkrecs.size() >= (size_t)bulk_) {
if (db_->remove_bulk_binary(bulkrecs, bopts_) < 0) {
dberrprint(db_, __LINE__, "DB::remove_bulk_binary");
err_ = true;
}
bulkrecs.clear();
}
} else {
keys.push_back(key);
if (keys.size() >= (size_t)bulk_) {
if (db_->remove_bulk(keys) < 0) {
dberrprint(db_, __LINE__, "DB::remove_bulk");
err_ = true;
}
keys.clear();
}
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
if (bulkrecs.size() > 0) {
if (db_->remove_bulk_binary(bulkrecs, bopts_) < 0) {
dberrprint(db_, __LINE__, "DB::remove_bulk_binary");
err_ = true;
}
bulkrecs.clear();
}
if (keys.size() > 0) {
if (db_->remove_bulk(keys) < 0) {
dberrprint(db_, __LINE__, "DB::remove_bulk");
err_ = true;
}
keys.clear();
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool bin_;
bool rnd_;
int32_t bulk_;
int32_t bopts_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, bin, rnd, bulk, bopts, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, mode == 'r');
oprintf("time: %.3f\n", etime - stime);
}
if (mode == 0 || mode == 'e') {
oprintf("performing mixed operations:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), bin_(false), rnd_(false), bulk_(0),
bopts_(0), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum, bool bin, bool rnd, int32_t bulk,
int32_t bopts, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
bin_ = bin;
rnd_ = rnd;
bulk_ = bulk;
bopts_ = bopts;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
std::map recs;
std::vector keys;
std::vector bulkrecs;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld",
(long long)(rnd_ ? myrand(rnum_) + 1 : i));
std::string key(kbuf, ksiz);
int64_t xt = rnd_ ? myrand(600) + 1 : kc::INT64MAX;
int32_t cmd;
if (rnd_) {
cmd = myrand(100);
} else {
cmd = i + id_;
cmd = kc::hashmurmur(&cmd, sizeof(cmd)) % 100;
}
if (bin_) {
kt::RemoteDB::BulkRecord rec = { 0, key, key, xt };
bulkrecs.push_back(rec);
if (bulkrecs.size() >= (size_t)bulk_) {
if (cmd < 50) {
if (db_->get_bulk_binary(&bulkrecs) < 0) {
dberrprint(db_, __LINE__, "DB::get_bulk_binary");
err_ = true;
}
} else if (cmd < 90) {
if (db_->set_bulk_binary(bulkrecs, bopts_) < 0) {
dberrprint(db_, __LINE__, "DB::set_bulk_binary");
err_ = true;
}
} else if (cmd < 98) {
if (db_->remove_bulk_binary(bulkrecs, bopts_) < 0) {
dberrprint(db_, __LINE__, "DB::remove_bulk_binary");
err_ = true;
}
} else {
std::map params, result;
params[key] = key;
if (!db_->play_script_binary("echo", params, &result, bopts_) &&
db_->error() != kt::RemoteDB::Error::NOIMPL &&
db_->error() != kt::RemoteDB::Error::LOGIC &&
db_->error() != kt::RemoteDB::Error::INTERNAL) {
dberrprint(db_, __LINE__, "DB::play_script_binary");
err_ = true;
}
}
bulkrecs.clear();
}
} else {
recs[key] = key;
keys.push_back(key);
if (keys.size() >= (size_t)bulk_) {
if (cmd < 50) {
std::map recs;
if (db_->get_bulk(keys, &recs) < 0) {
dberrprint(db_, __LINE__, "DB::get_bulk");
err_ = true;
}
} else if (cmd < 90) {
if (db_->set_bulk(recs, xt) != (int64_t)recs.size()) {
dberrprint(db_, __LINE__, "DB::set_bulk");
err_ = true;
}
} else if (cmd < 98) {
if (db_->remove_bulk(keys) < 0) {
dberrprint(db_, __LINE__, "DB::remove_bulk");
err_ = true;
}
} else {
std::map params, result;
params[key] = key;
if (!db_->play_script("echo", params, &result) &&
db_->error() != kt::RemoteDB::Error::NOIMPL &&
db_->error() != kt::RemoteDB::Error::LOGIC &&
db_->error() != kt::RemoteDB::Error::INTERNAL) {
dberrprint(db_, __LINE__, "DB::play_script_binary");
err_ = true;
}
}
recs.clear();
keys.clear();
}
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
if (bulkrecs.size() > 0) {
if (db_->set_bulk_binary(bulkrecs, bopts_) < 0) {
dberrprint(db_, __LINE__, "DB::set_bulk_binary");
err_ = true;
}
bulkrecs.clear();
}
if (recs.size() > 0) {
int64_t xt = rnd_ ? myrand(600) + 1 : kc::INT64MAX;
if (db_->set_bulk(recs, xt) != (int64_t)recs.size()) {
dberrprint(db_, __LINE__, "DB::set_bulk");
err_ = true;
}
recs.clear();
}
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
bool bin_;
bool rnd_;
int32_t bulk_;
int32_t bopts_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, bin, rnd, bulk, bopts, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, mode == 'e');
oprintf("time: %.3f\n", etime - stime);
}
oprintf("closing the database:\n");
stime = kc::time();
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].close()) {
dberrprint(dbs + i, __LINE__, "DB::close");
err = true;
}
}
etime = kc::time();
oprintf("time: %.3f\n", etime - stime);
delete[] dbs;
oprintf("%s\n\n", err ? "error" : "ok");
return err ? 1 : 0;
}
// perform wicked command
static int32_t procwicked(int64_t rnum, int32_t thnum, int32_t itnum,
const char* host, int32_t port, double tout) {
oprintf("\n seed=%u rnum=%lld thnum=%d itnum=%d host=%s port=%d"
" tout=%f\n\n", g_randseed, (long long)rnum, thnum, itnum, host, port, tout);
bool err = false;
for (int32_t itcnt = 1; itcnt <= itnum; itcnt++) {
if (itnum > 1) oprintf("iteration %d:\n", itcnt);
double stime = kc::time();
kt::RemoteDB* dbs = new kt::RemoteDB[thnum];
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].open(host, port, tout)) {
dberrprint(dbs + i, __LINE__, "DB::open");
err = true;
}
}
class ThreadWicked : public kc::Thread {
public:
void setparams(int32_t id, kt::RemoteDB* db, int64_t rnum, int32_t thnum,
const char* lbuf) {
id_ = id;
db_ = db;
rnum_ = rnum;
thnum_ = thnum;
lbuf_ = lbuf;
err_ = false;
}
bool error() {
return err_;
}
void run() {
kt::RemoteDB::Cursor* cur = db_->cursor();
int64_t range = rnum_ * thnum_ / 2;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%lld", (long long)(myrand(range) + 1));
if (myrand(1000) == 0) {
ksiz = myrand(RECBUFSIZ) + 1;
if (myrand(2) == 0) {
for (size_t j = 0; j < ksiz; j++) {
kbuf[j] = j;
}
} else {
for (size_t j = 0; j < ksiz; j++) {
kbuf[j] = myrand(256);
}
}
}
const char* vbuf = kbuf;
size_t vsiz = ksiz;
if (myrand(10) == 0) {
vbuf = lbuf_;
vsiz = myrand(RECBUFSIZL) / (myrand(5) + 1);
}
int64_t xt = myrand(600);
if (myrand(100) == 0) db_->set_signal_sending(kbuf, myrand(10) == 0);
do {
switch (myrand(16)) {
case 0: {
if (!db_->set(kbuf, ksiz, vbuf, vsiz, xt)) {
dberrprint(db_, __LINE__, "DB::set");
err_ = true;
}
break;
}
case 1: {
if (!db_->add(kbuf, ksiz, vbuf, vsiz, xt) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::add");
err_ = true;
}
break;
}
case 2: {
if (!db_->replace(kbuf, ksiz, vbuf, vsiz, xt) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::replace");
err_ = true;
}
break;
}
case 3: {
if (!db_->append(kbuf, ksiz, vbuf, vsiz, xt)) {
dberrprint(db_, __LINE__, "DB::append");
err_ = true;
}
break;
}
case 4: {
if (myrand(2) == 0) {
int64_t num = myrand(rnum_);
int64_t orig = myrand(10) == 0 ? kc::INT64MIN : myrand(rnum_);
if (myrand(10) == 0) orig = orig == kc::INT64MIN ? kc::INT64MAX : -orig;
if (db_->increment(kbuf, ksiz, num, orig, xt) == kc::INT64MIN &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::increment");
err_ = true;
}
} else {
double num = myrand(rnum_ * 10) / (myrand(rnum_) + 1.0);
double orig = myrand(10) == 0 ? -kc::inf() : myrand(rnum_);
if (myrand(10) == 0) orig = -orig;
if (kc::chknan(db_->increment_double(kbuf, ksiz, num, orig, xt)) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::increment_double");
err_ = true;
}
}
break;
}
case 5: {
if (!db_->cas(kbuf, ksiz, kbuf, ksiz, vbuf, vsiz, xt) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::cas");
err_ = true;
}
break;
}
case 6: {
if (!db_->remove(kbuf, ksiz) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::remove");
err_ = true;
}
break;
}
case 7: {
if (myrand(2) == 0) {
int32_t vsiz = db_->check(kbuf, ksiz);
if (vsiz < 0 && db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::check");
err_ = true;
}
} else {
size_t rsiz;
char* rbuf = db_->seize(kbuf, ksiz, &rsiz);
if (rbuf) {
delete[] rbuf;
} else if (db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::seize");
err_ = true;
}
}
break;
}
case 8: {
if (myrand(10) == 0) {
if (myrand(4) == 0) {
if (!cur->jump_back(kbuf, ksiz) &&
db_->error() != kt::RemoteDB::Error::NOIMPL &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::jump_back");
err_ = true;
}
} else {
if (!cur->jump(kbuf, ksiz) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::jump");
err_ = true;
}
}
} else {
switch (myrand(3)) {
case 0: {
size_t vsiz = myrand(RECBUFSIZL) / (myrand(5) + 1);
if (!cur->set_value(lbuf_, vsiz, xt, myrand(2) == 0) &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::set_value");
err_ = true;
}
break;
}
case 1: {
if (!cur->remove() && db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::remove");
err_ = true;
}
break;
}
}
if (myrand(5) > 0 && !cur->step() &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "Cursor::step");
err_ = true;
}
}
if (myrand(rnum_ / 50 + 1) == 0) {
std::vector keys;
std::string prefix(kbuf, ksiz > 0 ? ksiz - 1 : 0);
if (db_->match_prefix(prefix, &keys, myrand(10)) == -1) {
dberrprint(db_, __LINE__, "DB::match_prefix");
err_ = true;
}
}
if (myrand(rnum_ / 50 + 1) == 0) {
std::vector keys;
std::string regex(kbuf, ksiz > 0 ? ksiz - 1 : 0);
if (db_->match_regex(regex, &keys, myrand(10)) == -1 &&
db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::match_regex");
err_ = true;
}
}
if (myrand(rnum_ / 50 + 1) == 0) {
std::vector keys;
std::string origin(kbuf, ksiz > 0 ? ksiz - 1 : 0);
if (db_->match_similar(origin, 3, myrand(2) == 0, &keys, myrand(10)) == -1) {
dberrprint(db_, __LINE__, "DB::match_similar");
err_ = true;
}
}
break;
}
case 9: {
std::map recs;
int32_t num = myrand(4);
for (int32_t i = 0; i < num; i++) {
ksiz = std::sprintf(kbuf, "%lld", (long long)(myrand(range) + 1));
std::string key(kbuf, ksiz);
recs[key] = std::string(vbuf, vsiz);
}
if (db_->set_bulk(recs, xt) != (int64_t)recs.size()) {
dberrprint(db_, __LINE__, "DB::set_bulk");
err_ = true;
}
break;
}
case 10: {
std::vector keys;
int32_t num = myrand(4);
for (int32_t i = 0; i < num; i++) {
ksiz = std::sprintf(kbuf, "%lld", (long long)(myrand(range) + 1));
keys.push_back(std::string(kbuf, ksiz));
}
if (db_->remove_bulk(keys) < 0) {
dberrprint(db_, __LINE__, "DB::remove_bulk");
err_ = true;
}
break;
}
case 11: {
std::vector keys;
int32_t num = myrand(4);
for (int32_t i = 0; i < num; i++) {
ksiz = std::sprintf(kbuf, "%lld", (long long)(myrand(range) + 1));
keys.push_back(std::string(kbuf, ksiz));
}
std::map recs;
if (db_->get_bulk(keys, &recs) < 0) {
dberrprint(db_, __LINE__, "DB::get_bulk");
err_ = true;
}
break;
}
default: {
if (myrand(100) == 0) db_->set_signal_waiting(kbuf, 1.0 / (myrand(1000) + 1));
size_t rsiz;
char* rbuf = db_->get(kbuf, ksiz, &rsiz);
if (rbuf) {
delete[] rbuf;
} else if (db_->error() != kt::RemoteDB::Error::LOGIC &&
db_->error() != kt::RemoteDB::Error::TIMEOUT) {
dberrprint(db_, __LINE__, "DB::get");
err_ = true;
}
break;
}
}
} while (myrand(100) == 0);
if (i == rnum_ / 2) {
if (myrand(thnum_ * 4) == 0 && !db_->clear()) {
dberrprint(db_, __LINE__, "DB::clear");
err_ = true;
} else {
if (!db_->synchronize(false)) {
dberrprint(db_, __LINE__, "DB::synchronize");
err_ = true;
}
}
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
}
delete cur;
}
private:
int32_t id_;
kt::RemoteDB* db_;
int64_t rnum_;
int32_t thnum_;
const char* lbuf_;
bool err_;
};
char lbuf[RECBUFSIZL];
std::memset(lbuf, '*', sizeof(lbuf));
ThreadWicked threads[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
threads[i].setparams(i, dbs + i, rnum, thnum, lbuf);
threads[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
threads[i].join();
if (threads[i].error()) err = true;
}
dbmetaprint(dbs, itcnt == itnum);
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].close()) {
dberrprint(dbs + i, __LINE__, "DB::close");
err = true;
}
}
delete[] dbs;
oprintf("time: %.3f\n", kc::time() - stime);
}
oprintf("%s\n\n", err ? "error" : "ok");
return err ? 1 : 0;
}
// perform usual command
static int32_t procusual(int64_t rnum, int32_t thnum, int32_t itnum,
const char* host, int32_t port, double tout,
int64_t kp, int64_t vs, int64_t xt, double iv) {
oprintf("\n seed=%u rnum=%lld thnum=%d itnum=%d host=%s port=%d"
" tout=%f kp=%lld vs=%lld xt=%lld iv=%f\n\n",
g_randseed, (long long)rnum, thnum, itnum, host, port, tout, kp, vs, xt, iv);
bool err = false;
oprintf("opening the database:\n");
double stime = kc::time();
kt::RemoteDB* dbs = new kt::RemoteDB[thnum];
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].open(host, port, tout)) {
dberrprint(dbs + i, __LINE__, "DB::open");
err = true;
}
}
double etime = kc::time();
oprintf("time: %.3f\n", etime - stime);
oprintf("performing mixed operations:\n");
stime = kc::time();
class Worker : public kc::Thread {
public:
Worker() : id_(0), rnum_(0), thnum_(0), db_(NULL), err_(false) {}
void setparams(int32_t id, int64_t rnum, int32_t thnum,
int64_t kp, int64_t vs, int64_t xt, double iv, kt::RemoteDB* db) {
id_ = id;
rnum_ = rnum;
thnum_ = thnum;
kp_ = kp;
vs_ = vs;
xt_ = xt;
iv_ = iv;
db_ = db;
}
bool error() {
return err_;
}
private:
void run() {
size_t vsmax = vs_ > kc::INT8MAX ? vs_ : kc::INT8MAX;
char* vbuf = new char[vsmax];
for (size_t i = 0; i < vsmax; i++) {
vbuf[i] = 'A' + myrand('Z' - 'A');
}
double slptime = 0;
for (int64_t i = 1; !err_ && i <= rnum_; i++) {
char kbuf[RECBUFSIZ];
size_t ksiz = std::sprintf(kbuf, "%08lld", (long long)myrand(kp_));
std::memcpy(vbuf, kbuf, ksiz);
int32_t cmd = myrand(100);
if (cmd < 50) {
size_t rsiz;
char* rbuf = db_->get(kbuf, ksiz, &rsiz);
if (rbuf) {
delete[] rbuf;
} else if (db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::get");
err_ = true;
}
} else if (cmd < 60) {
if (!db_->remove(kbuf, ksiz) && db_->error() != kt::RemoteDB::Error::LOGIC) {
dberrprint(db_, __LINE__, "DB::remove");
err_ = true;
}
} else {
size_t vsiz = vs_ > 0 ? vs_ : myrand(kc::INT8MAX);
int64_t xt = xt_ == 0 ? kc::UINT32MAX : xt_ < 0 ? myrand(-xt_) + 1 : xt_;
if (!db_->set(kbuf, ksiz, vbuf, vsiz, xt)) {
dberrprint(db_, __LINE__, "DB::set");
err_ = true;
}
}
if (id_ < 1 && rnum_ > 250 && i % (rnum_ / 250) == 0) {
oputchar('.');
if (i == rnum_ || i % (rnum_ / 10) == 0) oprintf(" (%08lld)\n", (long long)i);
}
if (i % kc::INT8MAX == 0) {
for (size_t i = 0; i < vsmax; i++) {
vbuf[i] = 'A' + myrand('Z' - 'A');
}
}
if (iv_ > 0) {
slptime += iv_;
if (slptime >= 100) {
Thread::sleep(slptime / 1000);
slptime = 0;
}
}
}
delete[] vbuf;
}
int32_t id_;
int64_t rnum_;
int32_t thnum_;
int64_t kp_;
int64_t vs_;
int64_t xt_;
double iv_;
kt::RemoteDB* db_;
bool err_;
};
Worker workers[THREADMAX];
for (int32_t i = 0; i < thnum; i++) {
workers[i].setparams(i, rnum, thnum, kp, vs, xt, iv, dbs + i);
workers[i].start();
}
for (int32_t i = 0; i < thnum; i++) {
workers[i].join();
if (workers[i].error()) err = true;
}
etime = kc::time();
dbmetaprint(dbs, true);
oprintf("time: %.3f\n", etime - stime);
oprintf("closing the database:\n");
stime = kc::time();
for (int32_t i = 0; i < thnum; i++) {
if (!dbs[i].close()) {
dberrprint(dbs + i, __LINE__, "DB::close");
err = true;
}
}
etime = kc::time();
oprintf("time: %.3f\n", etime - stime);
delete[] dbs;
oprintf("%s\n\n", err ? "error" : "ok");
return err ? 1 : 0;
}
// END OF FILE
kyototycoon-0.9.56/kttimeddb.h 0000644 0001750 0001750 00000304645 11757471602 015364 0 ustar mikio mikio /*************************************************************************************************
* Timed database
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#ifndef _KTTIMEDDB_H // duplication check
#define _KTTIMEDDB_H
#include
#include
#include
#include
namespace kyototycoon { // common namespace
/**
* Timed database.
* @note This class is a concrete class of a wrapper for the polymorphic database to add
* expiration features. This class can be inherited but overwriting methods is forbidden.
* Before every database operation, it is necessary to call the TimedDB::open method in order to
* open a database file and connect the database object to it. To avoid data missing or
* corruption, it is important to close every database file by the TimedDB::close method when
* the database is no longer in use. It is forbidden for multible database objects in a process
* to open the same database at the same time.
*/
class TimedDB {
public:
class Cursor;
class Visitor;
class UpdateTrigger;
/** The width of expiration time. */
static const int32_t XTWIDTH = 5;
/** The maximum number of expiration time. */
static const int64_t XTMAX = (1LL << (XTWIDTH * 8)) - 1;
private:
class TimedVisitor;
class TimedMetaTrigger;
struct MergeLine;
/* The magic data of the database type. */
static const uint8_t MAGICDATA = 0xbb;
/* The score unit of expiratoin. */
static const int64_t XTSCUNIT = 256;
/* The inverse frequency of reading expiration. */
static const int64_t XTREADFREQ = 8;
/* The inverse frequency of iterating expiration. */
static const int64_t XTITERFREQ = 4;
/* The unit step number of expiration. */
static const int64_t XTUNIT = 8;
/* The size of the logging buffer. */
static const size_t LOGBUFSIZ = 1024;
public:
/**
* Cursor to indicate a record.
*/
class Cursor {
friend class TimedDB;
public:
/**
* Constructor.
* @param db the container database object.
*/
explicit Cursor(TimedDB* db) : db_(db), cur_(NULL), back_(false) {
_assert_(db);
cur_ = db_->db_.cursor();
}
/**
* Destructor.
*/
virtual ~Cursor() {
_assert_(true);
delete cur_;
}
/**
* Jump the cursor to the first record for forward scan.
* @return true on success, or false on failure.
*/
bool jump() {
_assert_(true);
if (!cur_->jump()) return false;
back_ = false;
return true;
}
/**
* Jump the cursor to a record for forward scan.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @return true on success, or false on failure.
*/
bool jump(const char* kbuf, size_t ksiz) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
if (!cur_->jump(kbuf, ksiz)) return false;
back_ = false;
return true;
}
/**
* Jump the cursor to a record for forward scan.
* @note Equal to the original Cursor::jump method except that the parameter is std::string.
*/
bool jump(const std::string& key) {
_assert_(true);
return jump(key.c_str(), key.size());
}
/**
* Jump the cursor to the last record for backward scan.
* @return true on success, or false on failure.
* @note This method is dedicated to tree databases. Some database types, especially hash
* databases, may provide a dummy implementation.
*/
bool jump_back() {
_assert_(true);
if (!cur_->jump_back()) return false;
back_ = true;
return true;
}
/**
* Jump the cursor to a record for backward scan.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @return true on success, or false on failure.
* @note This method is dedicated to tree databases. Some database types, especially hash
* databases, will provide a dummy implementation.
*/
bool jump_back(const char* kbuf, size_t ksiz) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
if (!cur_->jump_back(kbuf, ksiz)) return false;
back_ = true;
return true;
}
/**
* Jump the cursor to a record for backward scan.
* @note Equal to the original Cursor::jump_back method except that the parameter is
* std::string.
*/
bool jump_back(const std::string& key) {
_assert_(true);
return jump_back(key.c_str(), key.size());
}
/**
* Step the cursor to the next record.
* @return true on success, or false on failure.
*/
bool step() {
_assert_(true);
if (!cur_->step()) return false;
back_ = false;
return true;
}
/**
* Step the cursor to the previous record.
* @return true on success, or false on failure.
* @note This method is dedicated to tree databases. Some database types, especially hash
* databases, may provide a dummy implementation.
*/
bool step_back() {
_assert_(true);
if (!cur_->step_back()) return false;
back_ = true;
return true;
}
/**
* Accept a visitor to the current record.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @param step true to move the cursor to the next record, or false for no move.
* @return true on success, or false on failure.
* @note the operation for each record is performed atomically and other threads accessing
* the same record are blocked.
*/
bool accept(Visitor* visitor, bool writable = true, bool step = false) {
_assert_(visitor);
bool err = false;
int64_t ct = std::time(NULL);
while (true) {
TimedVisitor myvisitor(db_, visitor, ct, true);
if (!cur_->accept(&myvisitor, writable, step)) {
err = true;
break;
}
if (myvisitor.again()) {
if (!step && !(back_ ? cur_->step_back() : cur_->step())) {
err = true;
break;
}
continue;
}
break;
}
if (db_->xcur_) {
int64_t xtsc = writable ? XTSCUNIT : XTSCUNIT / XTREADFREQ;
if (!db_->expire_records(xtsc)) err = true;
}
return !err;
}
/**
* Set the value of the current record.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @param step true to move the cursor to the next record, or false for no move.
* @return true on success, or false on failure.
*/
bool set_value(const char* vbuf, size_t vsiz, int64_t xt = kc::INT64MAX, bool step = false) {
_assert_(vbuf && vsiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(const char* vbuf, size_t vsiz, int64_t xt) :
vbuf_(vbuf), vsiz_(vsiz), xt_(xt), ok_(false) {}
bool ok() const {
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
ok_ = true;
*sp = vsiz_;
*xtp = xt_;
return vbuf_;
}
const char* vbuf_;
size_t vsiz_;
int64_t xt_;
bool ok_;
};
VisitorImpl visitor(vbuf, vsiz, xt);
if (!accept(&visitor, true, step)) return false;
if (!visitor.ok()) return false;
return true;
}
/**
* Set the value of the current record.
* @note Equal to the original Cursor::set_value method except that the parameter is
* std::string.
*/
bool set_value_str(const std::string& value, int64_t xt = kc::INT64MAX, bool step = false) {
_assert_(true);
return set_value(value.c_str(), value.size(), xt, step);
}
/**
* Remove the current record.
* @return true on success, or false on failure.
* @note If no record corresponds to the key, false is returned. The cursor is moved to the
* next record implicitly.
*/
bool remove() {
_assert_(true);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : ok_(false) {}
bool ok() const {
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
ok_ = true;
return REMOVE;
}
bool ok_;
};
VisitorImpl visitor;
if (!accept(&visitor, true, false)) return false;
if (!visitor.ok()) return false;
return true;
}
/**
* Get the key of the current record.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param step true to move the cursor to the next record, or false for no move.
* @return the pointer to the key region of the current record, or NULL on failure.
* @note If the cursor is invalidated, NULL is returned. Because an additional zero
* code is appended at the end of the region of the return value, the return value can be
* treated as a C-style string. Because the region of the return value is allocated with the
* the new[] operator, it should be released with the delete[] operator when it is no longer
* in use.
*/
char* get_key(size_t* sp, bool step = false) {
_assert_(sp);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : kbuf_(NULL), ksiz_(0) {}
char* pop(size_t* sp) {
*sp = ksiz_;
return kbuf_;
}
void clear() {
delete[] kbuf_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
kbuf_ = new char[ksiz+1];
std::memcpy(kbuf_, kbuf, ksiz);
kbuf_[ksiz] = '\0';
ksiz_ = ksiz;
return NOP;
}
char* kbuf_;
size_t ksiz_;
};
VisitorImpl visitor;
if (!accept(&visitor, false, step)) {
visitor.clear();
*sp = 0;
return NULL;
}
size_t ksiz;
char* kbuf = visitor.pop(&ksiz);
if (!kbuf) {
*sp = 0;
return NULL;
}
*sp = ksiz;
return kbuf;
}
/**
* Get the key of the current record.
* @note Equal to the original Cursor::get_key method except that a parameter is a string to
* contain the result and the return value is bool for success.
*/
bool get_key(std::string* key, bool step = false) {
_assert_(key);
size_t ksiz;
char* kbuf = get_key(&ksiz, step);
if (!kbuf) return false;
key->clear();
key->append(kbuf, ksiz);
delete[] kbuf;
return true;
}
/**
* Get the value of the current record.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param step true to move the cursor to the next record, or false for no move.
* @return the pointer to the value region of the current record, or NULL on failure.
* @note If the cursor is invalidated, NULL is returned. Because an additional zero
* code is appended at the end of the region of the return value, the return value can be
* treated as a C-style string. Because the region of the return value is allocated with the
* the new[] operator, it should be released with the delete[] operator when it is no longer
* in use.
*/
char* get_value(size_t* sp, bool step = false) {
_assert_(sp);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : vbuf_(NULL), vsiz_(0) {}
char* pop(size_t* sp) {
*sp = vsiz_;
return vbuf_;
}
void clear() {
delete[] vbuf_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
vbuf_ = new char[vsiz+1];
std::memcpy(vbuf_, vbuf, vsiz);
vbuf_[vsiz] = '\0';
vsiz_ = vsiz;
return NOP;
}
char* vbuf_;
size_t vsiz_;
};
VisitorImpl visitor;
if (!accept(&visitor, false, step)) {
visitor.clear();
*sp = 0;
return NULL;
}
size_t vsiz;
char* vbuf = visitor.pop(&vsiz);
if (!vbuf) {
*sp = 0;
return NULL;
}
*sp = vsiz;
return vbuf;
}
/**
* Get the value of the current record.
* @note Equal to the original Cursor::get_value method except that a parameter is a string
* to contain the result and the return value is bool for success.
*/
bool get_value(std::string* value, bool step = false) {
_assert_(value);
size_t vsiz;
char* vbuf = get_value(&vsiz, step);
if (!vbuf) return false;
value->clear();
value->append(vbuf, vsiz);
delete[] vbuf;
return true;
}
/**
* Get a pair of the key and the value of the current record.
* @param ksp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param vbp the pointer to the variable into which the pointer to the value region is
* assigned.
* @param vsp the pointer to the variable into which the size of the value region is
* assigned.
* @param xtp the pointer to the variable into which the absolute expiration time is
* assigned. If it is NULL, it is ignored.
* @param step true to move the cursor to the next record, or false for no move.
* @return the pointer to the pair of the key region, or NULL on failure.
* @note If the cursor is invalidated, NULL is returned. Because an additional zero code is
* appended at the end of each region of the key and the value, each region can be treated
* as a C-style string. The return value should be deleted explicitly by the caller with
* the detele[] operator.
*/
char* get(size_t* ksp, const char** vbp, size_t* vsp, int64_t* xtp = NULL,
bool step = false) {
_assert_(ksp && vbp && vsp);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : kbuf_(NULL), ksiz_(0), vbuf_(NULL), vsiz_(0), xt_(0) {}
char* pop(size_t* ksp, const char** vbp, size_t* vsp, int64_t* xtp) {
*ksp = ksiz_;
*vbp = vbuf_;
*vsp = vsiz_;
if (xtp) *xtp = xt_;
return kbuf_;
}
void clear() {
delete[] kbuf_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
size_t rsiz = ksiz + 1 + vsiz + 1;
kbuf_ = new char[rsiz];
std::memcpy(kbuf_, kbuf, ksiz);
kbuf_[ksiz] = '\0';
ksiz_ = ksiz;
vbuf_ = kbuf_ + ksiz + 1;
std::memcpy(vbuf_, vbuf, vsiz);
vbuf_[vsiz] = '\0';
vsiz_ = vsiz;
xt_ = *xtp;
return NOP;
}
char* kbuf_;
size_t ksiz_;
char* vbuf_;
size_t vsiz_;
int64_t xt_;
};
VisitorImpl visitor;
if (!accept(&visitor, false, step)) {
visitor.clear();
*ksp = 0;
*vbp = NULL;
*vsp = 0;
if (xtp) *xtp = 0;
return NULL;
}
return visitor.pop(ksp, vbp, vsp, xtp);
}
/**
* Get a pair of the key and the value of the current record.
* @note Equal to the original Cursor::get method except that parameters are strings
* to contain the result and the return value is bool for success.
*/
bool get(std::string* key, std::string* value, int64_t* xtp = NULL, bool step = false) {
_assert_(key && value);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(std::string* key, std::string* value) :
key_(key), value_(value), xt_(0), ok_(false) {}
bool ok(int64_t* xtp) {
if (xtp) *xtp = xt_;
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
key_->clear();
key_->append(kbuf, ksiz);
value_->clear();
value_->append(vbuf, vsiz);
xt_ = *xtp;
ok_ = true;
return NOP;
}
std::string* key_;
std::string* value_;
int64_t xt_;
bool ok_;
};
VisitorImpl visitor(key, value);
if (!accept(&visitor, false, step)) return false;
return visitor.ok(xtp);
}
/**
* Get a pair of the key and the value of the current record and remove it atomically.
* @param ksp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param vbp the pointer to the variable into which the pointer to the value region is
* assigned.
* @param vsp the pointer to the variable into which the size of the value region is
* assigned.
* @param xtp the pointer to the variable into which the absolute expiration time is
* assigned. If it is NULL, it is ignored.
* @return the pointer to the pair of the key region, or NULL on failure.
* @note If the cursor is invalidated, NULL is returned. Because an additional zero code is
* appended at the end of each region of the key and the value, each region can be treated
* as a C-style string. The return value should be deleted explicitly by the caller with
* the detele[] operator.
*/
char* seize(size_t* ksp, const char** vbp, size_t* vsp, int64_t* xtp = NULL) {
_assert_(ksp && vbp && vsp);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : kbuf_(NULL), ksiz_(0), vbuf_(NULL), vsiz_(0), xt_(0) {}
char* pop(size_t* ksp, const char** vbp, size_t* vsp, int64_t* xtp) {
*ksp = ksiz_;
*vbp = vbuf_;
*vsp = vsiz_;
if (xtp) *xtp = xt_;
return kbuf_;
}
void clear() {
delete[] kbuf_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
size_t rsiz = ksiz + 1 + vsiz + 1;
kbuf_ = new char[rsiz];
std::memcpy(kbuf_, kbuf, ksiz);
kbuf_[ksiz] = '\0';
ksiz_ = ksiz;
vbuf_ = kbuf_ + ksiz + 1;
std::memcpy(vbuf_, vbuf, vsiz);
vbuf_[vsiz] = '\0';
vsiz_ = vsiz;
xt_ = *xtp;
return REMOVE;
}
char* kbuf_;
size_t ksiz_;
char* vbuf_;
size_t vsiz_;
int64_t xt_;
};
VisitorImpl visitor;
if (!accept(&visitor, true, false)) {
visitor.clear();
*ksp = 0;
*vbp = NULL;
*vsp = 0;
if (xtp) *xtp = 0;
return NULL;
}
return visitor.pop(ksp, vbp, vsp, xtp);
}
/**
* Get a pair of the key and the value of the current record and remove it atomically.
* @note Equal to the original Cursor::seize method except that parameters are strings
* to contain the result and the return value is bool for success.
*/
bool seize(std::string* key, std::string* value, int64_t* xtp = NULL) {
_assert_(key && value);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(std::string* key, std::string* value) :
key_(key), value_(value), xt_(0), ok_(false) {}
bool ok(int64_t* xtp) {
if (xtp) *xtp = xt_;
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
key_->clear();
key_->append(kbuf, ksiz);
value_->clear();
value_->append(vbuf, vsiz);
xt_ = *xtp;
ok_ = true;
return REMOVE;
}
std::string* key_;
std::string* value_;
int64_t xt_;
bool ok_;
};
VisitorImpl visitor(key, value);
if (!accept(&visitor, true, false)) return false;
return visitor.ok(xtp);
}
/**
* Get the database object.
* @return the database object.
*/
TimedDB* db() {
_assert_(true);
return db_;
}
/**
* Get the last happened error.
* @return the last happened error.
*/
kc::BasicDB::Error error() {
_assert_(true);
return db()->error();
}
private:
/** Dummy constructor to forbid the use. */
Cursor(const Cursor&);
/** Dummy Operator to forbid the use. */
Cursor& operator =(const Cursor&);
/** The inner database. */
TimedDB* db_;
/** The inner cursor. */
kc::BasicDB::Cursor* cur_;
/** The backward flag. */
bool back_;
};
/**
* Interface to access a record.
*/
class Visitor {
public:
/** Special pointer for no operation. */
static const char* const NOP;
/** Special pointer to remove the record. */
static const char* const REMOVE;
/**
* Destructor.
*/
virtual ~Visitor() {
_assert_(true);
}
/**
* Visit a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param xtp the pointer to the variable into which the expiration time from now in seconds
* is assigned. The initial value is the absolute expiration time.
* @return If it is the pointer to a region, the value is replaced by the content. If it
* is Visitor::NOP, nothing is modified. If it is Visitor::REMOVE, the record is removed.
*/
virtual const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && vbuf && vsiz <= kc::MEMMAXSIZ && sp && xtp);
return NOP;
}
/**
* Visit a empty record space.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param xtp the pointer to the variable into which the expiration time from now in seconds
* is assigned.
* @return If it is the pointer to a region, the value is replaced by the content. If it
* is Visitor::NOP or Visitor::REMOVE, nothing is modified.
*/
virtual const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && sp && xtp);
return NOP;
}
/**
* Preprocess the main operations.
*/
virtual void visit_before() {
_assert_(true);
}
/**
* Postprocess the main operations.
*/
virtual void visit_after() {
_assert_(true);
}
};
/**
* Interface to trigger update operations.
*/
class UpdateTrigger {
public:
/**
* Destructor.
*/
virtual ~UpdateTrigger() {
_assert_(true);
}
/**
* Trigger an update operation.
* @param mbuf the pointer to the message region.
* @param msiz the size of the message region.
*/
virtual void trigger(const char* mbuf, size_t msiz) = 0;
/**
* Begin transaction.
*/
virtual void begin_transaction() = 0;
/**
* End transaction.
* @param commit true to commit the transaction, or false to abort the transaction.
*/
virtual void end_transaction(bool commit) = 0;
};
/**
* Merge modes.
*/
enum MergeMode {
MSET, ///< overwrite the existing value
MADD, ///< keep the existing value
MREPLACE, ///< modify the existing record only
MAPPEND ///< append the new value
};
/**
* Default constructor.
*/
explicit TimedDB() :
xlock_(), db_(), mtrigger_(this), utrigger_(NULL), omode_(0),
opts_(0), capcnt_(0), capsiz_(0), xcur_(NULL), xsc_(0) {
_assert_(true);
db_.tune_meta_trigger(&mtrigger_);
}
/**
* Destructor.
*/
virtual ~TimedDB() {
_assert_(true);
if (omode_ != 0) close();
}
/**
* Set the internal database object.
* @param db the internal database object. Its possession is transferred inside and the
* object is deleted automatically.
* @return true on success, or false on failure.
*/
bool set_internal_db(kc::BasicDB* db) {
_assert_(db);
if (omode_ != 0) {
set_error(kc::BasicDB::Error::INVALID, "already opened");
return false;
}
db_.set_internal_db(db);
return true;
}
/**
* Get the last happened error.
* @return the last happened error.
*/
kc::BasicDB::Error error() const {
_assert_(true);
return db_.error();
}
/**
* Set the error information.
* @param code an error code.
* @param message a supplement message.
*/
void set_error(kc::BasicDB::Error::Code code, const char* message) {
_assert_(message);
db_.set_error(code, message);
}
/**
* Open a database file.
* @param path the path of a database file. The same as with kc::PolyDB. In addition, the
* following tuning parameters are supported. "ktopts" sets options and the value can contain
* "p" for the persistent option. "ktcapcnt" sets the capacity by record number. "ktcapsiz"
* sets the capacity by database size.
* @param mode the connection mode. The same as with kc::PolyDB.
* @return true on success, or false on failure.
*/
bool open(const std::string& path = ":",
uint32_t mode = kc::BasicDB::OWRITER | kc::BasicDB::OCREATE) {
_assert_(true);
if (omode_ != 0) {
set_error(kc::BasicDB::Error::INVALID, "already opened");
return false;
}
kc::ScopedSpinLock lock(&xlock_);
std::vector elems;
kc::strsplit(path, '#', &elems);
capcnt_ = -1;
capsiz_ = -1;
opts_ = 0;
std::vector::iterator it = elems.begin();
std::vector::iterator itend = elems.end();
if (it != itend) ++it;
while (it != itend) {
std::vector fields;
if (kc::strsplit(*it, '=', &fields) > 1) {
const char* key = fields[0].c_str();
const char* value = fields[1].c_str();
if (!std::strcmp(key, "ktcapcnt") || !std::strcmp(key, "ktcapcount") ||
!std::strcmp(key, "ktcap_count")) {
capcnt_ = kc::atoix(value);
} else if (!std::strcmp(key, "ktcapsiz") || !std::strcmp(key, "ktcapsize") ||
!std::strcmp(key, "ktcap_size")) {
capsiz_ = kc::atoix(value);
} else if (!std::strcmp(key, "ktopts") || !std::strcmp(key, "ktoptions")) {
if (std::strchr(value, 'p')) opts_ |= TPERSIST;
}
}
++it;
}
if (!db_.open(path, mode)) return false;
kc::BasicDB* idb = db_.reveal_inner_db();
if (idb) {
const std::type_info& info = typeid(*idb);
if (info == typeid(kc::HashDB)) {
kc::HashDB* hdb = (kc::HashDB*)idb;
char* opq = hdb->opaque();
if (opq) {
if (*(uint8_t*)opq == MAGICDATA) {
opts_ = *(uint8_t*)(opq + 1);
} else if ((mode & kc::BasicDB::OWRITER) && hdb->count() < 1) {
*(uint8_t*)opq = MAGICDATA;
*(uint8_t*)(opq + 1) = opts_;
hdb->synchronize_opaque();
}
}
} else if (info == typeid(kc::TreeDB)) {
kc::TreeDB* tdb = (kc::TreeDB*)idb;
char* opq = tdb->opaque();
if (opq) {
if (*(uint8_t*)opq == MAGICDATA) {
opts_ = *(uint8_t*)(opq + 1);
} else if ((mode & kc::BasicDB::OWRITER) && tdb->count() < 1) {
*(uint8_t*)opq = MAGICDATA;
*(uint8_t*)(opq + 1) = opts_;
tdb->synchronize_opaque();
}
}
} else if (info == typeid(kc::DirDB)) {
kc::DirDB* ddb = (kc::DirDB*)idb;
char* opq = ddb->opaque();
if (opq) {
if (*(uint8_t*)opq == MAGICDATA) {
opts_ = *(uint8_t*)(opq + 1);
} else if ((mode & kc::BasicDB::OWRITER) && ddb->count() < 1) {
*(uint8_t*)opq = MAGICDATA;
*(uint8_t*)(opq + 1) = opts_;
ddb->synchronize_opaque();
}
}
} else if (info == typeid(kc::ForestDB)) {
kc::ForestDB* fdb = (kc::ForestDB*)idb;
char* opq = fdb->opaque();
if (opq) {
if (*(uint8_t*)opq == MAGICDATA) {
opts_ = *(uint8_t*)(opq + 1);
} else if ((mode & kc::BasicDB::OWRITER) && fdb->count() < 1) {
*(uint8_t*)opq = MAGICDATA;
*(uint8_t*)(opq + 1) = opts_;
fdb->synchronize_opaque();
}
}
}
}
omode_ = mode;
if ((omode_ & kc::BasicDB::OWRITER) && !(opts_ & TPERSIST)) {
xcur_ = db_.cursor();
if (db_.count() > 0) xcur_->jump();
}
xsc_ = 0;
return true;
}
/**
* Close the database file.
* @return true on success, or false on failure.
*/
bool close() {
_assert_(true);
if (omode_ == 0) {
set_error(kc::BasicDB::Error::INVALID, "not opened");
return false;
}
kc::ScopedSpinLock lock(&xlock_);
bool err = false;
delete xcur_;
xcur_ = NULL;
if (!db_.close()) err = true;
omode_ = 0;
return !err;
}
/**
* Accept a visitor to a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @return true on success, or false on failure.
* @note the operation for each record is performed atomically and other threads accessing the
* same record are blocked.
*/
bool accept(const char* kbuf, size_t ksiz, Visitor* visitor, bool writable = true) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && visitor);
bool err = false;
int64_t ct = std::time(NULL);
TimedVisitor myvisitor(this, visitor, ct, false);
if (!db_.accept(kbuf, ksiz, &myvisitor, writable)) err = true;
if (xcur_) {
int64_t xtsc = writable ? XTSCUNIT : XTSCUNIT / XTREADFREQ;
if (!expire_records(xtsc)) err = true;
}
return !err;
}
/**
* Accept a visitor to multiple records at once.
* @param keys specifies a string vector of the keys.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @return true on success, or false on failure.
* @note The operations for specified records are performed atomically and other threads
* accessing the same records are blocked. To avoid deadlock, any database operation must not
* be performed in this function.
*/
bool accept_bulk(const std::vector& keys, Visitor* visitor,
bool writable = true) {
_assert_(visitor);
bool err = false;
int64_t ct = std::time(NULL);
TimedVisitor myvisitor(this, visitor, ct, false);
if (!db_.accept_bulk(keys, &myvisitor, writable)) err = true;
if (xcur_) {
int64_t xtsc = writable ? XTSCUNIT : XTSCUNIT / XTREADFREQ;
if (!expire_records(xtsc)) err = true;
}
return !err;
}
/**
* Iterate to accept a visitor for each record.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
* @note The whole iteration is performed atomically and other threads are blocked.
*/
bool iterate(Visitor *visitor, bool writable = true,
kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(visitor);
bool err = false;
int64_t ct = std::time(NULL);
TimedVisitor myvisitor(this, visitor, ct, true);
if (!db_.iterate(&myvisitor, writable, checker)) err = true;
if (xcur_) {
int64_t count = db_.count();
int64_t xtsc = writable ? XTSCUNIT : XTSCUNIT / XTREADFREQ;
if (count > 0) xtsc *= count / XTITERFREQ;
if (!expire_records(xtsc)) err = true;
}
return !err;
}
/**
* Scan each record in parallel.
* @param visitor a visitor object.
* @param thnum the number of worker threads.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
* @note This function is for reading records and not for updating ones. The return value of
* the visitor is just ignored. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool scan_parallel(Visitor *visitor, size_t thnum,
kc::BasicDB::ProgressChecker* checker = NULL) {
bool err = false;
int64_t ct = std::time(NULL);
TimedVisitor myvisitor(this, visitor, ct, true);
if (!db_.scan_parallel(&myvisitor, thnum, checker)) err = true;
if (xcur_) {
int64_t count = db_.count();
int64_t xtsc = XTSCUNIT / XTREADFREQ;
if (count > 0) xtsc *= count / XTITERFREQ;
if (!expire_records(xtsc)) err = true;
}
return !err;
}
/**
* Synchronize updated contents with the file and the device.
* @param hard true for physical synchronization with the device, or false for logical
* synchronization with the file system.
* @param proc a postprocessor object. If it is NULL, no postprocessing is performed.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
* @note The operation of the postprocessor is performed atomically and other threads accessing
* the same record are blocked. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool synchronize(bool hard = false, kc::BasicDB::FileProcessor* proc = NULL,
kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(true);
return db_.synchronize(hard, proc, checker);
}
/**
* Occupy database by locking and do something meanwhile.
* @param writable true to use writer lock, or false to use reader lock.
* @param proc a processor object. If it is NULL, no processing is performed.
* @return true on success, or false on failure.
* @note The operation of the processor is performed atomically and other threads accessing
* the same record are blocked. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool occupy(bool writable = true, kc::BasicDB::FileProcessor* proc = NULL) {
_assert_(true);
return db_.occupy(writable, proc);
}
/**
* Create a copy of the database file.
* @param dest the path of the destination file.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool copy(const std::string& dest, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(true);
return db_.copy(dest, checker);
}
/**
* Begin transaction.
* @param hard true for physical synchronization with the device, or false for logical
* synchronization with the file system.
* @return true on success, or false on failure.
*/
bool begin_transaction(bool hard = false) {
_assert_(true);
return db_.begin_transaction(hard);
}
/**
* Try to begin transaction.
* @param hard true for physical synchronization with the device, or false for logical
* synchronization with the file system.
* @return true on success, or false on failure.
*/
bool begin_transaction_try(bool hard = false) {
_assert_(true);
return db_.begin_transaction_try(hard);
}
/**
* End transaction.
* @param commit true to commit the transaction, or false to abort the transaction.
* @return true on success, or false on failure.
*/
bool end_transaction(bool commit = true) {
_assert_(true);
return db_.end_transaction(commit);
}
/**
* Remove all records.
* @return true on success, or false on failure.
*/
bool clear() {
_assert_(true);
return db_.clear();
}
/**
* Get the number of records.
* @return the number of records, or -1 on failure.
*/
int64_t count() {
_assert_(true);
return db_.count();
}
/**
* Get the size of the database file.
* @return the size of the database file in bytes, or -1 on failure.
*/
int64_t size() {
_assert_(true);
return db_.size();
}
/**
* Get the path of the database file.
* @return the path of the database file, or an empty string on failure.
*/
std::string path() {
_assert_(true);
return db_.path();
}
/**
* Get the miscellaneous status information.
* @param strmap a string map to contain the result.
* @return true on success, or false on failure.
*/
bool status(std::map* strmap) {
_assert_(strmap);
if (!db_.status(strmap)) return false;
(*strmap)["ktopts"] = kc::strprintf("%u", opts_);
(*strmap)["ktcapcnt"] = kc::strprintf("%lld", (long long)capcnt_);
(*strmap)["ktcapsiz"] = kc::strprintf("%lld", (long long)capsiz_);
return true;
}
/**
* Set the value of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @return true on success, or false on failure.
* @note If no record corresponds to the key, a new record is created. If the corresponding
* record exists, the value is overwritten.
*/
bool set(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz,
int64_t xt = kc::INT64MAX) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && vbuf && vsiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(const char* vbuf, size_t vsiz, int64_t xt) :
vbuf_(vbuf), vsiz_(vsiz), xt_(xt) {}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
*sp = vsiz_;
*xtp = xt_;
return vbuf_;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
*sp = vsiz_;
*xtp = xt_;
return vbuf_;
}
const char* vbuf_;
size_t vsiz_;
int64_t xt_;
};
VisitorImpl visitor(vbuf, vsiz, xt);
if (!accept(kbuf, ksiz, &visitor, true)) return false;
return true;
}
/**
* Set the value of a record.
* @note Equal to the original DB::set method except that the parameters are std::string.
*/
bool set(const std::string& key, const std::string& value, int64_t xt = kc::INT64MAX) {
_assert_(true);
return set(key.c_str(), key.size(), value.c_str(), value.size(), xt);
}
/**
* Add a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @return true on success, or false on failure.
* @note If no record corresponds to the key, a new record is created. If the corresponding
* record exists, the record is not modified and false is returned.
*/
bool add(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz,
int64_t xt = kc::INT64MAX) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && vbuf && vsiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(const char* vbuf, size_t vsiz, int64_t xt) :
vbuf_(vbuf), vsiz_(vsiz), xt_(xt), ok_(false) {}
bool ok() const {
return ok_;
}
private:
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
ok_ = true;
*sp = vsiz_;
*xtp = xt_;
return vbuf_;
}
const char* vbuf_;
size_t vsiz_;
int64_t xt_;
bool ok_;
};
VisitorImpl visitor(vbuf, vsiz, xt);
if (!accept(kbuf, ksiz, &visitor, true)) return false;
if (!visitor.ok()) {
set_error(kc::BasicDB::Error::DUPREC, "record duplication");
return false;
}
return true;
}
/**
* Set the value of a record.
* @note Equal to the original DB::add method except that the parameters are std::string.
*/
bool add(const std::string& key, const std::string& value, int64_t xt = kc::INT64MAX) {
_assert_(true);
return add(key.c_str(), key.size(), value.c_str(), value.size(), xt);
}
/**
* Replace the value of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @return true on success, or false on failure.
* @note If no record corresponds to the key, no new record is created and false is returned.
* If the corresponding record exists, the value is modified.
*/
bool replace(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz,
int64_t xt = kc::INT64MAX) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && vbuf && vsiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(const char* vbuf, size_t vsiz, int64_t xt) :
vbuf_(vbuf), vsiz_(vsiz), xt_(xt), ok_(false) {}
bool ok() const {
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
ok_ = true;
*sp = vsiz_;
*xtp = xt_;
return vbuf_;
}
const char* vbuf_;
size_t vsiz_;
int64_t xt_;
bool ok_;
};
VisitorImpl visitor(vbuf, vsiz, xt);
if (!accept(kbuf, ksiz, &visitor, true)) return false;
if (!visitor.ok()) {
set_error(kc::BasicDB::Error::NOREC, "no record");
return false;
}
return true;
}
/**
* Replace the value of a record.
* @note Equal to the original DB::replace method except that the parameters are std::string.
*/
bool replace(const std::string& key, const std::string& value, int64_t xt = kc::INT64MAX) {
_assert_(true);
return replace(key.c_str(), key.size(), value.c_str(), value.size(), xt);
}
/**
* Append the value of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @return true on success, or false on failure.
* @note If no record corresponds to the key, a new record is created. If the corresponding
* record exists, the given value is appended at the end of the existing value.
*/
bool append(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz,
int64_t xt = kc::INT64MAX) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && vbuf && vsiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(const char* vbuf, size_t vsiz, int64_t xt) :
vbuf_(vbuf), vsiz_(vsiz), xt_(xt), nbuf_(NULL) {}
~VisitorImpl() {
if (nbuf_) delete[] nbuf_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
size_t nsiz = vsiz + vsiz_;
nbuf_ = new char[nsiz];
std::memcpy(nbuf_, vbuf, vsiz);
std::memcpy(nbuf_ + vsiz, vbuf_, vsiz_);
*sp = nsiz;
*xtp = xt_;
return nbuf_;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
*sp = vsiz_;
*xtp = xt_;
return vbuf_;
}
const char* vbuf_;
size_t vsiz_;
int64_t xt_;
char* nbuf_;
};
VisitorImpl visitor(vbuf, vsiz, xt);
if (!accept(kbuf, ksiz, &visitor, true)) return false;
return true;
}
/**
* Set the value of a record.
* @note Equal to the original DB::append method except that the parameters are std::string.
*/
bool append(const std::string& key, const std::string& value, int64_t xt = kc::INT64MAX) {
_assert_(true);
return append(key.c_str(), key.size(), value.c_str(), value.size(), xt);
}
/**
* Add a number to the numeric integer value of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param num the additional number.
* @param orig the origin number if no record corresponds to the key. If it is INT64MIN and
* no record corresponds, this function fails. If it is INT64MAX, the value is set as the
* additional number regardless of the current value.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @return the result value, or kyotocabinet::INT64MIN on failure.
* @note The value is serialized as an 8-byte binary integer in big-endian order, not a decimal
* string. If existing value is not 8-byte, this function fails.
*/
int64_t increment(const char* kbuf, size_t ksiz, int64_t num, int64_t orig = 0,
int64_t xt = kc::INT64MAX) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(int64_t num, int64_t orig, int64_t xt) :
num_(num), orig_(orig), xt_(xt), big_(0) {}
int64_t num() {
return num_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
if (vsiz != sizeof(num_)) {
num_ = kc::INT64MIN;
return NOP;
}
int64_t onum;
if (orig_ == kc::INT64MAX) {
onum = 0;
} else {
std::memcpy(&onum, vbuf, vsiz);
onum = kc::ntoh64(onum);
if (num_ == 0) {
num_ = onum;
return NOP;
}
}
num_ += onum;
big_ = kc::hton64(num_);
*sp = sizeof(big_);
*xtp = xt_;
return (const char*)&big_;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
if (orig_ == kc::INT64MIN) {
num_ = kc::INT64MIN;
return NOP;
}
if (orig_ != kc::INT64MAX) num_ += orig_;
big_ = kc::hton64(num_);
*sp = sizeof(big_);
*xtp = xt_;
return (const char*)&big_;
}
int64_t num_;
int64_t orig_;
int64_t xt_;
uint64_t big_;
};
VisitorImpl visitor(num, orig, xt);
if (!accept(kbuf, ksiz, &visitor, num != 0 || orig != kc::INT64MIN)) return kc::INT64MIN;
num = visitor.num();
if (num == kc::INT64MIN) {
set_error(kc::BasicDB::Error::LOGIC, "logical inconsistency");
return num;
}
return num;
}
/**
* Add a number to the numeric integer value of a record.
* @note Equal to the original DB::increment method except that the parameter is std::string.
*/
int64_t increment(const std::string& key, int64_t num, int64_t orig = 0,
int64_t xt = kc::INT64MAX) {
_assert_(true);
return increment(key.c_str(), key.size(), num, orig, xt);
}
/**
* Add a number to the numeric double value of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param num the additional number.
* @param orig the origin number if no record corresponds to the key. If it is negative
* infinity and no record corresponds, this function fails. If it is positive infinity, the
* value is set as the additional number regardless of the current value.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @return the result value, or Not-a-number on failure.
* @note The value is serialized as an 16-byte binary fixed-point number in big-endian order,
* not a decimal string. If existing value is not 16-byte, this function fails.
*/
double increment_double(const char* kbuf, size_t ksiz, double num, double orig = 0,
int64_t xt = kc::INT64MAX) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(double num, double orig, int64_t xt) :
DECUNIT(1000000000000000LL), num_(num), orig_(orig), xt_(xt), buf_() {}
double num() {
return num_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
if (vsiz != sizeof(buf_)) {
num_ = kc::nan();
return NOP;
}
int64_t linteg, lfract;
if (kc::chkinf(orig_) && orig_ >= 0) {
linteg = 0;
lfract = 0;
} else {
std::memcpy(&linteg, vbuf, sizeof(linteg));
linteg = kc::ntoh64(linteg);
std::memcpy(&lfract, vbuf + sizeof(linteg), sizeof(lfract));
lfract = kc::ntoh64(lfract);
}
if (lfract == kc::INT64MIN && linteg == kc::INT64MIN) {
num_ = kc::nan();
return NOP;
} else if (linteg == kc::INT64MAX) {
num_ = HUGE_VAL;
return NOP;
} else if (linteg == kc::INT64MIN) {
num_ = -HUGE_VAL;
return NOP;
}
if (num_ == 0.0 && !(kc::chkinf(orig_) && orig_ >= 0)) {
num_ = linteg + (double)lfract / DECUNIT;
return NOP;
}
long double dinteg;
long double dfract = std::modfl(num_, &dinteg);
if (kc::chknan(dinteg)) {
linteg = kc::INT64MIN;
lfract = kc::INT64MIN;
num_ = kc::nan();
} else if (kc::chkinf(dinteg)) {
linteg = dinteg > 0 ? kc::INT64MAX : kc::INT64MIN;
lfract = 0;
num_ = dinteg;
} else {
linteg += (int64_t)dinteg;
lfract += (int64_t)(dfract * DECUNIT);
if (lfract >= DECUNIT) {
linteg += 1;
lfract -= DECUNIT;
}
num_ = linteg + (double)lfract / DECUNIT;
}
linteg = kc::hton64(linteg);
std::memcpy(buf_, &linteg, sizeof(linteg));
lfract = kc::hton64(lfract);
std::memcpy(buf_ + sizeof(linteg), &lfract, sizeof(lfract));
*sp = sizeof(buf_);
*xtp = xt_;
return buf_;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
if (kc::chknan(orig_) || (kc::chkinf(orig_) && orig_ < 0)) {
num_ = kc::nan();
return NOP;
}
if (!kc::chkinf(orig_)) num_ += orig_;
long double dinteg;
long double dfract = std::modfl(num_, &dinteg);
int64_t linteg, lfract;
if (kc::chknan(dinteg)) {
linteg = kc::INT64MIN;
lfract = kc::INT64MIN;
} else if (kc::chkinf(dinteg)) {
linteg = dinteg > 0 ? kc::INT64MAX : kc::INT64MIN;
lfract = 0;
} else {
linteg = (int64_t)dinteg;
lfract = (int64_t)(dfract * DECUNIT);
}
linteg = kc::hton64(linteg);
std::memcpy(buf_, &linteg, sizeof(linteg));
lfract = kc::hton64(lfract);
std::memcpy(buf_ + sizeof(linteg), &lfract, sizeof(lfract));
*sp = sizeof(buf_);
*xtp = xt_;
return buf_;
}
const int64_t DECUNIT;
double num_;
double orig_;
int64_t xt_;
char buf_[sizeof(int64_t)*2];
};
VisitorImpl visitor(num, orig, xt);
if (!accept(kbuf, ksiz, &visitor, true)) return kc::nan();
num = visitor.num();
if (kc::chknan(num)) {
set_error(kc::BasicDB::Error::LOGIC, "logical inconsistency");
return kc::nan();
}
return num;
}
/**
* Add a number to the numeric double value of a record.
* @note Equal to the original DB::increment_double method except that the parameter is
* std::string.
*/
double increment_double(const std::string& key, double num, double orig = 0,
int64_t xt = kc::INT64MAX) {
_assert_(true);
return increment_double(key.c_str(), key.size(), num, orig, xt);
}
/**
* Perform compare-and-swap.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param ovbuf the pointer to the old value region. NULL means that no record corresponds.
* @param ovsiz the size of the old value region.
* @param nvbuf the pointer to the new value region. NULL means that the record is removed.
* @param nvsiz the size of new old value region.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @return true on success, or false on failure.
*/
bool cas(const char* kbuf, size_t ksiz,
const char* ovbuf, size_t ovsiz, const char* nvbuf, size_t nvsiz,
int64_t xt = kc::INT64MAX) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(const char* ovbuf, size_t ovsiz, const char* nvbuf, size_t nvsiz,
int64_t xt) :
ovbuf_(ovbuf), ovsiz_(ovsiz), nvbuf_(nvbuf), nvsiz_(nvsiz), xt_(xt), ok_(false) {}
bool ok() const {
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
if (!ovbuf_ || vsiz != ovsiz_ || std::memcmp(vbuf, ovbuf_, vsiz)) return NOP;
ok_ = true;
if (!nvbuf_) return REMOVE;
*sp = nvsiz_;
*xtp = xt_;
return nvbuf_;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
if (ovbuf_) return NOP;
ok_ = true;
if (!nvbuf_) return NOP;
*sp = nvsiz_;
*xtp = xt_;
return nvbuf_;
}
const char* ovbuf_;
size_t ovsiz_;
const char* nvbuf_;
size_t nvsiz_;
int64_t xt_;
bool ok_;
};
VisitorImpl visitor(ovbuf, ovsiz, nvbuf, nvsiz, xt);
if (!accept(kbuf, ksiz, &visitor, true)) return false;
if (!visitor.ok()) {
set_error(kc::BasicDB::Error::LOGIC, "status conflict");
return false;
}
return true;
}
/**
* Perform compare-and-swap.
* @note Equal to the original DB::cas method except that the parameters are std::string.
*/
bool cas(const std::string& key,
const std::string& ovalue, const std::string& nvalue, int64_t xt = kc::INT64MAX) {
_assert_(true);
return cas(key.c_str(), key.size(),
ovalue.c_str(), ovalue.size(), nvalue.c_str(), nvalue.size(), xt);
}
/**
* Remove a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @return true on success, or false on failure.
* @note If no record corresponds to the key, false is returned.
*/
bool remove(const char* kbuf, size_t ksiz) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : ok_(false) {}
bool ok() const {
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
ok_ = true;
return REMOVE;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
return REMOVE;
}
bool ok_;
};
VisitorImpl visitor;
if (!accept(kbuf, ksiz, &visitor, true)) return false;
if (!visitor.ok()) {
set_error(kc::BasicDB::Error::NOREC, "no record");
return false;
}
return true;
}
/**
* Remove a record.
* @note Equal to the original DB::remove method except that the parameter is std::string.
*/
bool remove(const std::string& key) {
_assert_(true);
return remove(key.c_str(), key.size());
}
/**
* Retrieve the value of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param xtp the pointer to the variable into which the absolute expiration time is assigned.
* If it is NULL, it is ignored.
* @return the pointer to the value region of the corresponding record, or NULL on failure.
* @note If no record corresponds to the key, NULL is returned. Because an additional zero
* code is appended at the end of the region of the return value, the return value can be
* treated as a C-style string. Because the region of the return value is allocated with the
* the new[] operator, it should be released with the delete[] operator when it is no longer
* in use.
*/
char* get(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp = NULL) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && sp);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : vbuf_(NULL), vsiz_(0), xt_(0) {}
char* pop(size_t* sp, int64_t* xtp) {
*sp = vsiz_;
if (xtp) *xtp = xt_;
return vbuf_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
vbuf_ = new char[vsiz+1];
std::memcpy(vbuf_, vbuf, vsiz);
vbuf_[vsiz] = '\0';
vsiz_ = vsiz;
xt_ = *xtp;
return NOP;
}
char* vbuf_;
size_t vsiz_;
int64_t xt_;
};
VisitorImpl visitor;
if (!accept(kbuf, ksiz, &visitor, false)) {
*sp = 0;
if (xtp) *xtp = 0;
return NULL;
}
size_t vsiz;
char* vbuf = visitor.pop(&vsiz, xtp);
if (!vbuf) {
set_error(kc::BasicDB::Error::NOREC, "no record");
*sp = 0;
if (xtp) *xtp = 0;
return NULL;
}
*sp = vsiz;
return vbuf;
}
/**
* Retrieve the value of a record.
* @note Equal to the original DB::get method except that the first parameters is the key
* string and the second parameter is a string to contain the result and the return value is
* bool for success.
*/
bool get(const std::string& key, std::string* value, int64_t* xtp = NULL) {
_assert_(value);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(std::string* value) : value_(value), ok_(false), xt_(0) {}
bool ok(int64_t* xtp) {
if (xtp) *xtp = xt_;
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
value_->clear();
value_->append(vbuf, vsiz);
ok_ = true;
xt_ = *xtp;
return NOP;
}
std::string* value_;
bool ok_;
int64_t xt_;
};
VisitorImpl visitor(value);
if (!accept(key.data(), key.size(), &visitor, false)) {
if (xtp) *xtp = 0;
return false;
}
if (!visitor.ok(xtp)) {
set_error(kc::BasicDB::Error::NOREC, "no record");
return false;
}
return true;
}
/**
* Retrieve the value of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the buffer into which the value of the corresponding record is
* written.
* @param max the size of the buffer.
* @param xtp the pointer to the variable into which the expiration time from now in seconds
* is assigned. If it is NULL, it is ignored.
* @return the size of the value, or -1 on failure.
*/
int32_t get(const char* kbuf, size_t ksiz, char* vbuf, size_t max, int64_t* xtp = NULL) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && vbuf);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(char* vbuf, size_t max) :
vbuf_(vbuf), max_(max), vsiz_(-1), xt_(0) {}
int32_t vsiz(int64_t* xtp) {
if (xtp) *xtp = xt_;
return vsiz_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
vsiz_ = vsiz;
xt_ = *xtp;
size_t max = vsiz < max_ ? vsiz : max_;
std::memcpy(vbuf_, vbuf, max);
return NOP;
}
char* vbuf_;
size_t max_;
int32_t vsiz_;
int64_t xt_;
};
VisitorImpl visitor(vbuf, max);
if (!accept(kbuf, ksiz, &visitor, false)) return -1;
int32_t vsiz = visitor.vsiz(xtp);
if (vsiz < 0) {
set_error(kc::BasicDB::Error::NOREC, "no record");
return -1;
}
return vsiz;
}
/**
* Check the existence of a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param xtp the pointer to the variable into which the absolute expiration time is assigned.
* If it is NULL, it is ignored.
* @return the size of the value, or -1 on failure.
*/
int32_t check(const char* kbuf, size_t ksiz, int64_t* xtp = NULL) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : vsiz_(-1), xt_(0) {}
int32_t vsiz(int64_t* xtp) {
if (xtp) *xtp = xt_;
return vsiz_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
vsiz_ = vsiz;
xt_ = *xtp;
return NOP;
}
char* vbuf_;
int32_t vsiz_;
int64_t xt_;
};
VisitorImpl visitor;
if (!accept(kbuf, ksiz, &visitor, false)) {
if (xtp) *xtp = 0;
return -1;
}
int32_t vsiz = visitor.vsiz(xtp);
if (vsiz < 0) {
set_error(kc::BasicDB::Error::NOREC, "no record");
if (xtp) *xtp = 0;
return -1;
}
return vsiz;
}
/**
* Check the existence of a record.
* @note Equal to the original DB::check method except that the first parameters is the key
* string.
*/
int32_t check(const std::string& key, int64_t* xtp = NULL) {
return check(key.data(), key.size(), xtp);
}
/**
* Retrieve the value of a record and remove it atomically.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @param xtp the pointer to the variable into which the absolute expiration time is assigned.
* If it is NULL, it is ignored.
* @return the pointer to the value region of the corresponding record, or NULL on failure.
* @note If no record corresponds to the key, NULL is returned. Because an additional zero
* code is appended at the end of the region of the return value, the return value can be
* treated as a C-style string. Because the region of the return value is allocated with the
* the new[] operator, it should be released with the delete[] operator when it is no longer
* in use.
*/
char* seize(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp = NULL) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && sp);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : vbuf_(NULL), vsiz_(0), xt_(0) {}
char* pop(size_t* sp, int64_t* xtp) {
*sp = vsiz_;
if (xtp) *xtp = xt_;
return vbuf_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
vbuf_ = new char[vsiz+1];
std::memcpy(vbuf_, vbuf, vsiz);
vbuf_[vsiz] = '\0';
vsiz_ = vsiz;
xt_ = *xtp;
return REMOVE;
}
char* vbuf_;
size_t vsiz_;
int64_t xt_;
};
VisitorImpl visitor;
if (!accept(kbuf, ksiz, &visitor, true)) {
*sp = 0;
if (xtp) *xtp = 0;
return NULL;
}
size_t vsiz;
char* vbuf = visitor.pop(&vsiz, xtp);
if (!vbuf) {
set_error(kc::BasicDB::Error::NOREC, "no record");
*sp = 0;
if (xtp) *xtp = 0;
return NULL;
}
*sp = vsiz;
return vbuf;
}
/**
* Retrieve the value of a record and remove it atomically.
* @note Equal to the original DB::get method except that the first parameters is the key
* string and the second parameter is a string to contain the result and the return value is
* bool for success.
*/
bool seize(const std::string& key, std::string* value, int64_t* xtp = NULL) {
_assert_(value);
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(std::string* value) : value_(value), ok_(false), xt_(0) {}
bool ok(int64_t* xtp) {
if (xtp) *xtp = xt_;
return ok_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
value_->clear();
value_->append(vbuf, vsiz);
ok_ = true;
xt_ = *xtp;
return REMOVE;
}
std::string* value_;
bool ok_;
int64_t xt_;
};
VisitorImpl visitor(value);
if (!accept(key.data(), key.size(), &visitor, true)) {
if (xtp) *xtp = 0;
return false;
}
if (!visitor.ok(xtp)) {
set_error(kc::BasicDB::Error::NOREC, "no record");
return false;
}
return true;
}
/**
* Store records at once.
* @param recs the records to store.
* @param xt the expiration time from now in seconds. If it is negative, the absolute value
* is treated as the epoch time.
* @param atomic true to perform all operations atomically, or false for non-atomic operations.
* @return the number of stored records, or -1 on failure.
*/
int64_t set_bulk(const std::map& recs,
int64_t xt = kc::INT64MAX, bool atomic = true) {
_assert_(true);
if (atomic) {
std::vector keys;
keys.reserve(recs.size());
std::map::const_iterator rit = recs.begin();
std::map::const_iterator ritend = recs.end();
while (rit != ritend) {
keys.push_back(rit->first);
++rit;
}
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(const std::map& recs, int64_t xt) :
recs_(recs), xt_(xt) {}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
std::map::const_iterator rit =
recs_.find(std::string(kbuf, ksiz));
if (rit == recs_.end()) return NOP;
*sp = rit->second.size();
*xtp = xt_;
return rit->second.data();
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
std::map::const_iterator rit =
recs_.find(std::string(kbuf, ksiz));
if (rit == recs_.end()) return NOP;
*sp = rit->second.size();
*xtp = xt_;
return rit->second.data();
}
const std::map& recs_;
int64_t xt_;
};
VisitorImpl visitor(recs, xt);
if (!accept_bulk(keys, &visitor, true)) return -1;
return keys.size();
}
std::map::const_iterator rit = recs.begin();
std::map::const_iterator ritend = recs.end();
while (rit != ritend) {
if (!set(rit->first.data(), rit->first.size(), rit->second.data(), rit->second.size(), xt))
return -1;
++rit;
}
return recs.size();
}
/**
* Remove records at once.
* @param keys the keys of the records to remove.
* @param atomic true to perform all operations atomically, or false for non-atomic operations.
* @return the number of removed records, or -1 on failure.
*/
int64_t remove_bulk(const std::vector& keys, bool atomic = true) {
_assert_(true);
if (atomic) {
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl() : cnt_(0) {}
int64_t cnt() const {
return cnt_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
cnt_++;
return REMOVE;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp, int64_t* xtp) {
return REMOVE;
}
int64_t cnt_;
};
VisitorImpl visitor;
if (!accept_bulk(keys, &visitor, true)) return -1;
return visitor.cnt();
}
int64_t cnt = 0;
std::vector::const_iterator kit = keys.begin();
std::vector::const_iterator kitend = keys.end();
while (kit != kitend) {
if (remove(kit->data(), kit->size())) {
cnt++;
} else if (error() != kc::BasicDB::Error::NOREC) {
return -1;
}
++kit;
}
return cnt;
}
/**
* Retrieve records at once.
* @param keys the keys of the records to retrieve.
* @param recs a string map to contain the retrieved records.
* @param atomic true to perform all operations atomically, or false for non-atomic operations.
* @return the number of retrieved records, or -1 on failure.
*/
int64_t get_bulk(const std::vector& keys,
std::map* recs, bool atomic = true) {
_assert_(recs);
if (atomic) {
class VisitorImpl : public Visitor {
public:
explicit VisitorImpl(std::map* recs) : recs_(recs) {}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
(*recs_)[std::string(kbuf, ksiz)] = std::string(vbuf, vsiz);
return NOP;
}
std::map* recs_;
};
VisitorImpl visitor(recs);
if (!accept_bulk(keys, &visitor, false)) return -1;
return recs->size();
}
std::vector::const_iterator kit = keys.begin();
std::vector::const_iterator kitend = keys.end();
while (kit != kitend) {
size_t vsiz;
const char* vbuf = get(kit->data(), kit->size(), &vsiz);
if (vbuf) {
(*recs)[*kit] = std::string(vbuf, vsiz);
delete[] vbuf;
} else if (error() != kc::BasicDB::Error::NOREC) {
return -1;
}
++kit;
}
return recs->size();
}
/**
* Dump records into a data stream.
* @param dest the destination stream.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool dump_snapshot(std::ostream* dest, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(dest);
return db_.dump_snapshot(dest, checker);
}
/**
* Dump records into a file.
* @param dest the path of the destination file.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool dump_snapshot(const std::string& dest, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(true);
return db_.dump_snapshot(dest, checker);
}
/**
* Load records from a data stream.
* @param src the source stream.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool load_snapshot(std::istream* src, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(src);
return db_.load_snapshot(src, checker);
}
/**
* Load records from a file.
* @param src the path of the source file.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool load_snapshot(const std::string& src, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(true);
return db_.load_snapshot(src, checker);
}
/**
* Dump records atomically into a file.
* @param dest the path of the destination file.
* @param zcomp the data compressor object. If it is NULL, no compression is performed.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool dump_snapshot_atomic(const std::string& dest, kc::Compressor* zcomp = NULL,
kc::BasicDB::ProgressChecker* checker = NULL);
/**
* Load records atomically from a file.
* @param src the path of the source file.
* @param zcomp the data compressor object. If it is NULL, no decompression is performed.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool load_snapshot_atomic(const std::string& src, kc::Compressor* zcomp = NULL,
kc::BasicDB::ProgressChecker* checker = NULL);
/**
* Reveal the inner database object.
* @return the inner database object, or NULL on failure.
*/
kc::BasicDB* reveal_inner_db() {
_assert_(true);
return db_.reveal_inner_db();
}
/**
* Scan the database and eliminate regions of expired records.
* @param step the number of steps. If it is not more than 0, the whole region is scanned.
* @return true on success, or false on failure.
*/
bool vacuum(int64_t step = 0) {
_assert_(true);
bool err = false;
if (xcur_) {
if (step > 1) {
if (step > kc::INT64MAX / XTSCUNIT) step = kc::INT64MAX / XTSCUNIT;
if (!expire_records(step * XTSCUNIT)) err = true;
} else {
xcur_->jump();
xsc_ = 0;
if (!expire_records(kc::INT64MAX)) err = true;
xsc_ = 0;
}
}
if (!defrag(step)) err = true;
return !err;
}
/**
* Recover the database with an update log message.
* @param mbuf the pointer to the message region.
* @param msiz the size of the message region.
* @return true on success, or false on failure.
*/
bool recover(const char* mbuf, size_t msiz) {
_assert_(mbuf && msiz <= kc::MEMMAXSIZ);
bool err = false;
if (msiz < 1) {
set_error(kc::BasicDB::Error::INVALID, "invalid message format");
return false;
}
const char* rp = mbuf;
uint8_t op = *(uint8_t*)(rp++);
msiz--;
switch (op) {
case USET: {
if (msiz < 2) {
set_error(kc::BasicDB::Error::INVALID, "invalid message format");
return false;
}
uint64_t ksiz;
size_t step = kc::readvarnum(rp, msiz, &ksiz);
rp += step;
msiz -= step;
uint64_t vsiz;
step = kc::readvarnum(rp, msiz, &vsiz);
rp += step;
msiz -= step;
const char* kbuf = rp;
const char* vbuf = rp + ksiz;
if (msiz != ksiz + vsiz) {
set_error(kc::BasicDB::Error::INVALID, "invalid message format");
return false;
}
if (!db_.set(kbuf, ksiz, vbuf, vsiz)) err = true;
if (utrigger_) log_update(utrigger_, kbuf, ksiz, vbuf, vsiz);
break;
}
case UREMOVE: {
if (msiz < 1) {
set_error(kc::BasicDB::Error::INVALID, "invalid message format");
return false;
}
uint64_t ksiz;
size_t step = kc::readvarnum(rp, msiz, &ksiz);
rp += step;
msiz -= step;
const char* kbuf = rp;
if (msiz != ksiz) {
set_error(kc::BasicDB::Error::INVALID, "invalid message format");
return false;
}
if (!db_.remove(kbuf, ksiz) && db_.error() != kc::BasicDB::Error::NOREC) err = true;
if (utrigger_) log_update(utrigger_, kbuf, ksiz, TimedVisitor::REMOVE, 0);
break;
}
case UCLEAR: {
if (msiz != 0) {
set_error(kc::BasicDB::Error::INVALID, "invalid message format");
return false;
}
if (!db_.clear()) err = true;
break;
}
default: {
break;
}
}
if (xcur_ && !expire_records(XTSCUNIT)) err = true;
return !err;
}
/**
* Get keys matching a prefix string.
* @param prefix the prefix string.
* @param strvec a string vector to contain the result.
* @param max the maximum number to retrieve. If it is negative, no limit is specified.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return the number of retrieved keys or -1 on failure.
*/
int64_t match_prefix(const std::string& prefix, std::vector* strvec,
int64_t max = -1, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(strvec);
return db_.match_prefix(prefix, strvec, max, checker);
}
/**
* Get keys matching a regular expression string.
* @param regex the regular expression string.
* @param strvec a string vector to contain the result.
* @param max the maximum number to retrieve. If it is negative, no limit is specified.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return the number of retrieved keys or -1 on failure.
*/
int64_t match_regex(const std::string& regex, std::vector* strvec,
int64_t max = -1, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(strvec);
return db_.match_regex(regex, strvec, max, checker);
}
/**
* Get keys similar to a string in terms of the levenshtein distance.
* @param origin the origin string.
* @param range the maximum distance of keys to adopt.
* @param utf flag to treat keys as UTF-8 strings.
* @param strvec a string vector to contain the result.
* @param max the maximum number to retrieve. If it is negative, no limit is specified.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return the number of retrieved keys or -1 on failure.
*/
int64_t match_similar(const std::string& origin, size_t range, bool utf,
std::vector* strvec,
int64_t max = -1, kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(strvec);
return db_.match_similar(origin, range, utf, strvec, max, checker);
}
/**
* Merge records from other databases.
* @param srcary an array of the source detabase objects.
* @param srcnum the number of the elements of the source array.
* @param mode the merge mode. TimedDB::MSET to overwrite the existing value, TimedDB::MADD to
* keep the existing value, TimedDB::MREPLACE to modify the existing record only,
* TimedDB::MAPPEND to append the new value.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
*/
bool merge(TimedDB** srcary, size_t srcnum, MergeMode mode = MSET,
kc::BasicDB::ProgressChecker* checker = NULL) {
_assert_(srcary && srcnum <= kc::MEMMAXSIZ);
bool err = false;
kc::Comparator* comp = kc::LEXICALCOMP;
std::priority_queue lines;
int64_t allcnt = 0;
for (size_t i = 0; i < srcnum; i++) {
MergeLine line;
line.cur = srcary[i]->cursor();
line.comp = comp;
line.cur->jump();
line.kbuf = line.cur->get(&line.ksiz, &line.vbuf, &line.vsiz, &line.xt, true);
if (line.kbuf) {
lines.push(line);
int64_t count = srcary[i]->count();
if (count > 0) allcnt += count;
} else {
delete line.cur;
}
}
if (checker && !checker->check("merge", "beginning", 0, allcnt)) {
set_error(kc::BasicDB::Error::LOGIC, "checker failed");
err = true;
}
int64_t curcnt = 0;
while (!err && !lines.empty()) {
MergeLine line = lines.top();
lines.pop();
switch (mode) {
case MSET: {
if (!set(line.kbuf, line.ksiz, line.vbuf, line.vsiz, -line.xt)) err = true;
break;
}
case MADD: {
if (!add(line.kbuf, line.ksiz, line.vbuf, line.vsiz, -line.xt) &&
error() != kc::BasicDB::Error::DUPREC) err = true;
break;
}
case MREPLACE: {
if (!replace(line.kbuf, line.ksiz, line.vbuf, line.vsiz, -line.xt) &&
error() != kc::BasicDB::Error::NOREC) err = true;
break;
}
case MAPPEND: {
if (!append(line.kbuf, line.ksiz, line.vbuf, line.vsiz, -line.xt)) err = true;
break;
}
}
delete[] line.kbuf;
line.kbuf = line.cur->get(&line.ksiz, &line.vbuf, &line.vsiz, &line.xt, true);
if (line.kbuf) {
lines.push(line);
} else {
delete line.cur;
}
curcnt++;
if (checker && !checker->check("merge", "processing", curcnt, allcnt)) {
set_error(kc::BasicDB::Error::LOGIC, "checker failed");
err = true;
break;
}
}
if (checker && !checker->check("merge", "ending", -1, allcnt)) {
set_error(kc::BasicDB::Error::LOGIC, "checker failed");
err = true;
}
while (!lines.empty()) {
MergeLine line = lines.top();
lines.pop();
delete[] line.kbuf;
delete line.cur;
}
return !err;
}
/**
* Create a cursor object.
* @return the return value is the created cursor object.
* @note Because the object of the return value is allocated by the constructor, it should be
* released with the delete operator when it is no longer in use.
*/
Cursor* cursor() {
_assert_(true);
return new Cursor(this);
}
/**
* Set the internal logger.
* @param logger the logger object. The same as with kc::BasicDB.
* @param kinds kinds of logged messages by bitwise-or: The same as with kc::BasicDB.
* @return true on success, or false on failure.
*/
bool tune_logger(kc::BasicDB::Logger* logger,
uint32_t kinds = kc::BasicDB::Logger::WARN | kc::BasicDB::Logger::ERROR) {
_assert_(logger);
return db_.tune_logger(logger, kinds);
}
/**
* Set the internal update trigger.
* @param trigger the trigger object.
* @return true on success, or false on failure.
*/
bool tune_update_trigger(UpdateTrigger* trigger) {
_assert_(trigger);
utrigger_ = trigger;
return true;
}
/**
* Tokenize an update log message.
* @param mbuf the pointer to the message region.
* @param msiz the size of the message region.
* @param tokens a string vector to contain the result.
* @return true on success, or false on failure.
*/
static bool tokenize_update_log(const char* mbuf, size_t msiz,
std::vector* tokens) {
_assert_(mbuf && msiz <= kc::MEMMAXSIZ && tokens);
tokens->clear();
if (msiz < 1) return false;
const char* rp = mbuf;
uint8_t op = *(uint8_t*)(rp++);
msiz--;
switch (op) {
case USET: {
if (msiz < 2) return false;
uint64_t ksiz;
size_t step = kc::readvarnum(rp, msiz, &ksiz);
rp += step;
msiz -= step;
uint64_t vsiz;
step = kc::readvarnum(rp, msiz, &vsiz);
rp += step;
msiz -= step;
const char* kbuf = rp;
const char* vbuf = rp + ksiz;
if (msiz != ksiz + vsiz) return false;
tokens->push_back("set");
tokens->push_back(std::string(kbuf, ksiz));
tokens->push_back(std::string(vbuf, vsiz));
break;
}
case UREMOVE: {
if (msiz < 1) return false;
uint64_t ksiz;
size_t step = kc::readvarnum(rp, msiz, &ksiz);
rp += step;
msiz -= step;
const char* kbuf = rp;
if (msiz != ksiz) return false;
tokens->push_back("remove");
tokens->push_back(std::string(kbuf, ksiz));
break;
}
case UCLEAR: {
if (msiz != 0) return false;
tokens->push_back("clear");
break;
}
default: {
tokens->push_back("unknown");
tokens->push_back(std::string(mbuf, msiz));
break;
}
}
return true;
}
/**
* Get status of an atomic snapshot file.
* @param src the path of the source file.
* @param tsp the pointer to the variable into which the time stamp of the snapshot data is
* assigned. If it is NULL, it is ignored.
* @param cntp the pointer to the variable into which the number of records in the original
* database is assigned. If it is NULL, it is ignored.
* @param sizp the pointer to the variable into which the size of the original database is
* assigned. If it is NULL, it is ignored.
* @return true on success, or false on failure.
*/
static bool status_snapshot_atomic(const std::string& src, uint64_t* tsp = NULL,
int64_t* cntp = NULL, int64_t* sizp = NULL);
private:
/**
* Tuning Options.
*/
enum Option {
TPERSIST = 1 << 1 ///< disable expiration
};
/**
* Update Operations.
*/
enum UpdateOperation {
UNOP = 0xa0, ///< no operation
USET, ///< setting the value
UREMOVE, ///< removing the record
UOPEN, ///< opening
UCLOSE, ///< closing
UCLEAR, ///< clearing
UITERATE, ///< iteration
USYNCHRONIZE, ///< synchronization
UBEGINTRAN, ///< beginning transaction
UCOMMITTRAN, ///< committing transaction
UABORTTRAN, ///< aborting transaction
UUNKNOWN ///< unknown operation
};
/**
* Visitor to handle records with time stamps.
*/
class TimedVisitor : public kc::BasicDB::Visitor {
public:
TimedVisitor(TimedDB* db, TimedDB::Visitor* visitor, int64_t ct, bool isiter) :
db_(db), visitor_(visitor), ct_(ct), isiter_(isiter), jbuf_(NULL), again_(false) {
_assert_(db && visitor && ct >= 0);
}
~TimedVisitor() {
_assert_(true);
delete[] jbuf_;
}
bool again() {
_assert_(true);
return again_;
}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp) {
_assert_(kbuf && vbuf && sp);
if (db_->opts_ & TimedDB::TPERSIST) {
size_t rsiz;
int64_t xt = kc::INT64MAX;
const char* rbuf = visitor_->visit_full(kbuf, ksiz, vbuf, vsiz, &rsiz, &xt);
*sp = rsiz;
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, rbuf, rsiz);
return rbuf;
}
if (vsiz < (size_t)XTWIDTH) return NOP;
int64_t xt = kc::readfixnum(vbuf, XTWIDTH);
if (ct_ > xt) {
if (isiter_) {
again_ = true;
return NOP;
}
db_->set_error(kc::BasicDB::Error::NOREC, "no record (expired)");
size_t rsiz;
const char* rbuf = visitor_->visit_empty(kbuf, ksiz, &rsiz, &xt);
if (rbuf == TimedDB::Visitor::NOP) return NOP;
if (rbuf == TimedDB::Visitor::REMOVE) {
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, REMOVE, 0);
return REMOVE;
}
delete[] jbuf_;
xt = modify_exptime(xt, ct_);
size_t jsiz;
jbuf_ = make_record_value(rbuf, rsiz, xt, &jsiz);
*sp = jsiz;
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, jbuf_, jsiz);
return jbuf_;
}
vbuf += XTWIDTH;
vsiz -= XTWIDTH;
size_t rsiz;
const char* rbuf = visitor_->visit_full(kbuf, ksiz, vbuf, vsiz, &rsiz, &xt);
if (rbuf == TimedDB::Visitor::NOP) return NOP;
if (rbuf == TimedDB::Visitor::REMOVE) {
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, REMOVE, 0);
return REMOVE;
}
delete[] jbuf_;
xt = modify_exptime(xt, ct_);
size_t jsiz;
jbuf_ = make_record_value(rbuf, rsiz, xt, &jsiz);
*sp = jsiz;
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, jbuf_, jsiz);
return jbuf_;
}
const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp) {
if (db_->opts_ & TimedDB::TPERSIST) {
size_t rsiz;
int64_t xt = kc::INT64MAX;
const char* rbuf = visitor_->visit_empty(kbuf, ksiz, &rsiz, &xt);
*sp = rsiz;
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, rbuf, rsiz);
return rbuf;
}
size_t rsiz;
int64_t xt = -1;
const char* rbuf = visitor_->visit_empty(kbuf, ksiz, &rsiz, &xt);
if (rbuf == TimedDB::Visitor::NOP) return NOP;
if (rbuf == TimedDB::Visitor::REMOVE) {
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, REMOVE, 0);
return REMOVE;
}
delete[] jbuf_;
xt = modify_exptime(xt, ct_);
size_t jsiz;
jbuf_ = make_record_value(rbuf, rsiz, xt, &jsiz);
*sp = jsiz;
if (db_->utrigger_) log_update(db_->utrigger_, kbuf, ksiz, jbuf_, jsiz);
return jbuf_;
}
void visit_before() {
_assert_(true);
visitor_->visit_before();
}
void visit_after() {
_assert_(true);
visitor_->visit_after();
}
TimedDB* db_;
TimedDB::Visitor* visitor_;
int64_t ct_;
bool isiter_;
char* jbuf_;
bool again_;
};
/**
* Trigger of meta database operations.
*/
class TimedMetaTrigger : public kc::BasicDB::MetaTrigger {
public:
TimedMetaTrigger(TimedDB* db) : db_(db) {
_assert_(db);
}
private:
void trigger(Kind kind, const char* message) {
_assert_(message);
if (!db_->utrigger_) return;
switch (kind) {
case CLEAR: {
char mbuf[1];
*mbuf = UCLEAR;
db_->utrigger_->trigger(mbuf, 1);
break;
}
case BEGINTRAN: {
db_->utrigger_->begin_transaction();
break;
}
case COMMITTRAN: {
db_->utrigger_->end_transaction(true);
break;
}
case ABORTTRAN: {
db_->utrigger_->end_transaction(false);
break;
}
default: {
break;
}
}
}
TimedDB* db_;
};
/**
* Front line of a merging list.
*/
struct MergeLine {
TimedDB::Cursor* cur; ///< cursor
kc::Comparator* comp; ///< comparator
char* kbuf; ///< pointer to the key
size_t ksiz; ///< size of the key
const char* vbuf; ///< pointer to the value
size_t vsiz; ///< size of the value
int64_t xt; ///< expiration time
/** comparing operator */
bool operator <(const MergeLine& right) const {
return comp->compare(kbuf, ksiz, right.kbuf, right.ksiz) > 0;
}
};
/**
* Remove expired records.
* @param score the score of expiration.
* @return true on success, or false on failure.
*/
bool expire_records(int64_t score) {
_assert_(score >= 0);
xsc_ += score;
if (xsc_ < XTSCUNIT * XTUNIT) return true;
if (!xlock_.lock_try()) return true;
int64_t step = (int64_t)xsc_ / XTSCUNIT;
xsc_ -= step * XTSCUNIT;
int64_t ct = std::time(NULL);
class VisitorImpl : public kc::BasicDB::Visitor {
public:
VisitorImpl(int64_t ct) : ct_(ct) {}
private:
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp) {
if (vsiz < (size_t)XTWIDTH) return NOP;
int64_t xt = kc::readfixnum(vbuf, XTWIDTH);
if (ct_ <= xt) return NOP;
return REMOVE;
}
int64_t ct_;
};
VisitorImpl visitor(ct);
bool err = false;
for (int64_t i = 0; i < step; i++) {
if (!xcur_->accept(&visitor, true, true)) {
kc::BasicDB::Error::Code code = db_.error().code();
if (code == kc::BasicDB::Error::INVALID || code == kc::BasicDB::Error::NOREC) {
xcur_->jump();
} else {
err = true;
}
xsc_ = 0;
break;
}
}
if (capcnt_ > 0) {
int64_t count = db_.count();
while (count > capcnt_) {
if (!xcur_->remove()) {
kc::BasicDB::Error::Code code = db_.error().code();
if (code == kc::BasicDB::Error::INVALID || code == kc::BasicDB::Error::NOREC) {
xcur_->jump();
} else {
err = true;
}
break;
}
count--;
}
if (!defrag(step)) err = true;
}
if (capsiz_ > 0) {
int64_t size = db_.size();
if (size > capsiz_) {
for (int64_t i = 0; i < step; i++) {
if (!xcur_->remove()) {
kc::BasicDB::Error::Code code = db_.error().code();
if (code == kc::BasicDB::Error::INVALID || code == kc::BasicDB::Error::NOREC) {
xcur_->jump();
} else {
err = true;
}
break;
}
}
if (!defrag(step)) err = true;
}
}
xlock_.unlock();
return !err;
}
/**
* Perform defragmentation of the database file.
* @param step the number of steps. If it is not more than 0, the whole region is defraged.
* @return true on success, or false on failure.
*/
bool defrag(int step) {
_assert_(true);
bool err = false;
kc::BasicDB* idb = db_.reveal_inner_db();
if (idb) {
const std::type_info& info = typeid(*idb);
if (info == typeid(kc::HashDB)) {
kc::HashDB* hdb = (kc::HashDB*)idb;
if (!hdb->defrag(step)) err = true;
} else if (info == typeid(kc::TreeDB)) {
kc::TreeDB* tdb = (kc::TreeDB*)idb;
if (!tdb->defrag(step)) err = true;
}
}
return !err;
}
/**
* Make the record value with meta data.
* @param vbuf the buffer of the original record value.
* @param vsiz the size of the original record value.
* @param xt the expiration time.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @return the pointer to the result buffer.
*/
static char* make_record_value(const char* vbuf, size_t vsiz, int64_t xt, size_t* sp) {
_assert_(vbuf && vsiz <= kc::MEMMAXSIZ);
size_t jsiz = vsiz + XTWIDTH;
char* jbuf = new char[jsiz];
kc::writefixnum(jbuf, xt, XTWIDTH);
std::memcpy(jbuf + XTWIDTH, vbuf, vsiz);
*sp = jsiz;
return jbuf;
}
/**
* Modify an expiration time by the current time.
* @param xt the expiration time.
* @param ct the current time.
* @return the modified expiration time.
*/
static int64_t modify_exptime(int64_t xt, int64_t ct) {
_assert_(true);
if (xt < 0) {
if (xt < kc::INT64MIN / 2) xt = kc::INT64MIN / 2;
xt = -xt;
} else {
if (xt > kc::INT64MAX / 2) xt = kc::INT64MAX / 2;
xt += ct;
}
if (xt > XTMAX) xt = XTMAX;
return xt;
}
/**
* Log a record update operation.
* @param utrigger the update trigger.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
*/
static void log_update(UpdateTrigger* utrigger, const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz) {
_assert_(utrigger && kbuf);
if (vbuf == TimedVisitor::REMOVE) {
size_t msiz = 1 + sizeof(uint64_t) + ksiz;
char stack[LOGBUFSIZ];
char* mbuf = msiz > sizeof(stack) ? new char[msiz] : stack;
char* wp = mbuf;
*(wp++) = UREMOVE;
wp += kc::writevarnum(wp, ksiz);
std::memcpy(wp, kbuf, ksiz);
wp += ksiz;
utrigger->trigger(mbuf, wp - mbuf);
if (mbuf != stack) delete[] mbuf;
} else if (vbuf != TimedVisitor::NOP) {
size_t msiz = 1 + sizeof(uint64_t) * 2 + ksiz + vsiz;
char stack[LOGBUFSIZ];
char* mbuf = msiz > sizeof(stack) ? new char[msiz] : stack;
char* wp = mbuf;
*(wp++) = USET;
wp += kc::writevarnum(wp, ksiz);
wp += kc::writevarnum(wp, vsiz);
std::memcpy(wp, kbuf, ksiz);
wp += ksiz;
std::memcpy(wp, vbuf, vsiz);
wp += vsiz;
utrigger->trigger(mbuf, wp - mbuf);
if (mbuf != stack) delete[] mbuf;
}
}
/** Dummy constructor to forbid the use. */
TimedDB(const TimedDB&);
/** Dummy Operator to forbid the use. */
TimedDB& operator =(const TimedDB&);
/** The expiration cursor lock. */
kc::SpinLock xlock_;
/** The internal database. */
kc::PolyDB db_;
/** The internal meta trigger. */
TimedMetaTrigger mtrigger_;
/** The internal update trigger. */
UpdateTrigger* utrigger_;
/** The open mode. */
uint32_t omode_;
/** The options. */
uint8_t opts_;
/** The capacity of record number. */
int64_t capcnt_;
/** The capacity of memory usage. */
int64_t capsiz_;
/** The cursor for expiration. */
kc::PolyDB::Cursor* xcur_;
/** The score of expiration. */
kc::AtomicInt64 xsc_;
};
} // common namespace
#endif // duplication check
// END OF FILE
kyototycoon-0.9.56/COPYING 0000644 0001750 0001750 00000104513 11441176761 014265 0 ustar mikio mikio GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
kyototycoon-0.9.56/ktthserv.h 0000644 0001750 0001750 00000040076 11757471602 015262 0 ustar mikio mikio /*************************************************************************************************
* Threaded Server
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#ifndef _KTTHSERV_H // duplication check
#define _KTTHSERV_H
#include
#include
#include
namespace kyototycoon { // common namespace
/**
* Threaded TCP Server.
*/
class ThreadedServer {
public:
class Logger;
class Worker;
class Session;
private:
class TaskQueueImpl;
class SessionTask;
public:
/**
* Interface to log internal information and errors.
*/
class Logger {
public:
/**
* Event kinds.
*/
enum Kind {
DEBUG = 1 << 0, ///< normal information
INFO = 1 << 1, ///< normal information
SYSTEM = 1 << 2, ///< system information
ERROR = 1 << 3 ///< error
};
/**
* Destructor.
*/
virtual ~Logger() {
_assert_(true);
}
/**
* Process a log message.
* @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal
* information, Logger::SYSTEM for system information, and Logger::ERROR for fatal error.
* @param message the log message.
*/
virtual void log(Kind kind, const char* message) = 0;
};
/**
* Interface to process each request.
*/
class Worker {
public:
/**
* Destructor.
*/
virtual ~Worker() {
_assert_(true);
}
/**
* Process each request.
* @param serv the server.
* @param sess the session with the client.
* @return true to reuse the session, or false to close the session.
*/
virtual bool process(ThreadedServer* serv, Session* sess) = 0;
/**
* Process each idle event.
* @param serv the server.
*/
virtual void process_idle(ThreadedServer* serv) {
_assert_(serv);
}
/**
* Process each timer event.
* @param serv the server.
*/
virtual void process_timer(ThreadedServer* serv) {
_assert_(serv);
}
/**
* Process the starting event.
* @param serv the server.
*/
virtual void process_start(ThreadedServer* serv) {
_assert_(serv);
}
/**
* Process the finishing event.
* @param serv the server.
*/
virtual void process_finish(ThreadedServer* serv) {
_assert_(serv);
}
};
/**
* Interface to access each session data.
*/
class Session : public Socket {
friend class ThreadedServer;
public:
class Data;
public:
/**
* Interface of session local data.
*/
class Data {
public:
/**
* Destructor.
*/
virtual ~Data() {
_assert_(true);
}
};
/**
* Get the ID number of the session.
* @return the ID number of the session.
*/
uint64_t id() {
_assert_(true);
return id_;
}
/**
* Get the ID number of the worker thread.
* @return the ID number of the worker thread. It is from 0 to less than the number of
* worker threads.
*/
uint32_t thread_id() {
_assert_(true);
return thid_;
}
/**
* Set the session local data.
* @param data the session local data. If it is NULL, no data is registered.
* @note The registered data is destroyed implicitly when the session object is destroyed or
* this method is called again.
*/
void set_data(Data* data) {
_assert_(true);
delete data_;
data_ = data;
}
/**
* Get the session local data.
* @return the session local data, or NULL if no data is registered.
*/
Data* data() {
_assert_(true);
return data_;
}
private:
/**
* Default Constructor.
*/
explicit Session(uint64_t id) : id_(id), thid_(0), data_(NULL) {
_assert_(true);
}
/**
* Destructor.
*/
~Session() {
_assert_(true);
delete data_;
}
private:
/** The ID number of the session. */
uint64_t id_;
/** The ID number of the worker thread. */
uint32_t thid_;
/** The session local data. */
Data* data_;
};
/**
* Default constructor.
*/
explicit ThreadedServer() :
run_(false), expr_(), timeout_(0), logger_(NULL), logkinds_(0), worker_(NULL), thnum_(0),
sock_(), poll_(), queue_(this), sesscnt_(0), idlesem_(0), timersem_(0) {
_assert_(true);
}
/**
* Destructor.
*/
~ThreadedServer() {
_assert_(true);
}
/**
* Set the network configurations.
* @param expr an expression of the address and the port of the server.
* @param timeout the timeout of each network operation in seconds. If it is not more than 0,
* no timeout is specified.
*/
void set_network(const std::string& expr, double timeout = -1) {
expr_ = expr;
timeout_ = timeout;
}
/**
* Set the logger to process each log message.
* @param logger the logger object.
* @param kinds kinds of logged messages by bitwise-or: Logger::DEBUG for debugging,
* Logger::INFO for normal information, Logger::SYSTEM for system information, and
* Logger::ERROR for fatal error.
*/
void set_logger(Logger* logger, uint32_t kinds = Logger::SYSTEM | Logger::ERROR) {
_assert_(logger);
logger_ = logger;
logkinds_ = kinds;
}
/**
* Set the worker to process each request.
* @param worker the worker object.
* @param thnum the number of worker threads.
*/
void set_worker(Worker* worker, size_t thnum = 1) {
_assert_(worker && thnum > 0 && thnum < kc::MEMMAXSIZ);
worker_ = worker;
thnum_ = thnum;
}
/**
* Start the service.
* @return true on success, or false on failure.
* @note This function blocks until the server stops by the ThreadedServer::stop method.
*/
bool start() {
log(Logger::SYSTEM, "starting the server: expr=%s", expr_.c_str());
if (run_) {
log(Logger::ERROR, "alreadiy running");
return false;
}
if (expr_.empty()) {
log(Logger::ERROR, "the network configuration is not set");
return false;
}
if (!worker_) {
log(Logger::ERROR, "the worker is not set");
return false;
}
if (!sock_.open(expr_)) {
log(Logger::ERROR, "socket error: expr=%s msg=%s", expr_.c_str(), sock_.error());
return false;
}
log(Logger::SYSTEM, "server socket opened: expr=%s timeout=%.1f", expr_.c_str(), timeout_);
if (!poll_.open()) {
log(Logger::ERROR, "poller error: msg=%s", poll_.error());
sock_.close();
return false;
}
log(Logger::SYSTEM, "listening server socket started: fd=%d", sock_.descriptor());
bool err = false;
sock_.set_event_flags(Pollable::EVINPUT);
if (!poll_.deposit(&sock_)) {
log(Logger::ERROR, "poller error: msg=%s", poll_.error());
err = true;
}
queue_.set_worker(worker_);
queue_.start(thnum_);
uint32_t timercnt = 0;
run_ = true;
while (run_) {
if (poll_.wait(0.1)) {
Pollable* event;
while ((event = poll_.next()) != NULL) {
if (event == &sock_) {
Session* sess = new Session(++sesscnt_);
if (timeout_ > 0) sess->set_timeout(timeout_);
if (sock_.accept(sess)) {
log(Logger::INFO, "connected: expr=%s", sess->expression().c_str());
sess->set_event_flags(Pollable::EVINPUT);
if (!poll_.deposit(sess)) {
log(Logger::ERROR, "poller error: msg=%s", poll_.error());
err = true;
}
} else {
log(Logger::ERROR, "socket error: msg=%s", sock_.error());
err = true;
}
sock_.set_event_flags(Pollable::EVINPUT);
if (!poll_.undo(&sock_)) {
log(Logger::ERROR, "poller error: msg=%s", poll_.error());
err = true;
}
} else {
Session* sess = (Session*)event;
SessionTask* task = new SessionTask(sess);
queue_.add_task(task);
}
}
timercnt++;
} else {
if (queue_.count() < 1 && idlesem_.cas(0, 1)) {
SessionTask* task = new SessionTask(SESSIDLE);
queue_.add_task(task);
}
timercnt += kc::UINT8MAX / 4;
}
if (timercnt > kc::UINT8MAX && timersem_.cas(0, 1)) {
SessionTask* task = new SessionTask(SESSTIMER);
queue_.add_task(task);
timercnt = 0;
}
}
log(Logger::SYSTEM, "server stopped");
if (err) log(Logger::SYSTEM, "one or more errors were detected");
return !err;
}
/**
* Stop the service.
* @return true on success, or false on failure.
*/
bool stop() {
if (!run_) {
log(Logger::ERROR, "not running");
return false;
}
run_ = false;
sock_.abort();
poll_.abort();
return true;
}
/**
* Finish the service.
* @return true on success, or false on failure.
*/
bool finish() {
log(Logger::SYSTEM, "finishing the server");
if (run_) {
log(Logger::ERROR, "not stopped");
return false;
}
bool err = false;
queue_.finish();
if (queue_.error()) {
log(Logger::SYSTEM, "one or more errors were detected");
err = true;
}
if (poll_.flush()) {
Pollable* event;
while ((event = poll_.next()) != NULL) {
if (event == &sock_) continue;
Session* sess = (Session*)event;
log(Logger::INFO, "disconnecting: expr=%s", sess->expression().c_str());
if (!poll_.withdraw(sess)) {
log(Logger::ERROR, "poller error: msg=%s", poll_.error());
err = true;
}
if (!sess->close()) {
log(Logger::ERROR, "socket error: fd=%d msg=%s", sess->descriptor(), sess->error());
err = true;
}
delete sess;
}
} else {
log(Logger::ERROR, "poller error: msg=%s", poll_.error());
err = true;
}
if (!poll_.close()) {
log(Logger::ERROR, "poller error: msg=%s", poll_.error());
err = true;
}
log(Logger::SYSTEM, "closing the server socket");
if (!sock_.close()) {
log(Logger::ERROR, "socket error: fd=%d msg=%s", sock_.descriptor(), sock_.error());
err = true;
}
return !err;
}
/**
* Log a message.
* @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal
* information, Logger::SYSTEM for system information, and Logger::ERROR for fatal error.
* @param format the printf-like format string. The conversion character `%' can be used with
* such flag characters as `s', `d', `o', `u', `x', `X', `c', `e', `E', `f', `g', `G', and `%'.
* @param ... used according to the format string.
*/
void log(Logger::Kind kind, const char* format, ...) {
_assert_(format);
if (!logger_ || !(kind & logkinds_)) return;
std::string msg;
va_list ap;
va_start(ap, format);
kc::vstrprintf(&msg, format, ap);
va_end(ap);
logger_->log(kind, msg.c_str());
}
/**
* Log a message.
* @note Equal to the original Cursor::set_value method except that the last parameters is
* va_list.
*/
void log_v(Logger::Kind kind, const char* format, va_list ap) {
_assert_(format);
if (!logger_ || !(kind & logkinds_)) return;
std::string msg;
kc::vstrprintf(&msg, format, ap);
logger_->log(kind, msg.c_str());
}
/**
* Get the number of connections.
* @return the number of connections.
*/
int64_t connection_count() {
_assert_(true);
return poll_.count() - 1;
}
/**
* Get the number of tasks in the queue.
* @return the number of tasks in the queue.
*/
int64_t task_count() {
_assert_(true);
return queue_.count();
}
/**
* Check whether the thread is to be aborted.
* @return true if the thread is to be aborted, or false if not.
*/
bool aborted() {
_assert_(true);
return !run_;
}
private:
/** The magic pointer of an idle session. */
static Session* const SESSIDLE;
/** The magic pointer of a timer session. */
static Session* const SESSTIMER;
/**
* Task queue implementation.
*/
class TaskQueueImpl : public kc::TaskQueue {
public:
explicit TaskQueueImpl(ThreadedServer* serv) : serv_(serv), worker_(NULL), err_(false) {
_assert_(true);
}
void set_worker(Worker* worker) {
_assert_(worker);
worker_ = worker;
}
bool error() {
_assert_(true);
return err_;
}
private:
void do_task(kc::TaskQueue::Task* task) {
_assert_(task);
SessionTask* mytask = (SessionTask*)task;
Session* sess = mytask->sess_;
if (sess == SESSIDLE) {
worker_->process_idle(serv_);
serv_->idlesem_.set(0);
} else if (sess == SESSTIMER) {
worker_->process_timer(serv_);
serv_->timersem_.set(0);
} else {
bool keep = false;
if (mytask->aborted()) {
serv_->log(Logger::INFO, "aborted a request: expr=%s", sess->expression().c_str());
} else {
sess->thid_ = mytask->thread_id();
do {
keep = worker_->process(serv_, sess);
} while (keep && sess->left_size() > 0);
}
if (keep) {
sess->set_event_flags(Pollable::EVINPUT);
if (!serv_->poll_.undo(sess)) {
serv_->log(Logger::ERROR, "poller error: msg=%s", serv_->poll_.error());
err_ = true;
}
} else {
serv_->log(Logger::INFO, "disconnecting: expr=%s", sess->expression().c_str());
if (!serv_->poll_.withdraw(sess)) {
serv_->log(Logger::ERROR, "poller error: msg=%s", serv_->poll_.error());
err_ = true;
}
if (!sess->close()) {
serv_->log(Logger::ERROR, "socket error: msg=%s", sess->error());
err_ = true;
}
delete sess;
}
}
delete mytask;
}
void do_start(const kc::TaskQueue::Task* task) {
_assert_(task);
worker_->process_start(serv_);
}
void do_finish(const kc::TaskQueue::Task* task) {
_assert_(task);
worker_->process_finish(serv_);
}
ThreadedServer* serv_;
Worker* worker_;
bool err_;
};
/**
* Task with a session.
*/
class SessionTask : public kc::TaskQueue::Task {
friend class ThreadedServer;
public:
explicit SessionTask(Session* sess) : sess_(sess) {}
private:
Session* sess_;
};
/** Dummy constructor to forbid the use. */
ThreadedServer(const ThreadedServer&);
/** Dummy Operator to forbid the use. */
ThreadedServer& operator =(const ThreadedServer&);
/** The flag of running. */
bool run_;
/** The expression of the server socket. */
std::string expr_;
/** The timeout of each network operation. */
double timeout_;
/** The internal logger. */
Logger* logger_;
/** The kinds of logged messages. */
uint32_t logkinds_;
/** The worker operator. */
Worker* worker_;
/** The number of worker threads. */
size_t thnum_;
/** The server socket. */
ServerSocket sock_;
/** The event poller. */
Poller poll_;
/** The task queue. */
TaskQueueImpl queue_;
/** The session count. */
uint64_t sesscnt_;
/** The idle event semaphore. */
kc::AtomicInt64 idlesem_;
/** The timer event semaphore. */
kc::AtomicInt64 timersem_;
};
} // common namespace
#endif // duplication check
// END OF FILE
kyototycoon-0.9.56/ktrpc.h 0000644 0001750 0001750 00000047652 11757471602 014542 0 ustar mikio mikio /*************************************************************************************************
* RPC utilities
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#ifndef _KTRPC_H // duplication check
#define _KTRPC_H
#include
#include
#include
#include
#include
#define KTRPCPATHPREFIX "/rpc/" ///< prefix of the RPC entry
#define KTRPCFORMMTYPE "application/x-www-form-urlencoded" ///< MIME type of form data
#define KTRPCTSVMTYPE "text/tab-separated-values" ///< MIME type of TSV
#define KTRPCTSVMATTR "colenc" ///< encoding attribute of TSV
namespace kyototycoon { // common namespace
/**
* RPC client.
* @note Although all methods of this class are thread-safe, its instance does not have mutual
* exclusion mechanism. So, multiple threads must not share the same instance and they must use
* their own respective instances.
*/
class RPCClient {
public:
/**
* Return value.
*/
enum ReturnValue {
RVSUCCESS, ///< success
RVENOIMPL, ///< not implemented
RVEINVALID, ///< invalid operation
RVELOGIC, ///< logical inconsistency
RVETIMEOUT, ///< timeout
RVEINTERNAL, ///< internal error
RVENETWORK, ///< network error
RVEMISC = 15 ///< miscellaneous error
};
/**
* Default constructor.
*/
RPCClient() : ua_(), host_(), port_(0), timeout_(0), open_(false), alive_(false) {
_assert_(true);
}
/**
* Destructor.
*/
~RPCClient() {
_assert_(true);
if (open_) close();
}
/**
* Open the connection.
* @param host the name or the address of the server. If it is an empty string, the local host
* is specified.
* @param port the port numger of the server.
* @param timeout the timeout of each operation in seconds. If it is not more than 0, no
* timeout is specified.
* @return true on success, or false on failure.
*/
bool open(const std::string& host = "", int32_t port = DEFPORT, double timeout = -1) {
_assert_(true);
if (open_ || port < 1) return false;
if (!ua_.open(host, port, timeout)) return false;
host_ = host;
port_ = port;
timeout_ = timeout;
open_ = true;
alive_ = true;
return true;
}
/**
* Close the connection.
* @param grace true for graceful shutdown, or false for immediate disconnection.
* @return true on success, or false on failure.
*/
bool close(bool grace = true) {
_assert_(true);
if (!open_) return false;
bool err = false;
if (alive_ && !ua_.close(grace)) err = true;
return !err;
}
/**
* Call a remote procedure.
* @param name the name of the procecude.
* @param inmap a string map which contains the input of the procedure. If it is NULL, it is
* ignored.
* @param outmap a string map to contain the output parameters. If it is NULL, it is ignored.
* @return the return value of the procedure.
*/
ReturnValue call(const std::string& name,
const std::map* inmap = NULL,
std::map* outmap = NULL) {
_assert_(true);
if (outmap) outmap->clear();
if (!open_) return RVENETWORK;
if (!alive_ && !ua_.open(host_, port_, timeout_)) return RVENETWORK;
alive_ = true;
std::string pathquery = KTRPCPATHPREFIX;
char* zstr = kc::urlencode(name.data(), name.size());
pathquery.append(zstr);
delete[] zstr;
std::map reqheads;
std::string reqbody;
if (inmap) {
std::map tmap;
tmap.insert(inmap->begin(), inmap->end());
int32_t enc = checkmapenc(tmap);
std::string outtype = KTRPCTSVMTYPE;
switch (enc) {
case 'B': kc::strprintf(&outtype, "; %s=B", KTRPCTSVMATTR); break;
case 'Q': kc::strprintf(&outtype, "; %s=Q", KTRPCTSVMATTR); break;
case 'U': kc::strprintf(&outtype, "; %s=U", KTRPCTSVMATTR); break;
}
reqheads["content-type"] = outtype;
if (enc != 0) tsvmapencode(&tmap, enc);
maptotsv(tmap, &reqbody);
}
std::map resheads;
std::string resbody;
int32_t code = ua_.fetch(pathquery, HTTPClient::MPOST, &resbody, &resheads,
&reqbody, &reqheads);
if (outmap) {
const char* rp = strmapget(resheads, "content-type");
if (rp) {
if (kc::strifwm(rp, KTRPCFORMMTYPE)) {
wwwformtomap(resbody.c_str(), outmap);
} else if (kc::strifwm(rp, KTRPCTSVMTYPE)) {
rp += sizeof(KTRPCTSVMTYPE) - 1;
int32_t enc = 0;
while (*rp != '\0') {
while (*rp == ' ' || *rp == ';') {
rp++;
}
if (kc::strifwm(rp, KTRPCTSVMATTR) && rp[sizeof(KTRPCTSVMATTR)-1] == '=') {
rp += sizeof(KTRPCTSVMATTR);
if (*rp == '"') rp++;
switch (*rp) {
case 'b': case 'B': enc = 'B'; break;
case 'q': case 'Q': enc = 'Q'; break;
case 'u': case 'U': enc = 'U'; break;
}
}
while (*rp != '\0' && *rp != ' ' && *rp != ';') {
rp++;
}
}
tsvtomap(resbody, outmap);
if (enc != 0) tsvmapdecode(outmap, enc);
}
}
}
ReturnValue rv;
if (code < 1) {
rv = RVENETWORK;
ua_.close(false);
alive_ = false;
} else if (code >= 200 && code < 300) {
rv = RVSUCCESS;
} else if (code >= 400 && code < 500) {
if (code >= 450) {
rv = RVELOGIC;
} else {
rv = RVEINVALID;
}
} else if (code >= 500 && code < 600) {
if (code == 501) {
rv = RVENOIMPL;
} else if (code == 503) {
rv = RVETIMEOUT;
} else {
rv = RVEINTERNAL;
}
} else {
rv = RVEMISC;
}
return rv;
}
/**
* Get the expression of the socket.
* @return the expression of the socket or an empty string on failure.
*/
const std::string expression() {
_assert_(true);
if (!open_) return "";
std::string expr;
kc::strprintf(&expr, "%s:%d", host_.c_str(), port_);
return expr;
}
/**
* Reveal the internal HTTP client.
* @return the internal HTTP client.
*/
HTTPClient* reveal_core() {
_assert_(true);
return &ua_;
}
private:
/** The HTTP client. */
HTTPClient ua_;
/** The host name of the server. */
std::string host_;
/** The port numer of the server. */
uint32_t port_;
/** The timeout. */
double timeout_;
/** The open flag. */
bool open_;
/** The alive flag. */
bool alive_;
};
/**
* RPC server.
*/
class RPCServer {
public:
class Logger;
class Worker;
class Session;
private:
class WorkerAdapter;
public:
/**
* Interface to log internal information and errors.
*/
class Logger : public HTTPServer::Logger {
public:
/**
* Destructor.
*/
virtual ~Logger() {
_assert_(true);
}
};
/**
* Interface to process each request.
*/
class Worker {
public:
/**
* Destructor.
*/
virtual ~Worker() {
_assert_(true);
}
/**
* Process each request of RPC.
* @param serv the server.
* @param sess the session with the client.
* @param name the name of the procecude.
* @param inmap a string map which contains the input of the procedure.
* @param outmap a string map to contain the input parameters.
* @return the return value of the procedure.
*/
virtual RPCClient::ReturnValue process(RPCServer* serv, Session* sess,
const std::string& name,
const std::map& inmap,
std::map& outmap) = 0;
/**
* Process each request of the others.
* @param serv the server.
* @param sess the session with the client.
* @param path the path of the requested resource.
* @param method the kind of the request methods.
* @param reqheads a string map which contains the headers of the request. Header names are
* converted into lower cases. The empty key means the request-line.
* @param reqbody a string which contains the entity body of the request.
* @param resheads a string map to contain the headers of the response.
* @param resbody a string to contain the entity body of the response.
* @param misc a string map which contains miscellaneous information. "url" means the
* absolute URL. "query" means the query string of the URL.
* @return the status code of the response. If it is less than 1, internal server error is
* sent to the client and the connection is closed.
*/
virtual int32_t process(HTTPServer* serv, HTTPServer::Session* sess,
const std::string& path, HTTPClient::Method method,
const std::map& reqheads,
const std::string& reqbody,
std::map& resheads,
std::string& resbody,
const std::map& misc) {
_assert_(serv && sess);
return 501;
}
/**
* Process each binary request.
* @param serv the server.
* @param sess the session with the client.
* @return true to reuse the session, or false to close the session.
*/
virtual bool process_binary(ThreadedServer* serv, ThreadedServer::Session* sess) {
_assert_(serv && sess);
return false;
}
/**
* Process each idle event.
* @param serv the server.
*/
virtual void process_idle(RPCServer* serv) {
_assert_(serv);
}
/**
* Process each timer event.
* @param serv the server.
*/
virtual void process_timer(RPCServer* serv) {
_assert_(serv);
}
/**
* Process the starting event.
* @param serv the server.
*/
virtual void process_start(RPCServer* serv) {
_assert_(serv);
}
/**
* Process the finishing event.
* @param serv the server.
*/
virtual void process_finish(RPCServer* serv) {
_assert_(serv);
}
};
/**
* Interface to log internal information and errors.
*/
class Session {
friend class RPCServer;
public:
/**
* Interface of session local data.
*/
class Data : public HTTPServer::Session::Data {
public:
/**
* Destructor.
*/
virtual ~Data() {
_assert_(true);
}
};
/**
* Get the ID number of the session.
* @return the ID number of the session.
*/
uint64_t id() {
_assert_(true);
return sess_->id();
}
/**
* Get the ID number of the worker thread.
* @return the ID number of the worker thread. It is from 0 to less than the number of
* worker threads.
*/
uint32_t thread_id() {
_assert_(true);
return sess_->thread_id();
}
/**
* Set the session local data.
* @param data the session local data. If it is NULL, no data is registered.
* @note The registered data is destroyed implicitly when the session object is destroyed or
* this method is called again.
*/
void set_data(Data* data) {
_assert_(true);
sess_->set_data(data);
}
/**
* Get the session local data.
* @return the session local data, or NULL if no data is registered.
*/
Data* data() {
_assert_(true);
return (Data*)sess_->data();
}
/**
* Get the expression of the socket.
* @return the expression of the socket or an empty string on failure.
*/
const std::string expression() {
_assert_(true);
return sess_->expression();
}
private:
/**
* Constructor.
*/
explicit Session(HTTPServer::Session* sess) : sess_(sess) {
_assert_(true);
}
/**
* Destructor.
*/
virtual ~Session() {
_assert_(true);
}
private:
HTTPServer::Session* sess_;
};
/**
* Default constructor.
*/
explicit RPCServer() : serv_(), worker_() {
_assert_(true);
}
/**
* Destructor.
*/
~RPCServer() {
_assert_(true);
}
/**
* Set the network configurations.
* @param expr an expression of the address and the port of the server.
* @param timeout the timeout of each network operation in seconds. If it is not more than 0,
* no timeout is specified.
*/
void set_network(const std::string& expr, double timeout = -1) {
_assert_(true);
serv_.set_network(expr, timeout);
}
/**
* Set the logger to process each log message.
* @param logger the logger object.
* @param kinds kinds of logged messages by bitwise-or: Logger::DEBUG for debugging,
* Logger::INFO for normal information, Logger::SYSTEM for system information, and
* Logger::ERROR for fatal error.
*/
void set_logger(Logger* logger, uint32_t kinds = Logger::SYSTEM | Logger::ERROR) {
_assert_(true);
serv_.set_logger(logger, kinds);
}
/**
* Set the worker to process each request.
* @param worker the worker object.
* @param thnum the number of worker threads.
*/
void set_worker(Worker* worker, size_t thnum = 1) {
_assert_(true);
worker_.serv_ = this;
worker_.worker_ = worker;
serv_.set_worker(&worker_, thnum);
}
/**
* Start the service.
* @return true on success, or false on failure.
* @note This function blocks until the server stops by the RPCServer::stop method.
*/
bool start() {
_assert_(true);
return serv_.start();
}
/**
* Stop the service.
* @return true on success, or false on failure.
*/
bool stop() {
_assert_(true);
return serv_.stop();
}
/**
* Finish the service.
* @return true on success, or false on failure.
*/
bool finish() {
_assert_(true);
return serv_.finish();
}
/**
* Log a message.
* @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal
* information, Logger::SYSTEM for system information, and Logger::ERROR for fatal error.
* @param format the printf-like format string. The conversion character `%' can be used with
* such flag characters as `s', `d', `o', `u', `x', `X', `c', `e', `E', `f', `g', `G', and `%'.
* @param ... used according to the format string.
*/
void log(Logger::Kind kind, const char* format, ...) {
_assert_(format);
va_list ap;
va_start(ap, format);
serv_.log_v(kind, format, ap);
va_end(ap);
}
/**
* Log a message.
* @note Equal to the original Cursor::set_value method except that the last parameters is
* va_list.
*/
void log_v(Logger::Kind kind, const char* format, va_list ap) {
_assert_(format);
serv_.log_v(kind, format, ap);
}
/**
* Reveal the internal HTTP server.
* @return the internal HTTP server.
*/
HTTPServer* reveal_core() {
_assert_(true);
return &serv_;
}
private:
/**
* Adapter for the worker.
*/
class WorkerAdapter : public HTTPServer::Worker {
friend class RPCServer;
public:
WorkerAdapter() : serv_(NULL), worker_(NULL) {
_assert_(true);
}
private:
int32_t process(HTTPServer* serv, HTTPServer::Session* sess,
const std::string& path, HTTPClient::Method method,
const std::map& reqheads,
const std::string& reqbody,
std::map& resheads,
std::string& resbody,
const std::map& misc) {
const char* name = path.c_str();
if (!kc::strfwm(name, KTRPCPATHPREFIX))
return worker_->process(serv, sess, path, method, reqheads, reqbody,
resheads, resbody, misc);
name += sizeof(KTRPCPATHPREFIX) - 1;
size_t zsiz;
char* zbuf = kc::urldecode(name, &zsiz);
std::string rawname(zbuf, zsiz);
delete[] zbuf;
std::map inmap;
const char* rp = strmapget(misc, "query");
if (rp) wwwformtomap(rp, &inmap);
rp = strmapget(reqheads, "content-type");
if (rp) {
if (kc::strifwm(rp, KTRPCFORMMTYPE)) {
wwwformtomap(reqbody.c_str(), &inmap);
} else if (kc::strifwm(rp, KTRPCTSVMTYPE)) {
rp += sizeof(KTRPCTSVMTYPE) - 1;
int32_t enc = 0;
while (*rp != '\0') {
while (*rp == ' ' || *rp == ';') {
rp++;
}
if (kc::strifwm(rp, KTRPCTSVMATTR) && rp[sizeof(KTRPCTSVMATTR)-1] == '=') {
rp += sizeof(KTRPCTSVMATTR);
if (*rp == '"') rp++;
switch (*rp) {
case 'b': case 'B': enc = 'B'; break;
case 'q': case 'Q': enc = 'Q'; break;
case 'u': case 'U': enc = 'U'; break;
}
}
while (*rp != '\0' && *rp != ' ' && *rp != ';') {
rp++;
}
}
tsvtomap(reqbody, &inmap);
if (enc != 0) tsvmapdecode(&inmap, enc);
}
}
std::map outmap;
Session mysess(sess);
RPCClient::ReturnValue rv = worker_->process(serv_, &mysess, rawname, inmap, outmap);
int32_t code = -1;
switch (rv) {
case RPCClient::RVSUCCESS: code = 200; break;
case RPCClient::RVENOIMPL: code = 501; break;
case RPCClient::RVEINVALID: code = 400; break;
case RPCClient::RVELOGIC: code = 450; break;
case RPCClient::RVETIMEOUT: code = 503; break;
default: code = 500; break;
}
int32_t enc = checkmapenc(outmap);
std::string outtype = KTRPCTSVMTYPE;
switch (enc) {
case 'B': kc::strprintf(&outtype, "; %s=B", KTRPCTSVMATTR); break;
case 'Q': kc::strprintf(&outtype, "; %s=Q", KTRPCTSVMATTR); break;
case 'U': kc::strprintf(&outtype, "; %s=U", KTRPCTSVMATTR); break;
}
resheads["content-type"] = outtype;
if (enc != 0) tsvmapencode(&outmap, enc);
maptotsv(outmap, &resbody);
return code;
}
bool process_binary(ThreadedServer* serv, ThreadedServer::Session* sess) {
return worker_->process_binary(serv, sess);
}
void process_idle(HTTPServer* serv) {
worker_->process_idle(serv_);
}
void process_timer(HTTPServer* serv) {
worker_->process_timer(serv_);
}
void process_start(HTTPServer* serv) {
worker_->process_start(serv_);
}
void process_finish(HTTPServer* serv) {
worker_->process_finish(serv_);
}
RPCServer* serv_;
RPCServer::Worker* worker_;
};
/** Dummy constructor to forbid the use. */
RPCServer(const RPCServer&);
/** Dummy Operator to forbid the use. */
RPCServer& operator =(const RPCServer&);
/** The internal server. */
HTTPServer serv_;
/** The adapter for worker. */
WorkerAdapter worker_;
};
} // common namespace
#endif // duplication check
// END OF FILE
kyototycoon-0.9.56/ktcommon.h 0000644 0001750 0001750 00000002532 11757471602 015232 0 ustar mikio mikio /*************************************************************************************************
* Common symbols for the library
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#ifndef _KTCOMMON_H // duplication check
#define _KTCOMMON_H
#include
#include
#include
#include
#include
#include
/**
* All symbols of Kyoto Tycoon.
*/
namespace kyototycoon {
namespace kc = kyotocabinet;
}
#endif // duplication check
// END OF FILE
kyototycoon-0.9.56/example/ 0000755 0001750 0001750 00000000000 11757471566 014674 5 ustar mikio mikio kyototycoon-0.9.56/example/ktreplprint.rb 0000644 0001750 0001750 00000002141 11757471566 017575 0 ustar mikio mikio require 'base64'
rtspath = "ktreplprint.rts"
mode = File::Constants::RDWR | File::Constants::CREAT
File::open(rtspath, mode) do |rtsfile|
while true
begin
line = $stdin.readline
rescue
break
end
line = line.strip
fields = line.split("\t")
next if fields.length < 4
rts = fields[0]
rsid = fields[1]
rdbid = fields[2]
rcmd = fields[3]
args = []
i = 4
while i < fields.length
args.push(fields[i].unpack("m")[0])
i += 1
end
printf("ts=%d sid=%d dbid=%d: ", rts, rsid, rdbid)
case rcmd
when "set"
if args.length >= 2
key = args[0]
value = args[1][5,args[1].length]
nums = args[1].unpack("C5")
xt = 0
nums.each do |num|
xt = (xt << 8) + num
end
printf("set: key=%s value=%s xt=%d", key, value, xt)
end
when "remove"
if args.length >= 1
key = args[0]
printf("remove: key=%s", key)
end
when "clear"
printf("clear")
end
printf("\n")
rtsfile.pos = 0
rtsfile.printf("%020d\n", rts)
end
end
exit 0
kyototycoon-0.9.56/example/ktmemcfastex.pl 0000644 0001750 0001750 00000003370 11757471566 017727 0 ustar mikio mikio use strict;
use warnings;
use Cache::Memcached::Fast;
my $servers = [{
address => "127.0.0.1:11211",
noreply => 1,
}];
printf("connecting...\n");
my $cache = Cache::Memcached::Fast->new({ servers => $servers });
if (!defined($cache)) {
printf("new failed\n");
}
printf("checking the version...\n");
my $versions = $cache->server_versions();
while (my ($server, $version) = each(%$versions)) {
printf("versions: %s: %s\n", $server, $version);
}
printf("flusing...\n");
if (!$cache->flush_all()) {
printf("flush_all failed\n");
}
printf("flusing without reply...\n");
$cache->flush_all();
printf("setting...\n");
for (my $i = 1; $i <= 10; $i++) {
if (!$cache->set($i, $i)) {
printf("set failed\n");
}
}
printf("incrementing...\n");
for (my $i = 1; $i <= 10; $i++) {
if (!defined($cache->incr($i, 10000))) {
printf("incr failed\n");
}
if (!defined($cache->decr($i, 1000))) {
printf("decr failed\n");
}
}
printf("retrieving...\n");
for (my $i = 1; $i <= 10; $i++) {
my $value = $cache->get($i);
printf("get: %s: %s\n", $i, $value);
}
printf("removing...\n");
for (my $i = 1; $i <= 10; $i++) {
if (!$cache->remove($i)) {
printf("remove failed\n");
}
}
printf("setting without reply...\n");
for (my $i = 1; $i <= 10; $i++) {
$cache->set($i, $i);
}
printf("incrementing without reply...\n");
for (my $i = 1; $i <= 10; $i++) {
$cache->incr($i, 1000);
}
printf("retrieving in bulk...\n");
my $values = $cache->get_multi(1..10);
while (my ($key, $value) = each(%$values)) {
printf("get_multi: %s: %s\n", $key, $value);
}
printf("removing without reply...\n");
for (my $i = 1; $i <= 10; $i++) {
$cache->delete($i);
}
printf("disconnecting...\n");
$cache->disconnect_all();
kyototycoon-0.9.56/example/ktrestex.pl 0000644 0001750 0001750 00000004064 11757471566 017106 0 ustar mikio mikio use strict;
use warnings;
use LWP::UserAgent;
use URI::Escape;
{
# RESTful interface of Kyoto Tycoon
package KyotoTycoon;
# constructor
sub new {
my $self = {};
bless $self;
return $self;
}
# connect to the server
sub open {
my ($self, $host, $port, $timeout) = @_;
$host = "127.0.0.1" if (!defined($host));
$port = 1978 if (!defined($port));
$timeout = 30 if (!defined($timeout));
$self->{base} = "http://$host:$port/";
$self->{ua} = LWP::UserAgent->new(keep_alive => 1);
$self->{ua}->timeout($timeout);
return undef;
}
# close the connection
sub close {
my ($self) = @_;
$self->{ua} = undef;
return undef;
}
# store a record
sub set {
my ($self, $key, $value, $xt) = @_;
my $url = $self->{base} . URI::Escape::uri_escape($key);
my @headers;
if (defined($xt)) {
$xt = time() + $xt;
push(@headers, "X-Kt-Xt");
push(@headers, $xt);
}
my $req = HTTP::Request->new(PUT => $url, \@headers, $value);
my $res = $self->{ua}->request($req);
my $code = $res->code();
return $code == 201;
}
# remove a record
sub remove {
my ($self, $key) = @_;
my $url = $self->{base} . URI::Escape::uri_escape($key);
my $req = HTTP::Request->new(DELETE => $url);
my $res = $self->{ua}->request($req);
my $code = $res->code();
return $code == 204;
}
# retrieve the value of a record
sub get {
my ($self, $key) = @_;
my $url = $self->{base} . URI::Escape::uri_escape($key);
my $req = HTTP::Request->new(GET => $url);
my $res = $self->{ua}->request($req);
my $code = $res->code();
return undef if ($code != 200);
return $res->content();
}
}
# sample usage
my $kt = new KyotoTycoon;
$kt->open("localhost", 1978);
$kt->set("japan", "tokyo", 30);
printf("%s\n", $kt->get("japan"));
$kt->remove("japan");
$kt->close();
kyototycoon-0.9.56/example/ktremoteex.cc 0000644 0001750 0001750 00000001674 11757471566 017402 0 ustar mikio mikio #include
using namespace std;
using namespace kyototycoon;
// main routine
int main(int argc, char** argv) {
// create the database object
RemoteDB db;
// open the database
if (!db.open()) {
cerr << "open error: " << db.error().name() << endl;
}
// store records
if (!db.set("foo", "hop") ||
!db.set("bar", "step") ||
!db.set("baz", "jump")) {
cerr << "set error: " << db.error().name() << endl;
}
// retrieve a record
string value;
if (db.get("foo", &value)) {
cout << value << endl;
} else {
cerr << "get error: " << db.error().name() << endl;
}
// traverse records
RemoteDB::Cursor* cur = db.cursor();
cur->jump();
string ckey, cvalue;
while (cur->get(&ckey, &cvalue, NULL, true)) {
cout << ckey << ":" << cvalue << endl;
}
delete cur;
// close the database
if (!db.close()) {
cerr << "close error: " << db.error().name() << endl;
}
return 0;
}
kyototycoon-0.9.56/example/Makefile 0000644 0001750 0001750 00000003403 11460057211 016306 0 ustar mikio mikio # Makefile for sample programs of Kyoto Tycoon
#================================================================
# Setting Variables
#================================================================
# Generic settings
SHELL = /bin/sh
# Targets
MYBINS = ktremoteex ktpollex ktthservex kthttpex
# Building binaries
CC = gcc
CXX = g++
CFLAGS = -I. -I.. -Wall -ansi -pedantic -fsigned-char -O2
CXXFLAGS = -I. -I.. -Wall -fsigned-char -O2
LDFLAGS =
LIBS = -L. -L.. -lkyototycoon -lkyotocabinet -lstdc++ -lz -lrt -lpthread -lm -lc
LDENV = LD_RUN_PATH=/lib:/usr/lib:$(HOME)/lib:/usr/local/lib:.:..
RUNENV = LD_LIBRARY_PATH=/lib:/usr/lib:$(HOME)/lib:/usr/local/lib:.:..
#================================================================
# Suffix rules
#================================================================
.SUFFIXES :
.SUFFIXES : .c .cc .o
.c.o :
$(CC) -c $(CFLAGS) $<
.cc.o :
$(CXX) -c $(CXXFLAGS) $<
#================================================================
# Actions
#================================================================
all : $(MYBINS)
clean :
rm -rf $(MYBINS) *.exe *.o a.out check.out gmon.out leak.log casket* *~
static :
make LDFLAGS="$(LDFLAGS) -static"
check :
rm -rf casket*
$(RUNENV) ./ktremoteex
.PHONY : all clean static
#================================================================
# Building binaries
#================================================================
ktremoteex : ktremoteex.o
$(LDENV) $(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS) $(LIBS)
ktpollex : ktpollex.o
$(LDENV) $(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS) $(LIBS)
ktthservex : ktthservex.o
$(LDENV) $(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS) $(LIBS)
kthttpex : kthttpex.o
$(LDENV) $(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS) $(LIBS)
# END OF FILE
kyototycoon-0.9.56/example/ktpollex.cc 0000644 0001750 0001750 00000004733 11757471566 017054 0 ustar mikio mikio #include
using namespace std;
using namespace kyototycoon;
// the flag whether the server is alive
Poller* g_poll = NULL;
// stop the running server
static void stopserver(int signum) {
if (g_poll) g_poll->abort();
g_poll = NULL;
}
// main routine
int main(int argc, char** argv) {
// set the signal handler to stop the server
setkillsignalhandler(stopserver);
// open the server socket
ServerSocket serv;
serv.open("127.0.0.1:1978");
// open the event notifier
Poller poll;
poll.open();
g_poll = &poll;
// deposit the server socket into the poller
serv.set_event_flags(Pollable::EVINPUT);
poll.deposit(&serv);
// event loop
while (g_poll) {
// wait one or more active requests
if (poll.wait()) {
// iterate all active requests
Pollable* event;
while ((event = poll.next()) != NULL) {
if (event == &serv) {
// accept a new connection
Socket* sock = new Socket;
sock->set_timeout(1.0);
if (serv.accept(sock)) {
sock->set_event_flags(Pollable::EVINPUT);
poll.deposit(sock);
}
// undo the server socket
serv.set_event_flags(Pollable::EVINPUT);
poll.undo(&serv);
} else {
// process each request
Socket* sock = (Socket*)event;
// read a line from the client socket
char line[1024];
if (sock->receive_line(line, sizeof(line))) {
if (!kc::stricmp(line, "/quit")) {
// process the quit command
sock->printf("> Bye!\n");
poll.withdraw(sock);
sock->close();
delete sock;
} else {
// echo back the message
sock->printf("> %s\n", line);
// undo the client socket
serv.set_event_flags(Pollable::EVINPUT);
poll.undo(sock);
}
} else {
// process a connection closed by the client
poll.withdraw(sock);
sock->close();
delete sock;
}
}
}
}
}
// clean up all connections
if (poll.flush()) {
Pollable* event;
while ((event = poll.next()) != NULL) {
if (event != &serv) {
Socket* sock = (Socket*)event;
poll.withdraw(sock);
sock->close();
delete sock;
}
}
}
// close the event notifier
poll.close();
// close the server socket
serv.close();
return 0;
}
kyototycoon-0.9.56/example/ktthservex.cc 0000644 0001750 0001750 00000002360 11757471566 017413 0 ustar mikio mikio #include
using namespace std;
using namespace kyototycoon;
// the flag whether the server is alive
ThreadedServer* g_serv = NULL;
// stop the running server
static void stopserver(int signum) {
if (g_serv) g_serv->stop();
g_serv = NULL;
}
// main routine
int main(int argc, char** argv) {
// set the signal handler to stop the server
setkillsignalhandler(stopserver);
// prepare the worker
class Worker : public ThreadedServer::Worker {
bool process(ThreadedServer* serv, ThreadedServer::Session* sess) {
bool keep = false;
// read a line from the client socket
char line[1024];
if (sess->receive_line(line, sizeof(line))) {
if (!kc::stricmp(line, "/quit")) {
// process the quit command
sess->printf("> Bye!\n");
} else {
// echo back the message
sess->printf("> %s\n", line);
keep = true;
}
}
return keep;
}
};
Worker worker;
// prepare the server
ThreadedServer serv;
serv.set_network("127.0.0.1:1978", 1.0);
serv.set_worker(&worker, 4);
g_serv = &serv;
// start the server and block until its stop
serv.start();
// clean up connections and other resources
serv.finish();
return 0;
}
kyototycoon-0.9.56/example/ktscrjsonex.lua 0000644 0001750 0001750 00000007474 11757471566 017770 0 ustar mikio mikio kt = __kyototycoon__
db = kt.db
json = require("json")
-- post a new document
function writedoc(inmap, outmap)
local doc = inmap.doc
if not doc then
return kt.RVEINVALID
end
local doc = json.decode(doc)
local owner = tonumber(doc.owner)
local date = tonumber(doc.date)
local title = tostring(doc.title)
local text = tostring(doc.text)
local key = string.format("%010d:%010d", owner, date)
local doc = {}
doc.title = title
doc.text = text
local value = json.encode(doc)
if not db:add(key, value) then
local err = db:error()
if err:code() == kt.Error.DUPREC then
return kt.RVELOGIC
end
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- post a new comment
function addcomment(inmap, outmap)
local owner = tonumber(inmap.owner)
local date = tonumber(inmap.date)
local comowner = tonumber(inmap.comowner)
local comdate = tostring(inmap.comdate)
local comtext = tostring(inmap.comtext)
if not owner or not date or not comowner or not comdate or not comtext then
return kt.RVEINVALID
end
local key = string.format("%010d:%010d", owner, date)
local hit = false
local function visit(rkey, rvalue)
local doc = json.decode(rvalue)
if not doc.comments then
doc.comments = {}
end
local newcom = {}
newcom.owner = comowner
newcom.date = comdate
newcom.text = comtext
table.insert(doc.comments, newcom)
hit = true
return json.encode(doc)
end
if not db:accept(key, visit) then
local err = db:error()
if err:code() == kt.Error.DUPREC then
return kt.RVELOGIC
end
return kt.RVEINTERNAL
end
if not hit then
return kt.RVELOGIC
end
return kt.RVSUCCESS
end
-- get a document
function getdoc(inmap, outmap)
local owner = tonumber(inmap.owner)
local date = tonumber(inmap.date)
if not owner or not date then
return kt.RVEINVALID
end
local key = string.format("%010d:%010d", owner, date)
local value = db:get(key)
if not value then
return kt.RVELOGIC
end
local doc = _composedoc(key, value)
outmap.doc = json.encode(doc)
return kt.RVSUCCESS
end
-- list documents of a user
function listnewdocs(inmap, outmap)
local owner = tonumber(inmap.owner)
local max = tonumber(inmap.max)
if not owner then
return kt.RVEINVALID
end
if not max then
max = 10
end
local key = string.format("%010d:", owner)
local cur = db:cursor()
cur:jump_back(key .. "~")
local num = 0
while num < max do
local rkey, rvalue = cur:get()
if not rkey or not kt.strfwm(rkey, key) then
break
end
cur:step_back()
local doc = _composedoc(rkey, rvalue)
num = num + 1
outmap[num] = json.encode(doc)
end
return kt.RVSUCCESS
end
-- list documents of a user without the text and the comments
function listnewdocslight(inmap, outmap)
local owner = tonumber(inmap.owner)
local max = tonumber(inmap.max)
if not owner then
return kt.RVEINVALID
end
if not max then
max = 10
end
local key = string.format("%010d:", owner)
local cur = db:cursor()
cur:jump_back(key .. "~")
local num = 0
while num < max do
local rkey, rvalue = cur:get()
if not rkey or not kt.strfwm(rkey, key) then
break
end
cur:step_back()
local doc = _composedoc(rkey, rvalue)
doc.text = nil
doc.comnum = #doc.comments
doc.comments = nil
num = num + 1
outmap[num] = json.encode(doc)
end
return kt.RVSUCCESS
end
-- helper to compose a document object
function _composedoc(key, value)
local doc = json.decode(value)
doc.owner = string.gsub(key, ":%d*", "")
doc.date = string.gsub(key, "%d*:", "")
if not doc.comments then
doc.comments = {}
end
return doc
end
kyototycoon-0.9.56/example/ktreplmysql.rb 0000644 0001750 0001750 00000003553 11757471566 017616 0 ustar mikio mikio require 'dbi'
require 'base64'
hostname = "localhost"
dbname = "kttest"
username = "root"
password = ""
rtspath = "ktreplmysql.rts"
# $ mysql --user=root
# > create database kttest;
# > create table kttest (
# k varchar(256) primary key,
# v varchar(256) not null,
# xt datetime not null
# ) TYPE=InnoDB;
begin
dbh = DBI::connect("dbi:Mysql:#{dbname}:#{hostname}", username, password)
sthins = dbh.prepare("INSERT INTO kttest ( k, v, xt ) VALUES ( ?, ?, ? )" +
" ON DUPLICATE KEY UPDATE v = ?, xt = ?;")
sthrem = dbh.prepare("DELETE FROM kttest WHERE k = ?;")
sthclr = dbh.prepare("DELETE FROM kttest;")
mode = File::Constants::RDWR | File::Constants::CREAT
File::open(rtspath, mode) do |rtsfile|
while true
begin
line = $stdin.readline
rescue
break
end
line = line.strip
fields = line.split("\t")
next if fields.length < 4
rts = fields[0]
rsid = fields[1]
rdbid = fields[2]
rcmd = fields[3]
args = []
i = 4
while i < fields.length
args.push(fields[i].unpack("m")[0])
i += 1
end
case rcmd
when "set"
if args.length >= 2
key = args[0]
value = args[1][5,args[1].length]
nums = args[1].unpack("C5")
xt = 0
nums.each do |num|
xt = (xt << 8) + num
end
xt = 1 << 32 if xt > (1 << 32)
xt = Time::at(xt).strftime("%Y-%m-%d %H:%M:%S")
sthins.execute(key, value, xt, value, xt)
end
when "remove"
if args.length >= 1
key = args[0]
sthrem.execute(key)
end
when "clear"
sthclr.execute()
end
rtsfile.pos = 0
rtsfile.printf("%020d\n", rts)
end
end
rescue Exception => e
printf("Error: %s\n", e)
ensure
dbh.disconnect if dbh
end
exit 0
kyototycoon-0.9.56/example/ktmemcex.rb 0000644 0001750 0001750 00000002045 11757471566 017037 0 ustar mikio mikio require 'memcache'
host = "127.0.0.1:11211"
options = {
:timeout => 3600,
}
printf("connecting...\n")
cache = MemCache.new([host], options)
printf("count: %s\n", cache.stats[host]["curr_items"])
printf("flusing...\n")
cache.flush_all
printf("count: %s\n", cache.stats[host]["curr_items"])
printf("setting...\n")
(1..10).each do |i|
str = i.to_s
cache.set(str, str, 180, { :raw => true })
cache.add(str, str, 180, { :raw => true })
cache.replace(str, str, 180, { :raw => true })
end
printf("count: %s\n", cache.stats[host]["curr_items"])
printf("incrementing...\n")
(1..10).each do |i|
str = i.to_s
cache.incr(str, 10000)
cache.decr(str, 1000)
end
printf("count: %s\n", cache.stats[host]["curr_items"])
printf("getting...\n")
(1..10).each do |i|
str = i.to_s
value = cache.get(str, { :raw => true })
printf("get: %s: %s\n", str, value)
end
printf("count: %s\n", cache.stats[host]["curr_items"])
printf("removing...\n")
(1..10).each do |i|
str = i.to_s
cache.delete(str)
end
printf("count: %s\n", cache.stats[host]["curr_items"])
kyototycoon-0.9.56/example/ktrestex.rb 0000644 0001750 0001750 00000002132 11757471566 017070 0 ustar mikio mikio require 'uri'
require 'net/http'
# RESTful interface of Kyoto Tycoon
class KyotoTycoon
# connect to the server
def open(host = "127.0.0.1", port = 1978, timeout = 30)
@ua = Net::HTTP::new(host, port)
@ua.read_timeout = timeout
@ua.start
end
# close the connection
def close
@ua.finish
end
# store a record
def set(key, value, xt = nil)
key = "/" + URI::encode(key)
req = Net::HTTP::Put::new(key)
if xt
xt = Time::now.to_i + xt
req.add_field("X-Kt-Xt", xt)
end
res = @ua.request(req, value)
res.code.to_i == 201
end
# remove a record
def remove(key)
key = "/" + URI::encode(key)
req = Net::HTTP::Delete::new(key)
res = @ua.request(req)
res.code.to_i == 204
end
# retrieve the value of a record
def get(key)
key = "/" + URI::encode(key)
req = Net::HTTP::Get::new(key)
res = @ua.request(req)
return nil if res.code.to_i != 200
res.body
end
end
# sample usage
kt = KyotoTycoon::new
kt.open("localhost", 1978)
kt.set("japan", "tokyo", 60)
printf("%s\n", kt.get("japan"))
kt.remove("japan")
kt.close
kyototycoon-0.9.56/example/ktmemcmqex.rb 0000644 0001750 0001750 00000002010 11757471566 017365 0 ustar mikio mikio require 'memcache'
host = "127.0.0.1:11211"
options = {
:timeout => 3600,
}
thnum = 4
rnum = 100
gcache = MemCache.new([host], options)
gcache.flush_all
producers = Array::new
for thid in 0...thnum
th = Thread::new(thid) { |id|
cache = MemCache.new([host], options)
mid = rnum / 4
for i in 0...rnum
name = (i % 10).to_s
value = i.to_s
printf("set: %s: %s\n", name, value)
cache.set(name, value, 0, { :raw => true })
wt = rand() * 0.1
sleep(wt) if i >= mid && wt >= 0.01
end
}
producers.push(th)
end
workers = Array::new
for thid in 0...thnum
th = Thread::new(thid) { |id|
cache = MemCache.new([host], options)
for i in 0...rnum
name = (i % 10).to_s
value = cache.get(name, { :raw => true })
printf("get: %s: %s\n", name, value ? value : "(miss)")
cache.delete(name)
end
}
workers.push(th)
end
workers.each { |th|
th.join
}
producers.each { |th|
th.join
}
GC.start
printf("count: %s\n", gcache.stats[host]["curr_items"])
kyototycoon-0.9.56/example/ktrestex.py 0000644 0001750 0001750 00000003075 11757471566 017124 0 ustar mikio mikio import time
import urllib
import http.client
# RESTful interface of Kyoto Tycoon
class KyotoTycoon:
# connect to the server
def open(self, host = "127.0.0.1", port = 1978, timeout = 30):
self.ua = http.client.HTTPConnection(host, port, False, timeout)
# close the connection
def close(self):
self.ua.close()
# store a record
def set(self, key, value, xt = None):
if isinstance(key, str): key = key.encode("UTF-8")
if isinstance(value, str): value = value.encode("UTF-8")
key = "/" + urllib.parse.quote(key)
headers = {}
if xt != None:
xt = int(time.time()) + xt
headers["X-Kt-Xt"] = str(xt)
self.ua.request("PUT", key, value, headers)
res = self.ua.getresponse()
body = res.read()
return res.status == 201
# remove a record
def remove(self, key):
if isinstance(key, str): key = key.encode("UTF-8")
key = "/" + urllib.parse.quote(key)
self.ua.request("DELETE", key)
res = self.ua.getresponse()
body = res.read()
return res.status == 204
# retrieve the value of a record
def get(self, key):
if isinstance(key, str): key = key.encode("UTF-8")
key = "/" + urllib.parse.quote(key)
self.ua.request("GET", key)
res = self.ua.getresponse()
body = res.read()
if res.status != 200: return None
return body
# sample usage
kt = KyotoTycoon()
kt.open("localhost", 1978)
kt.set("japan", "tokyo", 60)
print(kt.get("japan"))
kt.remove("japan")
kt.close()
kyototycoon-0.9.56/example/kthttpex.cc 0000644 0001750 0001750 00000002713 11757471566 017061 0 ustar mikio mikio #include
using namespace std;
using namespace kyototycoon;
// the flag whether the server is alive
HTTPServer* g_serv = NULL;
// stop the running server
static void stopserver(int signum) {
if (g_serv) g_serv->stop();
g_serv = NULL;
}
// main routine
int main(int argc, char** argv) {
// set the signal handler to stop the server
setkillsignalhandler(stopserver);
// prepare the worker
class Worker : public HTTPServer::Worker {
int32_t process(HTTPServer* serv, HTTPServer::Session* sess,
const string& path, HTTPClient::Method method,
const map& reqheads,
const string& reqbody,
map& resheads,
string& resbody,
const map& misc) {
// echo back the input data
for (map::const_iterator it = reqheads.begin();
it != reqheads.end(); it++) {
if (!it->first.empty()) resbody.append(it->first + ": ");
resbody.append(it->second + "\n");
}
resbody.append(reqbody);
// return the status code
return 200;
}
};
Worker worker;
// prepare the server
HTTPServer serv;
serv.set_network("127.0.0.1:1978", 1.0);
serv.set_worker(&worker, 4);
g_serv = &serv;
// start the server and block until its stop
serv.start();
// clean up connections and other resources
serv.finish();
return 0;
}
kyototycoon-0.9.56/example/ktscrtableex.lua 0000644 0001750 0001750 00000011164 11757471566 020075 0 ustar mikio mikio kt = __kyototycoon__
db = kt.db
-- prepare secondary indices
idxdbs = {}
for dbname, dbobj in pairs(kt.dbs) do
if kt.strbwm(dbname, ".kct") then
local prefix = kt.regex(dbname, ".*/", "")
prefix = kt.regex(dbname, ".kct$", "")
if #prefix > 0 then
idxdbs[prefix] = dbobj
end
end
end
-- set a record
function set(inmap, outmap)
local id = tostring(inmap.id)
if not id then
return kt.RVEINVALID
end
local err = false
inmap.id = nil
local serial = kt.mapdump(inmap)
-- visitor function
local function visit(key, value, xt)
-- clean up indices
if value then
local obj = kt.mapload(value)
for rkey, rvalue in pairs(obj) do
local idxdb = idxdbs[rkey]
if idxdb then
local idxkey = rvalue .. " " .. id
if not idxdb:remove(idxkey) then
kt.log("error", "removing an index entry failed")
err = true
end
end
end
end
-- insert into indices
for rkey, rvalue in pairs(inmap) do
local idxdb = idxdbs[rkey]
if idxdb then
local idxkey = rvalue .. " " .. id
if not idxdb:set(idxkey, "") then
kt.log("error", "setting an index entry failed")
err = true
end
end
end
-- insert the serialized data into the main database
return serial
end
-- perform the visitor atomically
if not db:accept(id, visit) then
kt.log("error", "inserting a record failed")
err = true
end
if err then
return kt.EVEINTERNAL
end
return kt.RVSUCCESS
end
-- get a record
function get(inmap, outmap)
local id = tostring(inmap.id)
if not id then
return kt.RVEINVALID
end
local serial = db:get(id)
if not serial then
return kt.RVELOGIC
end
local rec = kt.mapload(serial)
for rkey, rvalue in pairs(rec) do
outmap[rkey] = rvalue
end
return kt.RVSUCCESS
end
-- get heading records
function head(inmap, outmap)
local name = tostring(inmap.name)
if not name then
return kt.RVEINVALID
end
local max = tonumber(inmap.max)
if not max then
max = 10
end
local idxdb = idxdbs[name]
if not idxdb then
return kt.RVELOGIC
end
local cur = idxdb:cursor()
cur:jump()
local rec
while max > 0 do
local key = cur:get_key(true)
if not key then
break
end
local rkey = kt.regex(key, "[^ ]+ ", "")
local rvalue = kt.regex(key, " .*", "")
outmap[rkey] = rvalue
max = max - 1
end
cur:disable()
return kt.RVSUCCESS
end
-- get tailing records
function tail(inmap, outmap)
local name = tostring(inmap.name)
if not name then
return kt.RVEINVALID
end
local max = tonumber(inmap.max)
if not max then
max = 10
end
local idxdb = idxdbs[name]
if not idxdb then
return kt.RVELOGIC
end
local cur = idxdb:cursor()
cur:jump_back()
local rec
while max > 0 do
local key = cur:get_key()
if not key then
break
end
local rkey = kt.regex(key, "[^ ]+ ", "")
local rvalue = kt.regex(key, " .*", "")
outmap[rkey] = rvalue
cur:step_back()
max = max - 1
end
cur:disable()
return kt.RVSUCCESS
end
-- reindex an index
function reindex(inmap, outmap)
local name = tostring(inmap.name)
if not name then
return kt.RVEINVALID
end
local idxdb = idxdbs[name]
if not idxdb then
return kt.RVELOGIC
end
local err = false
-- map function: invert the record data
local function map(key, value, emit)
local obj = kt.mapload(value)
for rkey, rvalue in pairs(obj) do
local idxdb = idxdbs[rkey]
if idxdb then
emit(rvalue, key)
end
end
return true
end
-- reduce function: insert into the index
local function reduce(key, iter)
local value
while true do
value = iter()
if not value then
break
end
local idxkey = key .. " " .. value
if not idxdb:set(idxkey, "") then
kt.log("error", "setting an index entry failed")
err = true
end
end
if err then
return false
end
return true
end
-- clear the index
if not idxdb:clear() then
kt.log("error", "clearing an index failed")
err = true
end
-- update the index
if not db:mapreduce(map, reduce) then
kt.log("error", "mapreduce failed")
err = true
end
if err then
return kt.EVEINTERNAL
end
return kt.RVSUCCESS
end
kyototycoon-0.9.56/example/ktscrex.lua 0000644 0001750 0001750 00000013771 11757471566 017073 0 ustar mikio mikio kt = __kyototycoon__
db = kt.db
-- log the start-up message
if kt.thid == 0 then
kt.log("system", "the Lua script has been loaded")
end
-- echo back the input data as the output data
function echo(inmap, outmap)
for key, value in pairs(inmap) do
outmap[key] = value
end
return kt.RVSUCCESS
end
-- report the internal state of the server
function report(inmap, outmap)
outmap["__kyototycoon__.VERSION"] = kt.VERSION
outmap["__kyototycoon__.thid"] = kt.thid
outmap["__kyototycoon__.db"] = tostring(kt.db)
for i = 1, #kt.dbs do
local key = "__kyototycoon__.dbs[" .. i .. "]"
outmap[key] = tostring(kt.dbs[i])
end
local names = ""
for name, value in pairs(kt.dbs) do
if #names > 0 then names = names .. "," end
names = names .. name
end
outmap["names"] = names
return kt.RVSUCCESS
end
-- log a message
function log(inmap, outmap)
local kind = inmap.kind
local message = inmap.message
if not message then
return kt.RVEINVALID
end
if not kind then
kind = "info"
end
kt.log(kind, message)
return kt.RVSUCCESS
end
-- store a record
function set(inmap, outmap)
local key = inmap.key
local value = inmap.value
if not key or not value then
return kt.RVEINVALID
end
local xt = inmap.xt
if not db:set(key, value, xt) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- remove a record
function remove(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
if not db:remove(key) then
local err = db:error()
if err:code() == kt.Error.NOREC then
return kt.RVELOGIC
end
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- increment the numeric string value
function increment(inmap, outmap)
local key = inmap.key
local num = inmap.num
if not key or not num then
return kt.RVEINVALID
end
local function visit(rkey, rvalue, rxt)
rvalue = tonumber(rvalue)
if not rvalue then rvalue = 0 end
num = rvalue + num
return num
end
if not db:accept(key, visit) then
return kt.REINTERNAL
end
outmap.num = num
return kt.RVSUCCESS
end
-- retrieve the value of a record
function get(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
local value, xt = db:get(key)
if value then
outmap.value = value
outmap.xt = xt
else
local err = db:error()
if err:code() == kt.Error.NOREC then
return kt.RVELOGIC
end
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- store records at once
function setbulk(inmap, outmap)
local num = db:set_bulk(inmap)
if num < 0 then
return kt.RVEINTERNAL
end
outmap["num"] = num
return kt.RVSUCCESS
end
-- remove records at once
function removebulk(inmap, outmap)
local keys = {}
for key, value in pairs(inmap) do
table.insert(keys, key)
end
local num = db:remove_bulk(keys)
if num < 0 then
return kt.RVEINTERNAL
end
outmap["num"] = num
return kt.RVSUCCESS
end
-- retrieve records at once
function getbulk(inmap, outmap)
local keys = {}
for key, value in pairs(inmap) do
table.insert(keys, key)
end
local res = db:get_bulk(keys)
if not res then
return kt.RVEINTERNAL
end
for key, value in pairs(res) do
outmap[key] = value
end
return kt.RVSUCCESS
end
-- move the value of a record to another
function move(inmap, outmap)
local srckey = inmap.src
local destkey = inmap.dest
if not srckey or not destkey then
return kt.RVEINVALID
end
local keys = { srckey, destkey }
local first = true
local srcval = nil
local srcxt = nil
local function visit(key, value, xt)
if first then
srcval = value
srcxt = xt
first = false
return kt.Visitor.REMOVE
end
if srcval then
return srcval, srcxt
end
return kt.Visitor.NOP
end
if not db:accept_bulk(keys, visit) then
return kt.REINTERNAL
end
if not srcval then
return kt.RVELOGIC
end
return kt.RVSUCCESS
end
-- list all records
function list(inmap, outmap)
local cur = db:cursor()
cur:jump()
while true do
local key, value, xt = cur:get(true)
if not key then break end
outmap[key] = value
end
return kt.RVSUCCESS
end
-- upcate all characters in the value of a record
function upcase(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
local function visit(key, value, xt)
if not value then
return kt.Visitor.NOP
end
return string.upper(value)
end
if not db:accept(key, visit) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- prolong the expiration time of a record
function survive(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
local function visit(key, value, xt)
if not value then
return kt.Visitor.NOP
end
outmap.old_xt = xt
if xt > kt.time() + 3600 then
return kt.Visitor.NOP
end
return value, 3600
end
if not db:accept(key, visit) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- count words with the MapReduce framework
function countwords(inmap, outmap)
local function map(key, value, emit)
local values = kt.split(value, " ")
for i = 1, #values do
local word = kt.regex(values[i], "[ .?!:;]", "")
word = string.lower(word)
if #word > 0 then
if not emit(word, "") then
return false
end
end
end
return true
end
local function reduce(key, iter)
local count = 0
while true do
local value = iter()
if not value then
break
end
count = count + 1
end
outmap[key] = count
return true
end
if not db:mapreduce(map, reduce, nil, kt.DB.XNOLOCK) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
kyototycoon-0.9.56/ktdbext.h 0000644 0001750 0001750 00000065770 11757471602 015065 0 ustar mikio mikio /*************************************************************************************************
* Database extension
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#ifndef _KTDBEXT_H // duplication check
#define _KTDBEXT_H
#include
#include
#include
#include
#include
namespace kyototycoon { // common namespace
/**
* MapReduce framework.
* @note Although this framework is not distributed or concurrent, it is useful for aggregate
* calculation with less CPU loading and less memory usage.
*/
class MapReduce {
public:
class ValueIterator;
private:
class FlushThread;
class ReduceTaskQueue;
class MapVisitor;
struct MergeLine;
/** An alias of vector of loaded values. */
typedef std::vector Values;
/** The default number of temporary databases. */
static const size_t DEFDBNUM = 8;
/** The maxinum number of temporary databases. */
static const size_t MAXDBNUM = 256;
/** The default cache limit. */
static const int64_t DEFCLIM = 512LL << 20;
/** The default cache bucket numer. */
static const int64_t DEFCBNUM = 1048583LL;
/** The bucket number of temprary databases. */
static const int64_t DBBNUM = 512LL << 10;
/** The page size of temprary databases. */
static const int32_t DBPSIZ = 32768;
/** The mapped size of temprary databases. */
static const int64_t DBMSIZ = 516LL * 4096;
/** The page cache capacity of temprary databases. */
static const int64_t DBPCCAP = 16LL << 20;
/** The default number of threads in parallel mode. */
static const size_t DEFTHNUM = 8;
/** The number of slots of the record lock. */
static const int32_t RLOCKSLOT = 256;
public:
/**
* Value iterator for the reducer.
*/
class ValueIterator {
friend class MapReduce;
public:
/**
* Get the next value.
* @param sp the pointer to the variable into which the size of the region of the return
* value is assigned.
* @return the pointer to the next value region, or NULL if no value remains.
*/
const char* next(size_t* sp) {
_assert_(sp);
if (!vptr_) {
if (vit_ == vend_) return NULL;
vptr_ = vit_->data();
vsiz_ = vit_->size();
vit_++;
}
uint64_t vsiz;
size_t step = kc::readvarnum(vptr_, vsiz_, &vsiz);
vptr_ += step;
vsiz_ -= step;
const char* vbuf = vptr_;
*sp = vsiz;
vptr_ += vsiz;
vsiz_ -= vsiz;
if (vsiz_ < 1) vptr_ = NULL;
return vbuf;
}
private:
/**
* Default constructor.
*/
explicit ValueIterator(Values::const_iterator vit, Values::const_iterator vend) :
vit_(vit), vend_(vend), vptr_(NULL), vsiz_(0) {
_assert_(true);
}
/**
* Destructor.
*/
~ValueIterator() {
_assert_(true);
}
/** Dummy constructor to forbid the use. */
ValueIterator(const ValueIterator&);
/** Dummy Operator to forbid the use. */
ValueIterator& operator =(const ValueIterator&);
/** The current iterator of loaded values. */
Values::const_iterator vit_;
/** The ending iterator of loaded values. */
Values::const_iterator vend_;
/** The pointer of the current value. */
const char* vptr_;
/** The size of the current value. */
size_t vsiz_;
};
/**
* Execution options.
*/
enum Option {
XNOLOCK = 1 << 0, ///< avoid locking against update operations
XPARAMAP = 1 << 1, ///< run mappers in parallel
XPARARED = 1 << 2, ///< run reducers in parallel
XPARAFLS = 1 << 3, ///< run cache flushers in parallel
XNOCOMP = 1 << 8 ///< avoid compression of temporary databases
};
/**
* Default constructor.
*/
explicit MapReduce() :
rcomp_(NULL), tmpdbs_(NULL), dbnum_(DEFDBNUM), dbclock_(0),
mapthnum_(DEFTHNUM), redthnum_(DEFTHNUM), flsthnum_(DEFTHNUM),
cache_(NULL), csiz_(0), clim_(DEFCLIM), cbnum_(DEFCBNUM), flsths_(NULL),
redtasks_(NULL), redaborted_(false), rlocks_(NULL) {
_assert_(true);
}
/**
* Destructor.
*/
virtual ~MapReduce() {
_assert_(true);
}
/**
* Map a record data.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @return true on success, or false on failure.
* @note This function can call the MapReduce::emit method to emit a record. To avoid
* deadlock, any explicit database operation must not be performed in this function.
*/
virtual bool map(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz) = 0;
/**
* Reduce a record data.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param iter the iterator to get the values.
* @return true on success, or false on failure.
* @note To avoid deadlock, any explicit database operation must not be performed in this
* function.
*/
virtual bool reduce(const char* kbuf, size_t ksiz, ValueIterator* iter) = 0;
/**
* Preprocess the map operations.
* @return true on success, or false on failure.
* @note This function can call the MapReduce::emit method to emit a record. To avoid
* deadlock, any explicit database operation must not be performed in this function.
*/
virtual bool preprocess() {
_assert_(true);
return true;
}
/**
* Mediate between the map and the reduce phases.
* @return true on success, or false on failure.
* @note This function can call the MapReduce::emit method to emit a record. To avoid
* deadlock, any explicit database operation must not be performed in this function.
*/
virtual bool midprocess() {
_assert_(true);
return true;
}
/**
* Postprocess the reduce operations.
* @return true on success, or false on failure.
* @note To avoid deadlock, any explicit database operation must not be performed in this
* function.
*/
virtual bool postprocess() {
_assert_(true);
return true;
}
/**
* Process a log message.
* @param name the name of the event.
* @param message a supplement message.
* @return true on success, or false on failure.
*/
virtual bool log(const char* name, const char* message) {
_assert_(name && message);
return true;
}
/**
* Execute the MapReduce process about a database.
* @param db the source database.
* @param tmppath the path of a directory for the temporary data storage. If it is an empty
* string, temporary data are handled on memory.
* @param opts the optional features by bitwise-or: MapReduce::XNOLOCK to avoid locking
* against update operations by other threads, MapReduce::XNOCOMP to avoid compression of
* temporary databases.
* @return true on success, or false on failure.
*/
bool execute(TimedDB* db, const std::string& tmppath = "", uint32_t opts = 0) {
int64_t count = db->count();
if (count < 0) {
if (db->error() != kc::BasicDB::Error::NOIMPL) return false;
count = 0;
}
bool err = false;
double stime, etime;
db_ = db;
rcomp_ = kc::LEXICALCOMP;
kc::BasicDB* idb = db->reveal_inner_db();
const std::type_info& info = typeid(*idb);
if (info == typeid(kc::GrassDB)) {
kc::GrassDB* gdb = (kc::GrassDB*)idb;
rcomp_ = gdb->rcomp();
} else if (info == typeid(kc::TreeDB)) {
kc::TreeDB* tdb = (kc::TreeDB*)idb;
rcomp_ = tdb->rcomp();
} else if (info == typeid(kc::ForestDB)) {
kc::ForestDB* fdb = (kc::ForestDB*)idb;
rcomp_ = fdb->rcomp();
}
tmpdbs_ = new kc::BasicDB*[dbnum_];
if (tmppath.empty()) {
if (!logf("prepare", "started to open temporary databases on memory")) err = true;
stime = kc::time();
for (size_t i = 0; i < dbnum_; i++) {
kc::GrassDB* gdb = new kc::GrassDB;
int32_t myopts = 0;
if (!(opts & XNOCOMP)) myopts |= kc::GrassDB::TCOMPRESS;
gdb->tune_options(myopts);
gdb->tune_buckets(DBBNUM / 2);
gdb->tune_page(DBPSIZ);
gdb->tune_page_cache(DBPCCAP);
gdb->tune_comparator(rcomp_);
gdb->open("%", kc::GrassDB::OWRITER | kc::GrassDB::OCREATE | kc::GrassDB::OTRUNCATE);
tmpdbs_[i] = gdb;
}
etime = kc::time();
if (!logf("prepare", "opening temporary databases finished: time=%.6f", etime - stime))
err = true;
if (err) {
delete[] tmpdbs_;
return false;
}
} else {
kc::File::Status sbuf;
if (!kc::File::status(tmppath, &sbuf) || !sbuf.isdir) {
db->set_error(kc::BasicDB::Error::NOREPOS, "no such directory");
delete[] tmpdbs_;
return false;
}
if (!logf("prepare", "started to open temporary databases under %s", tmppath.c_str()))
err = true;
stime = kc::time();
uint32_t pid = getpid() & kc::UINT16MAX;
uint32_t tid = kc::Thread::hash() & kc::UINT16MAX;
uint32_t ts = kc::time() * 1000;
for (size_t i = 0; i < dbnum_; i++) {
std::string childpath =
kc::strprintf("%s%cmr-%04x-%04x-%08x-%03d%ckct", tmppath.c_str(),
kc::File::PATHCHR, pid, tid, ts, (int)(i + 1), kc::File::EXTCHR);
kc::TreeDB* tdb = new kc::TreeDB;
int32_t myopts = kc::TreeDB::TSMALL | kc::TreeDB::TLINEAR;
if (!(opts & XNOCOMP)) myopts |= kc::TreeDB::TCOMPRESS;
tdb->tune_options(myopts);
tdb->tune_buckets(DBBNUM);
tdb->tune_page(DBPSIZ);
tdb->tune_map(DBMSIZ);
tdb->tune_page_cache(DBPCCAP);
tdb->tune_comparator(rcomp_);
if (!tdb->open(childpath,
kc::TreeDB::OWRITER | kc::TreeDB::OCREATE | kc::TreeDB::OTRUNCATE)) {
const kc::BasicDB::Error& e = tdb->error();
db->set_error(e.code(), e.message());
err = true;
}
tmpdbs_[i] = tdb;
}
etime = kc::time();
if (!logf("prepare", "opening temporary databases finished: time=%.6f", etime - stime))
err = true;
if (err) {
for (size_t i = 0; i < dbnum_; i++) {
delete tmpdbs_[i];
}
delete[] tmpdbs_;
return false;
}
}
if (opts & XPARARED) redtasks_ = new ReduceTaskQueue;
if (opts & XPARAFLS) flsths_ = new std::deque;
if (opts & XNOLOCK) {
MapChecker mapchecker;
MapVisitor mapvisitor(this, &mapchecker, count);
mapvisitor.visit_before();
if (!err) {
TimedDB::Cursor* cur = db->cursor();
if (!cur->jump() && cur->error() != kc::BasicDB::Error::NOREC) err = true;
while (!err) {
if (!cur->accept(&mapvisitor, false, true)) {
if (cur->error() != kc::BasicDB::Error::NOREC) err = true;
break;
}
}
delete cur;
}
if (mapvisitor.error()) err = true;
mapvisitor.visit_after();
} else if (opts & XPARAMAP) {
MapChecker mapchecker;
MapVisitor mapvisitor(this, &mapchecker, count);
rlocks_ = new kc::SlottedMutex(RLOCKSLOT);
if (!err && !db->scan_parallel(&mapvisitor, mapthnum_, &mapchecker)) {
db_->set_error(kc::BasicDB::Error::LOGIC, "mapper failed");
err = true;
}
delete rlocks_;
rlocks_ = NULL;
if (mapvisitor.error()) err = true;
} else {
MapChecker mapchecker;
MapVisitor mapvisitor(this, &mapchecker, count);
if (!err && !db->iterate(&mapvisitor, false, &mapchecker)) err = true;
if (mapvisitor.error()) err = true;
}
if (flsths_) {
delete flsths_;
flsths_ = NULL;
}
if (redtasks_) {
delete redtasks_;
redtasks_ = NULL;
}
if (!logf("clean", "closing the temporary databases")) err = true;
stime = kc::time();
for (size_t i = 0; i < dbnum_; i++) {
std::string path = tmpdbs_[i]->path();
if (!tmpdbs_[i]->clear()) {
const kc::BasicDB::Error& e = tmpdbs_[i]->error();
db->set_error(e.code(), e.message());
err = true;
}
if (!tmpdbs_[i]->close()) {
const kc::BasicDB::Error& e = tmpdbs_[i]->error();
db->set_error(e.code(), e.message());
err = true;
}
if (!tmppath.empty()) kc::File::remove(path);
delete tmpdbs_[i];
}
etime = kc::time();
if (!logf("clean", "closing the temporary databases finished: time=%.6f",
etime - stime)) err = true;
delete[] tmpdbs_;
return !err;
}
/**
* Set the storage configurations.
* @param dbnum the number of temporary databases.
* @param clim the limit size of the internal cache.
* @param cbnum the bucket number of the internal cache.
*/
void tune_storage(int32_t dbnum, int64_t clim, int64_t cbnum) {
_assert_(true);
dbnum_ = dbnum > 0 ? dbnum : DEFDBNUM;
if (dbnum_ > MAXDBNUM) dbnum_ = MAXDBNUM;
clim_ = clim > 0 ? clim : DEFCLIM;
cbnum_ = cbnum > 0 ? cbnum : DEFCBNUM;
if (cbnum_ > kc::INT16MAX) cbnum_ = kc::nearbyprime(cbnum_);
}
/**
* Set the thread configurations.
* @param mapthnum the number of threads for the mapper.
* @param redthnum the number of threads for the reducer.
* @param flsthnum the number of threads for the internal flusher.
*/
void tune_thread(int32_t mapthnum, int32_t redthnum, int32_t flsthnum) {
_assert_(true);
mapthnum_ = mapthnum > 0 ? mapthnum : DEFTHNUM;
redthnum_ = redthnum > 0 ? redthnum : DEFTHNUM;
flsthnum_ = flsthnum > 0 ? flsthnum : DEFTHNUM;
}
protected:
/**
* Emit a record from the mapper.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param vbuf the pointer to the value region.
* @param vsiz the size of the value region.
* @return true on success, or false on failure.
*/
bool emit(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ && vbuf && vsiz <= kc::MEMMAXSIZ);
bool err = false;
size_t rsiz = kc::sizevarnum(vsiz) + vsiz;
char stack[kc::NUMBUFSIZ*4];
char* rbuf = rsiz > sizeof(stack) ? new char[rsiz] : stack;
char* wp = rbuf;
wp += kc::writevarnum(rbuf, vsiz);
std::memcpy(wp, vbuf, vsiz);
if (rlocks_) {
size_t bidx = kc::TinyHashMap::hash_record(kbuf, ksiz) % cbnum_;
size_t lidx = bidx % RLOCKSLOT;
rlocks_->lock(lidx);
cache_->append(kbuf, ksiz, rbuf, rsiz);
rlocks_->unlock(lidx);
} else {
cache_->append(kbuf, ksiz, rbuf, rsiz);
}
if (rbuf != stack) delete[] rbuf;
csiz_ += kc::sizevarnum(ksiz) + ksiz + rsiz;
return !err;
}
private:
/**
* Cache flusher.
*/
class FlushThread : public kc::Thread {
public:
/** constructor */
explicit FlushThread(MapReduce* mr, kc::BasicDB* tmpdb,
kc::TinyHashMap* cache, size_t csiz, bool cown) :
mr_(mr), tmpdb_(tmpdb), cache_(cache), csiz_(csiz), cown_(cown), err_(false) {}
/** perform the concrete process */
void run() {
if (!mr_->logf("map", "started to flushing the cache: count=%lld size=%lld",
(long long)cache_->count(), (long long)csiz_)) err_ = true;
double stime = kc::time();
kc::BasicDB* tmpdb = tmpdb_;
kc::TinyHashMap* cache = cache_;
bool cown = cown_;
kc::TinyHashMap::Sorter sorter(cache);
const char* kbuf, *vbuf;
size_t ksiz, vsiz;
while ((kbuf = sorter.get(&ksiz, &vbuf, &vsiz)) != NULL) {
if (!tmpdb->append(kbuf, ksiz, vbuf, vsiz)) {
const kc::BasicDB::Error& e = tmpdb->error();
mr_->db_->set_error(e.code(), e.message());
err_ = true;
}
sorter.step();
if (cown) cache->remove(kbuf, ksiz);
}
double etime = kc::time();
if (!mr_->logf("map", "flushing the cache finished: time=%.6f", etime - stime))
err_ = true;
if (cown) delete cache;
}
/** check the error flag. */
bool error() {
return err_;
}
private:
MapReduce* mr_; ///< driver
kc::BasicDB* tmpdb_; ///< temprary database
kc::TinyHashMap* cache_; ///< cache for emitter
size_t csiz_; ///< current cache size
bool cown_; ///< cache ownership flag
bool err_; ///< error flag
};
/**
* Task queue for parallel reducer.
*/
class ReduceTaskQueue : public kc::TaskQueue {
public:
/**
* Task for parallel reducer.
*/
class ReduceTask : public Task {
friend class ReduceTaskQueue;
public:
/** constructor */
explicit ReduceTask(MapReduce* mr, const char* kbuf, size_t ksiz, const Values& values) :
mr_(mr), key_(kbuf, ksiz), values_(values) {}
private:
MapReduce* mr_; ///< driver
std::string key_; ///< key
Values values_; ///< values
};
/** constructor */
explicit ReduceTaskQueue() {}
private:
/** process a task */
void do_task(Task* task) {
ReduceTask* rtask = (ReduceTask*)task;
ValueIterator iter(rtask->values_.begin(), rtask->values_.end());
if (!rtask->mr_->reduce(rtask->key_.data(), rtask->key_.size(), &iter))
rtask->mr_->redaborted_ = true;
delete rtask;
}
};
/**
* Checker for the map process.
*/
class MapChecker : public kc::BasicDB::ProgressChecker {
public:
/** constructor */
explicit MapChecker() : stop_(false) {}
/** stop the process */
void stop() {
stop_ = true;
}
/** check whether stopped */
bool stopped() {
return stop_;
}
private:
/** check whether stopped */
bool check(const char* name, const char* message, int64_t curcnt, int64_t allcnt) {
return !stop_;
}
bool stop_; ///< flag for stop
};
/**
* Visitor for the map process.
*/
class MapVisitor : public TimedDB::Visitor {
public:
/** constructor */
explicit MapVisitor(MapReduce* mr, MapChecker* checker, int64_t scale) :
mr_(mr), checker_(checker), scale_(scale), stime_(0), err_(false) {}
/** get the error flag */
bool error() {
return err_;
}
/** preprocess the mappter */
void visit_before() {
mr_->dbclock_ = 0;
mr_->cache_ = new kc::TinyHashMap(mr_->cbnum_);
mr_->csiz_ = 0;
if (!mr_->preprocess()) err_ = true;
if (mr_->cache_->count() > 0 && !mr_->flush_cache()) err_ = true;
if (!mr_->logf("map", "started the map process: scale=%lld", (long long)scale_))
err_ = true;
stime_ = kc::time();
}
/** postprocess the mappter and call the reducer */
void visit_after() {
if (mr_->cache_->count() > 0 && !mr_->flush_cache()) err_ = true;
double etime = kc::time();
if (!mr_->logf("map", "the map process finished: time=%.6f", etime - stime_))
err_ = true;
if (!mr_->midprocess()) err_ = true;
if (mr_->cache_->count() > 0 && !mr_->flush_cache()) err_ = true;
delete mr_->cache_;
if (mr_->flsths_ && !mr_->flsths_->empty()) {
std::deque::iterator flthit = mr_->flsths_->begin();
std::deque::iterator flthitend = mr_->flsths_->end();
while (flthit != flthitend) {
FlushThread* flth = *flthit;
flth->join();
if (flth->error()) err_ = true;
delete flth;
++flthit;
}
}
if (!err_ && !mr_->execute_reduce()) err_ = true;
if (!mr_->postprocess()) err_ = true;
}
private:
/** visit a record */
const char* visit_full(const char* kbuf, size_t ksiz,
const char* vbuf, size_t vsiz, size_t* sp, int64_t* xtp) {
if (!mr_->map(kbuf, ksiz, vbuf, vsiz)) {
checker_->stop();
err_ = true;
}
if (mr_->rlocks_) {
if (mr_->csiz_ >= mr_->clim_) {
mr_->rlocks_->lock_all();
if (mr_->csiz_ >= mr_->clim_ && !mr_->flush_cache()) {
checker_->stop();
err_ = true;
}
mr_->rlocks_->unlock_all();
}
} else {
if (mr_->csiz_ >= mr_->clim_ && !mr_->flush_cache()) {
checker_->stop();
err_ = true;
}
}
return NOP;
}
MapReduce* mr_; ///< driver
MapChecker* checker_; ///< checker
int64_t scale_; ///< number of records
double stime_; ///< start time
bool err_; ///< error flag
};
/**
* Front line of a merging list.
*/
struct MergeLine {
kc::BasicDB::Cursor* cur; ///< cursor
kc::Comparator* rcomp; ///< record comparator
char* kbuf; ///< pointer to the key
size_t ksiz; ///< size of the key
const char* vbuf; ///< pointer to the value
size_t vsiz; ///< size of the value
/** comparing operator */
bool operator <(const MergeLine& right) const {
return rcomp->compare(kbuf, ksiz, right.kbuf, right.ksiz) > 0;
}
};
/**
* Process a log message.
* @param name the name of the event.
* @param format the printf-like format string.
* @param ... used according to the format string.
* @return true on success, or false on failure.
*/
bool logf(const char* name, const char* format, ...) {
_assert_(name && format);
va_list ap;
va_start(ap, format);
std::string message;
kc::vstrprintf(&message, format, ap);
va_end(ap);
return log(name, message.c_str());
}
/**
* Flush all cache records.
* @return true on success, or false on failure.
*/
bool flush_cache() {
_assert_(true);
bool err = false;
kc::BasicDB* tmpdb = tmpdbs_[dbclock_];
dbclock_ = (dbclock_ + 1) % dbnum_;
if (flsths_) {
size_t num = flsths_->size();
if (num >= flsthnum_ || num >= dbnum_) {
FlushThread* flth = flsths_->front();
flsths_->pop_front();
flth->join();
if (flth->error()) err = true;
delete flth;
}
FlushThread* flth = new FlushThread(this, tmpdb, cache_, csiz_, true);
cache_ = new kc::TinyHashMap(cbnum_);
csiz_ = 0;
flth->start();
flsths_->push_back(flth);
} else {
FlushThread flth(this, tmpdb, cache_, csiz_, false);
flth.run();
if (flth.error()) err = true;
cache_->clear();
csiz_ = 0;
}
return !err;
}
/**
* Execute the reduce part.
* @return true on success, or false on failure.
*/
bool execute_reduce() {
bool err = false;
int64_t scale = 0;
for (size_t i = 0; i < dbnum_; i++) {
scale += tmpdbs_[i]->count();
}
if (!logf("reduce", "started the reduce process: scale=%lld", (long long)scale)) err = true;
double stime = kc::time();
if (redtasks_) redtasks_->start(redthnum_);
std::priority_queue lines;
for (size_t i = 0; i < dbnum_; i++) {
MergeLine line;
line.cur = tmpdbs_[i]->cursor();
line.rcomp = rcomp_;
line.cur->jump();
line.kbuf = line.cur->get(&line.ksiz, &line.vbuf, &line.vsiz, true);
if (line.kbuf) {
lines.push(line);
} else {
delete line.cur;
}
}
char* lkbuf = NULL;
size_t lksiz = 0;
Values values;
while (!err && !lines.empty()) {
MergeLine line = lines.top();
lines.pop();
if (lkbuf && (lksiz != line.ksiz || std::memcmp(lkbuf, line.kbuf, lksiz))) {
if (!call_reducer(lkbuf, lksiz, values)) err = true;
values.clear();
}
values.push_back(std::string(line.vbuf, line.vsiz));
delete[] lkbuf;
lkbuf = line.kbuf;
lksiz = line.ksiz;
line.kbuf = line.cur->get(&line.ksiz, &line.vbuf, &line.vsiz, true);
if (line.kbuf) {
lines.push(line);
} else {
delete line.cur;
}
}
if (lkbuf) {
if (!err && !call_reducer(lkbuf, lksiz, values)) err = true;
values.clear();
delete[] lkbuf;
}
while (!lines.empty()) {
MergeLine line = lines.top();
lines.pop();
delete[] line.kbuf;
delete line.cur;
}
if (redtasks_) redtasks_->finish();
double etime = kc::time();
if (!logf("reduce", "the reduce process finished: time=%.6f", etime - stime)) err = true;
return !err;
}
/**
* Call the reducer.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param values a vector of the values.
* @return true on success, or false on failure.
*/
bool call_reducer(const char* kbuf, size_t ksiz, const Values& values) {
_assert_(kbuf && ksiz <= kc::MEMMAXSIZ);
if (redtasks_) {
if (redaborted_) return false;
ReduceTaskQueue::ReduceTask* task =
new ReduceTaskQueue::ReduceTask(this, kbuf, ksiz, values);
redtasks_->add_task(task);
return true;
}
bool err = false;
ValueIterator iter(values.begin(), values.end());
if (!reduce(kbuf, ksiz, &iter)) err = true;
return !err;
}
/** Dummy constructor to forbid the use. */
MapReduce(const MapReduce&);
/** Dummy Operator to forbid the use. */
MapReduce& operator =(const MapReduce&);
/** The internal database. */
TimedDB* db_;
/** The record comparator. */
kc::Comparator* rcomp_;
/** The temporary databases. */
kc::BasicDB** tmpdbs_;
/** The number of temporary databases. */
size_t dbnum_;
/** The logical clock for temporary databases. */
int64_t dbclock_;
/** The number of the mapper threads. */
size_t mapthnum_;
/** The number of the reducer threads. */
size_t redthnum_;
/** The number of the flusher threads. */
size_t flsthnum_;
/** The cache for emitter. */
kc::TinyHashMap* cache_;
/** The current size of the cache for emitter. */
int64_t csiz_;
/** The limit size of the cache for emitter. */
int64_t clim_;
/** The bucket number of the cache for emitter. */
int64_t cbnum_;
/** The flush threads. */
std::deque* flsths_;
/** The task queue for parallel reducer. */
kc::TaskQueue* redtasks_;
/** The flag whether aborted. */
bool redaborted_;
/** The whole lock. */
kc::SlottedMutex* rlocks_;
};
} // common namespace
#endif // duplication check
// END OF FILE
kyototycoon-0.9.56/ktserver.cc 0000644 0001750 0001750 00000343333 11757471602 015415 0 ustar mikio mikio /*************************************************************************************************
* A handy cache/storage server
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or 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 General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see .
*************************************************************************************************/
#include "cmdcommon.h"
enum { // enumeration for operation counting
CNTSET, // setting operations
CNTSETMISS, // misses of setting operations
CNTREMOVE, // removing operations
CNTREMOVEMISS, // misses of removing operations
CNTGET, // getting operations
CNTGETMISS, // misses of getting operations
CNTSCRIPT, // scripting operations
CNTMISC // miscellaneous operations
};
typedef uint64_t OpCount[CNTMISC+1]; // counters per thread
// global variables
const char* g_progname; // program name
int32_t g_procid; // process ID number
double g_starttime; // start time
bool g_daemon; // daemon flag
kt::RPCServer* g_serv; // running RPC server
bool g_restart; // restart flag
// function prototypes
int main(int argc, char** argv);
static void usage();
static void killserver(int signum);
static int32_t run(int argc, char** argv);
static int32_t proc(const std::vector& dbpaths,
const char* host, int32_t port, double tout, int32_t thnum,
const char* logpath, uint32_t logkinds,
const char* ulogpath, int64_t ulim, double uasi,
int32_t sid, int32_t omode, double asi, bool ash,
const char* bgspath, double bgsi, kc::Compressor* bgscomp, bool dmn,
const char* pidpath, const char* cmdpath, const char* scrpath,
const char* mhost, int32_t mport, const char* rtspath, double riv,
const char* plsvpath, const char* plsvex, const char* pldbpath);
static bool dosnapshot(const char* bgspath, kc::Compressor* bgscomp,
kt::TimedDB* dbs, int32_t dbnum, kt::RPCServer* serv);
// logger implementation
class Logger : public kt::RPCServer::Logger {
public:
// constructor
explicit Logger() : strm_(NULL), lock_() {}
// destructor
~Logger() {
if (strm_) close();
}
// open the stream
bool open(const char* path) {
if (strm_) return false;
if (path && *path != '\0' && std::strcmp(path, "-")) {
std::ofstream* strm = new std::ofstream;
strm->open(path, std::ios_base::out | std::ios_base::binary | std::ios_base::app);
if (!*strm) {
delete strm;
return false;
}
strm_ = strm;
} else {
strm_ = &std::cout;
}
return true;
}
// close the stream
void close() {
if (!strm_) return;
if (strm_ != &std::cout) delete strm_;
strm_ = NULL;
}
// process a log message.
void log(Kind kind, const char* message) {
if (!strm_) return;
char date[48];
kt::datestrwww(kc::nan(), kc::INT32MAX, 6, date);
const char* kstr = "MISC";
switch (kind) {
case kt::RPCServer::Logger::DEBUG: kstr = "DEBUG"; break;
case kt::RPCServer::Logger::INFO: kstr = "INFO"; break;
case kt::RPCServer::Logger::SYSTEM: kstr = "SYSTEM"; break;
case kt::RPCServer::Logger::ERROR: kstr = "ERROR"; break;
}
lock_.lock();
*strm_ << date << ": [" << kstr << "]: " << message << "\n";
strm_->flush();
lock_.unlock();
}
private:
std::ostream* strm_;
kc::Mutex lock_;
};
// database logger implementation
class DBLogger : public kc::BasicDB::Logger {
public:
// constructor
explicit DBLogger(::Logger* logger, uint32_t kinds) : logger_(logger), kinds_(kinds) {}
// process a log message.
void log(const char* file, int32_t line, const char* func,
kc::BasicDB::Logger::Kind kind, const char* message) {
kt::RPCServer::Logger::Kind rkind;
switch (kind) {
default: rkind = kt::RPCServer::Logger::DEBUG; break;
case kc::BasicDB::Logger::INFO: rkind = kt::RPCServer::Logger::INFO; break;
case kc::BasicDB::Logger::WARN: rkind = kt::RPCServer::Logger::SYSTEM; break;
case kc::BasicDB::Logger::ERROR: rkind = kt::RPCServer::Logger::ERROR; break;
}
if (!(rkind & kinds_)) return;
std::string lmsg;
kc::strprintf(&lmsg, "[DB]: %s", message);
logger_->log(rkind, lmsg.c_str());
}
private:
::Logger* logger_;
uint32_t kinds_;
};
// replication slave implemantation
class Slave : public kc::Thread {
friend class Worker;
public:
// constructor
explicit Slave(uint16_t sid, const char* rtspath, const char* host, int32_t port, double riv,
kt::RPCServer* serv, kt::TimedDB* dbs, int32_t dbnum,
kt::UpdateLogger* ulog, DBUpdateLogger* ulogdbs) :
lock_(), sid_(sid), rtspath_(rtspath), host_(""), port_(port), riv_(riv),
serv_(serv), dbs_(dbs), dbnum_(dbnum), ulog_(ulog), ulogdbs_(ulogdbs),
wrts_(kc::UINT64MAX), rts_(0), alive_(true), hup_(false) {
if (host) host_ = host;
}
// stop the slave
void stop() {
alive_ = false;
}
// restart the slave
void restart() {
hup_ = true;
}
// set the configuration of the master
void set_master(const std::string& host, int32_t port, uint64_t ts, double iv) {
kc::ScopedSpinLock lock(&lock_);
host_ = host;
port_ = port;
wrts_ = ts;
if (iv >= 0) riv_ = iv;
}
// get the host name of the master
std::string host() {
kc::ScopedSpinLock lock(&lock_);
return host_;
}
// get the port number name of the master
int32_t port() {
kc::ScopedSpinLock lock(&lock_);
return port_;
}
// get the replication time stamp
uint64_t rts() {
return rts_;
}
// get the replication interval
double riv() {
return riv_;
}
private:
static const int32_t DUMMYFREQ = 256;
static const size_t RTSFILESIZ = 21;
// perform replication
void run(void) {
if (!rtspath_) return;
kc::File rtsfile;
if (!rtsfile.open(rtspath_, kc::File::OWRITER | kc::File::OCREATE, kc::NUMBUFSIZ) ||
!rtsfile.truncate(RTSFILESIZ)) {
serv_->log(Logger::ERROR, "opening the RTS file failed: path=%s", rtspath_);
return;
}
rts_ = read_rts(&rtsfile);
write_rts(&rtsfile, rts_);
kc::Thread::sleep(0.2);
bool deferred = false;
while (true) {
lock_.lock();
std::string host = host_;
int32_t port = port_;
uint64_t wrts = wrts_;
lock_.unlock();
if (!host.empty()) {
if (wrts != kc::UINT64MAX) {
lock_.lock();
wrts_ = kc::UINT64MAX;
rts_ = wrts;
write_rts(&rtsfile, rts_);
lock_.unlock();
}
kt::ReplicationClient rc;
if (rc.open(host, port, 60, rts_, sid_)) {
serv_->log(Logger::SYSTEM, "replication started: host=%s port=%d rts=%llu",
host.c_str(), port, (unsigned long long)rts_);
hup_ = false;
double rivsum = 0;
while (alive_ && !hup_ && rc.alive()) {
size_t msiz;
uint64_t mts;
char* mbuf = rc.read(&msiz, &mts);
if (mbuf) {
if (msiz > 0) {
size_t rsiz;
uint16_t rsid, rdbid;
const char* rbuf = DBUpdateLogger::parse(mbuf, msiz, &rsiz, &rsid, &rdbid);
if (rbuf && rsid != sid_ && rdbid < dbnum_) {
kt::TimedDB* db = dbs_ + rdbid;
DBUpdateLogger* ulogdb = ulogdbs_ ? ulogdbs_ + rdbid : NULL;
if (ulogdb) ulogdb->set_rsid(rsid);
if (!db->recover(rbuf, rsiz)) {
const kc::BasicDB::Error& e = db->error();
serv_->log(Logger::ERROR, "recovering a database failed: %s: %s",
e.name(), e.message());
}
if (ulogdb) ulogdb->clear_rsid();
}
rivsum += riv_;
} else {
rivsum += riv_ * DUMMYFREQ / 4;
}
delete[] mbuf;
while (rivsum > 100 && alive_ && !hup_ && rc.alive()) {
kc::Thread::sleep(0.1);
rivsum -= 100;
}
}
if (mts > rts_) rts_ = mts;
}
rc.close();
serv_->log(Logger::SYSTEM, "replication finished: host=%s port=%d",
host.c_str(), port);
write_rts(&rtsfile, rts_);
deferred = false;
} else {
if (!deferred) serv_->log(Logger::SYSTEM, "replication was deferred: host=%s port=%d",
host.c_str(), port);
deferred = true;
}
}
if (alive_) {
kc::Thread::sleep(1);
} else {
break;
}
}
if (!rtsfile.close()) serv_->log(Logger::ERROR, "closing the RTS file failed");
}
// read the replication time stamp
uint64_t read_rts(kc::File* file) {
char buf[RTSFILESIZ];
file->read_fast(0, buf, RTSFILESIZ);
buf[sizeof(buf)-1] = '\0';
return kc::atoi(buf);
}
// write the replication time stamp
void write_rts(kc::File* file, uint64_t rts) {
char buf[kc::NUMBUFSIZ];
std::sprintf(buf, "%020llu\n", (unsigned long long)rts);
if (!file->write_fast(0, buf, RTSFILESIZ))
serv_->log(Logger::SYSTEM, "writing the time stamp failed");
}
kc::SpinLock lock_;
const uint16_t sid_;
const char* const rtspath_;
std::string host_;
int32_t port_;
double riv_;
kt::RPCServer* const serv_;
kt::TimedDB* const dbs_;
const int32_t dbnum_;
kt::UpdateLogger* const ulog_;
DBUpdateLogger* const ulogdbs_;
uint64_t wrts_;
uint64_t rts_;
bool alive_;
bool hup_;
};
// plug-in server driver
class PlugInDriver : public kc::Thread {
public:
// constructor
explicit PlugInDriver(kt::PluggableServer* serv) : serv_(serv), error_(false) {}
// get the error flag
bool error() {
return error_;
}
private:
// perform service
void run(void) {
kc::Thread::sleep(0.4);
if (serv_->start()) {
if (!serv_->finish()) error_ = true;
} else {
error_ = true;
}
}
kt::PluggableServer* serv_;
bool error_;
};
// worker implementation
class Worker : public kt::RPCServer::Worker {
private:
class SLS;
typedef kt::RPCClient::ReturnValue RV;
public:
// constructor
explicit Worker(int32_t thnum, kc::CondMap* condmap, kt::TimedDB* dbs, int32_t dbnum,
const std::map& dbmap, int32_t omode,
double asi, bool ash, const char* bgspath, double bgsi,
kc::Compressor* bgscomp, kt::UpdateLogger* ulog, DBUpdateLogger* ulogdbs,
const char* cmdpath, ScriptProcessor* scrprocs, OpCount* opcounts) :
thnum_(thnum), condmap_(condmap), dbs_(dbs), dbnum_(dbnum), dbmap_(dbmap),
omode_(omode), asi_(asi), ash_(ash), bgspath_(bgspath), bgsi_(bgsi), bgscomp_(bgscomp),
ulog_(ulog), ulogdbs_(ulogdbs), cmdpath_(cmdpath), scrprocs_(scrprocs),
opcounts_(opcounts), idlecnt_(0), asnext_(0), bgsnext_(0), slave_(NULL) {
asnext_ = kc::time() + asi_;
bgsnext_ = kc::time() + bgsi_;
}
// set miscellaneous configuration
void set_misc_conf(Slave* slave) {
slave_ = slave;
}
private:
// process each request of RPC.
RV process(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::string& name,
const std::map& inmap,
std::map& outmap) {
size_t rsiz;
const char* rp = kt::strmapget(inmap, "WAIT", &rsiz);
if (rp) {
std::string condname(rp, rsiz);
rp = kt::strmapget(inmap, "WAITTIME");
double wsec = rp ? kc::atof(rp) : 0.0;
if (wsec <= 0) wsec = DEFTOUT;
kt::ThreadedServer* thserv = serv->reveal_core()->reveal_core();
if (!condmap_->wait(condname, wsec) || thserv->aborted()) {
set_message(outmap, "ERROR", "the condition timed out");
return kt::RPCClient::RVETIMEOUT;
}
}
int32_t dbidx = 0;
rp = kt::strmapget(inmap, "DB");
if (rp && *rp != '\0') {
dbidx = -1;
if (*rp >= '0' && *rp <= '9') {
dbidx = kc::atoi(rp);
} else {
std::map::const_iterator it = dbmap_.find(rp);
if (it != dbmap_.end()) dbidx = it->second;
}
}
kt::TimedDB* db = dbidx >= 0 && dbidx < dbnum_ ? dbs_ + dbidx : NULL;
int64_t curid = -1;
rp = kt::strmapget(inmap, "CUR");
if (rp && *rp >= '0' && *rp <= '9') curid = kc::atoi(rp);
kt::TimedDB::Cursor* cur = NULL;
if (curid >= 0) {
SLS* sls = SLS::create(sess);
std::map::iterator it = sls->curs_.find(curid);
if (it == sls->curs_.end()) {
if (db) {
cur = db->cursor();
sls->curs_[curid] = cur;
}
} else {
cur = it->second;
if (name == "cur_delete") {
sls->curs_.erase(curid);
delete cur;
return kt::RPCClient::RVSUCCESS;
}
}
}
RV rv;
if (name == "void") {
rv = do_void(serv, sess, inmap, outmap);
} else if (name == "echo") {
rv = do_echo(serv, sess, inmap, outmap);
} else if (name == "report") {
rv = do_report(serv, sess, inmap, outmap);
} else if (name == "play_script") {
rv = do_play_script(serv, sess, inmap, outmap);
} else if (name == "tune_replication") {
rv = do_tune_replication(serv, sess, inmap, outmap);
} else if (name == "ulog_list") {
rv = do_ulog_list(serv, sess, inmap, outmap);
} else if (name == "ulog_remove") {
rv = do_ulog_remove(serv, sess, inmap, outmap);
} else if (name == "status") {
rv = do_status(serv, sess, db, inmap, outmap);
} else if (name == "clear") {
rv = do_clear(serv, sess, db, inmap, outmap);
} else if (name == "synchronize") {
rv = do_synchronize(serv, sess, db, inmap, outmap);
} else if (name == "set") {
rv = do_set(serv, sess, db, inmap, outmap);
} else if (name == "add") {
rv = do_add(serv, sess, db, inmap, outmap);
} else if (name == "replace") {
rv = do_replace(serv, sess, db, inmap, outmap);
} else if (name == "append") {
rv = do_append(serv, sess, db, inmap, outmap);
} else if (name == "increment") {
rv = do_increment(serv, sess, db, inmap, outmap);
} else if (name == "increment_double") {
rv = do_increment_double(serv, sess, db, inmap, outmap);
} else if (name == "cas") {
rv = do_cas(serv, sess, db, inmap, outmap);
} else if (name == "remove") {
rv = do_remove(serv, sess, db, inmap, outmap);
} else if (name == "get") {
rv = do_get(serv, sess, db, inmap, outmap);
} else if (name == "check") {
rv = do_check(serv, sess, db, inmap, outmap);
} else if (name == "seize") {
rv = do_seize(serv, sess, db, inmap, outmap);
} else if (name == "set_bulk") {
rv = do_set_bulk(serv, sess, db, inmap, outmap);
} else if (name == "remove_bulk") {
rv = do_remove_bulk(serv, sess, db, inmap, outmap);
} else if (name == "get_bulk") {
rv = do_get_bulk(serv, sess, db, inmap, outmap);
} else if (name == "vacuum") {
rv = do_vacuum(serv, sess, db, inmap, outmap);
} else if (name == "match_prefix") {
rv = do_match_prefix(serv, sess, db, inmap, outmap);
} else if (name == "match_regex") {
rv = do_match_regex(serv, sess, db, inmap, outmap);
} else if (name == "match_similar") {
rv = do_match_similar(serv, sess, db, inmap, outmap);
} else if (name == "cur_jump") {
rv = do_cur_jump(serv, sess, cur, inmap, outmap);
} else if (name == "cur_jump_back") {
rv = do_cur_jump_back(serv, sess, cur, inmap, outmap);
} else if (name == "cur_step") {
rv = do_cur_step(serv, sess, cur, inmap, outmap);
} else if (name == "cur_step_back") {
rv = do_cur_step_back(serv, sess, cur, inmap, outmap);
} else if (name == "cur_set_value") {
rv = do_cur_set_value(serv, sess, cur, inmap, outmap);
} else if (name == "cur_remove") {
rv = do_cur_remove(serv, sess, cur, inmap, outmap);
} else if (name == "cur_get_key") {
rv = do_cur_get_key(serv, sess, cur, inmap, outmap);
} else if (name == "cur_get_value") {
rv = do_cur_get_value(serv, sess, cur, inmap, outmap);
} else if (name == "cur_get") {
rv = do_cur_get(serv, sess, cur, inmap, outmap);
} else if (name == "cur_seize") {
rv = do_cur_seize(serv, sess, cur, inmap, outmap);
} else {
set_message(outmap, "ERROR", "not implemented: %s", name.c_str());
rv = kt::RPCClient::RVENOIMPL;
}
rp = kt::strmapget(inmap, "SIGNAL", &rsiz);
if (rp) {
std::string condname(rp, rsiz);
rp = kt::strmapget(inmap, "SIGNALBROAD");
bool broad = rp ? true : false;
size_t wnum = broad ? condmap_->broadcast(condname) : condmap_->signal(condname);
set_message(outmap, "SIGNALED", "%lld", (long long)wnum);
}
return rv;
}
// process each request of the others.
int32_t process(kt::HTTPServer* serv, kt::HTTPServer::Session* sess,
const std::string& path, kt::HTTPClient::Method method,
const std::map& reqheads,
const std::string& reqbody,
std::map& resheads,
std::string& resbody,
const std::map& misc) {
const char* pstr = path.c_str();
if (*pstr == '/') pstr++;
int32_t dbidx = 0;
const char* rp = std::strchr(pstr, '/');
if (rp) {
std::string dbexpr(pstr, rp - pstr);
pstr = rp + 1;
if (*pstr == '/') pstr++;
size_t desiz;
char* destr = kc::urldecode(dbexpr.c_str(), &desiz);
if (*destr != '\0') {
dbidx = -1;
if (*destr >= '0' && *destr <= '9') {
dbidx = kc::atoi(destr);
} else {
std::map::const_iterator it = dbmap_.find(destr);
if (it != dbmap_.end()) dbidx = it->second;
}
}
delete[] destr;
}
if (dbidx < 0 || dbidx >= dbnum_) {
resbody.append("no such database\n");
return 400;
}
kt::TimedDB* db = dbs_ + dbidx;
size_t ksiz;
char* kbuf = kc::urldecode(pstr, &ksiz);
int32_t code;
switch (method) {
case kt::HTTPClient::MGET: {
code = do_rest_get(serv, sess, db, kbuf, ksiz,
reqheads, reqbody, resheads, resbody, misc);
break;
}
case kt::HTTPClient::MHEAD: {
code = do_rest_head(serv, sess, db, kbuf, ksiz,
reqheads, reqbody, resheads, resbody, misc);
break;
}
case kt::HTTPClient::MPUT: {
code = do_rest_put(serv, sess, db, kbuf, ksiz,
reqheads, reqbody, resheads, resbody, misc);
break;
}
case kt::HTTPClient::MDELETE: {
code = do_rest_delete(serv, sess, db, kbuf, ksiz,
reqheads, reqbody, resheads, resbody, misc);
break;
}
default: {
code = 501;
break;
}
}
delete[] kbuf;
return code;
}
// process each binary request
bool process_binary(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) {
int32_t magic = sess->receive_byte();
const char* cmd;
bool rv;
switch (magic) {
case kt::RemoteDB::BMREPLICATION: {
cmd = "bin_replication";
rv = do_bin_replication(serv, sess);
break;
}
case kt::RemoteDB::BMPLAYSCRIPT: {
cmd = "bin_play_script";
rv = do_bin_play_script(serv, sess);
break;
}
case kt::RemoteDB::BMSETBULK: {
cmd = "bin_set_bulk";
rv = do_bin_set_bulk(serv, sess);
break;
}
case kt::RemoteDB::BMREMOVEBULK: {
cmd = "bin_remove_bulk";
rv = do_bin_remove_bulk(serv, sess);
break;
}
case kt::RemoteDB::BMGETBULK: {
cmd = "bin_get_bulk";
rv = do_bin_get_bulk(serv, sess);
break;
}
default: {
cmd = "bin_unknown";
rv = false;
break;
}
}
std::string expr = sess->expression();
serv->log(kt::ThreadedServer::Logger::INFO, "(%s): %s: %d", expr.c_str(), cmd, rv);
return rv;
}
// process each idle event
void process_idle(kt::RPCServer* serv) {
if (omode_ & kc::BasicDB::OWRITER) {
int32_t dbidx = idlecnt_++ % dbnum_;
kt::TimedDB* db = dbs_ + dbidx;
kt::ThreadedServer* thserv = serv->reveal_core()->reveal_core();
for (int32_t i = 0; i < 4; i++) {
if (thserv->task_count() > 0) break;
if (!db->vacuum(2)) {
const kc::BasicDB::Error& e = db->error();
log_db_error(serv, e);
break;
}
kc::Thread::yield();
}
}
}
// process each timer event
void process_timer(kt::RPCServer* serv) {
if (asi_ > 0 && (omode_ & kc::BasicDB::OWRITER) && kc::time() >= asnext_) {
serv->log(Logger::INFO, "synchronizing databases");
for (int32_t i = 0; i < dbnum_; i++) {
kt::TimedDB* db = dbs_ + i;
if (!db->synchronize(ash_)) {
const kc::BasicDB::Error& e = db->error();
log_db_error(serv, e);
break;
}
kc::Thread::yield();
}
asnext_ = kc::time() + asi_;
}
if (bgspath_ && bgsi_ > 0 && kc::time() >= bgsnext_) {
serv->log(Logger::INFO, "snapshotting databases");
dosnapshot(bgspath_, bgscomp_, dbs_, dbnum_, serv);
bgsnext_ = kc::time() + bgsi_;
}
}
// process the starting event
void process_start(kt::RPCServer* serv) {
kt::maskthreadsignal();
}
// set the error message
void set_message(std::map& outmap, const char* key,
const char* format, ...) {
std::string message;
va_list ap;
va_start(ap, format);
kc::vstrprintf(&message, format, ap);
va_end(ap);
outmap[key] = message;
}
// set the database error message
void set_db_error(std::map& outmap, const kc::BasicDB::Error& e) {
set_message(outmap, "ERROR", "DB: %d: %s: %s", e.code(), e.name(), e.message());
}
// log the database error message
void log_db_error(kt::RPCServer* serv, const kc::BasicDB::Error& e) {
log_db_error(serv->reveal_core(), e);
}
// log the database error message
void log_db_error(kt::HTTPServer* serv, const kc::BasicDB::Error& e) {
serv->log(Logger::ERROR, "database error: %d: %s: %s", e.code(), e.name(), e.message());
}
// process the void procedure
RV do_void(kt::RPCServer* serv, kt::RPCServer::Session* sess,
const std::map& inmap,
std::map& outmap) {
return kt::RPCClient::RVSUCCESS;
}
// process the echo procedure
RV do_echo(kt::RPCServer* serv, kt::RPCServer::Session* sess,
const std::map& inmap,
std::map& outmap) {
outmap.insert(inmap.begin(), inmap.end());
return kt::RPCClient::RVSUCCESS;
}
// process the report procedure
RV do_report(kt::RPCServer* serv, kt::RPCServer::Session* sess,
const std::map& inmap,
std::map& outmap) {
int64_t totalcount = 0;
int64_t totalsize = 0;
for (int32_t i = 0; i < dbnum_; i++) {
int64_t count = dbs_[i].count();
int64_t size = dbs_[i].size();
std::string key;
kc::strprintf(&key, "db_%d", i);
set_message(outmap, key.c_str(), "count=%lld size=%lld path=%s",
(long long)count, (long long)size, dbs_[i].path().c_str());
totalcount += count;
totalsize += size;
}
set_message(outmap, "db_total_count", "%lld", (long long)totalcount);
set_message(outmap, "db_total_size", "%lld", (long long)totalsize);
kt::ThreadedServer* thserv = serv->reveal_core()->reveal_core();
set_message(outmap, "serv_conn_count", "%lld", (long long)thserv->connection_count());
set_message(outmap, "serv_task_count", "%lld", (long long)thserv->task_count());
set_message(outmap, "serv_thread_count", "%lld", (long long)thnum_);
double ctime = kc::time();
set_message(outmap, "serv_current_time", "%.6f", ctime);
set_message(outmap, "serv_running_term", "%.6f", ctime - g_starttime);
set_message(outmap, "serv_proc_id", "%d", g_procid);
std::map sysinfo;
kc::getsysinfo(&sysinfo);
std::map::iterator it = sysinfo.begin();
std::map::iterator itend = sysinfo.end();
while (it != itend) {
std::string key;
kc::strprintf(&key, "sys_%s", it->first.c_str());
set_message(outmap, key.c_str(), it->second.c_str());
++it;
}
const std::string& mhost = slave_->host();
if (!mhost.empty()) {
set_message(outmap, "repl_master_host", "%s", mhost.c_str());
set_message(outmap, "repl_master_port", "%d", slave_->port());
uint64_t rts = slave_->rts();
set_message(outmap, "repl_timestamp", "%llu", (unsigned long long)rts);
set_message(outmap, "repl_interval", "%.6f", slave_->riv());
uint64_t cc = kt::UpdateLogger::clock_pure();
uint64_t delay = cc > rts ? cc - rts : 0;
set_message(outmap, "repl_delay", "%.6f", delay / 1000000000.0);
}
OpCount ocsum;
for (int32_t i = 0; i <= CNTMISC; i++) {
ocsum[i] = 0;
}
for (int32_t i = 0; i < thnum_; i++) {
for (int32_t j = 0; j <= CNTMISC; j++) {
ocsum[j] += opcounts_[i][j];
}
}
set_message(outmap, "cnt_set", "%llu", (unsigned long long)ocsum[CNTSET]);
set_message(outmap, "cnt_set_misses", "%llu", (unsigned long long)ocsum[CNTSETMISS]);
set_message(outmap, "cnt_remove", "%llu", (unsigned long long)ocsum[CNTREMOVE]);
set_message(outmap, "cnt_remove_misses", "%llu", (unsigned long long)ocsum[CNTREMOVEMISS]);
set_message(outmap, "cnt_get", "%llu", (unsigned long long)ocsum[CNTGET]);
set_message(outmap, "cnt_get_misses", "%llu", (unsigned long long)ocsum[CNTGETMISS]);
set_message(outmap, "cnt_script", "%llu", (unsigned long long)ocsum[CNTSCRIPT]);
set_message(outmap, "cnt_misc", "%llu", (unsigned long long)ocsum[CNTMISC]);
set_message(outmap, "conf_kt_version", "%s (%d.%d)", kt::VERSION, kt::LIBVER, kt::LIBREV);
set_message(outmap, "conf_kt_features", "%s", kt::FEATURES);
set_message(outmap, "conf_kc_version", "%s (%d.%d)", kc::VERSION, kc::LIBVER, kc::LIBREV);
set_message(outmap, "conf_kc_features", "%s", kc::FEATURES);
set_message(outmap, "conf_os_name", "%s", kc::OSNAME);
return kt::RPCClient::RVSUCCESS;
}
// process the play_script procedure
RV do_play_script(kt::RPCServer* serv, kt::RPCServer::Session* sess,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!scrprocs_) {
set_message(outmap, "ERROR", "the scripting extention is disabled");
return kt::RPCClient::RVENOIMPL;
}
ScriptProcessor* scrproc = scrprocs_ + thid;
const char* nstr = kt::strmapget(inmap, "name");
if (!nstr || *nstr == '\0' || !kt::strisalnum(nstr)) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
std::map scrinmap;
std::map::const_iterator it = inmap.begin();
std::map::const_iterator itend = inmap.end();
while (it != itend) {
const char* kbuf = it->first.data();
size_t ksiz = it->first.size();
if (ksiz > 0 && *kbuf == '_') {
std::string key(kbuf + 1, ksiz - 1);
scrinmap[key] = it->second;
}
++it;
}
opcounts_[thid][CNTSCRIPT]++;
std::map scroutmap;
RV rv = scrproc->call(nstr, scrinmap, scroutmap);
if (rv == kt::RPCClient::RVSUCCESS) {
it = scroutmap.begin();
itend = scroutmap.end();
while (it != itend) {
std::string key = "_";
key.append(it->first);
outmap[key] = it->second;
++it;
}
} else if (rv == kt::RPCClient::RVENOIMPL) {
set_message(outmap, "ERROR", "no such scripting procedure");
} else {
set_message(outmap, "ERROR", "the scripting procedure failed");
}
return rv;
}
// process the tune_replication procedure
RV do_tune_replication(kt::RPCServer* serv, kt::RPCServer::Session* sess,
const std::map& inmap,
std::map& outmap) {
if (!slave_->rtspath_) {
set_message(outmap, "ERROR", "the RTS file is not set");
return kt::RPCClient::RVENOIMPL;
}
const char* host = kt::strmapget(inmap, "host");
if (!host) host = "";
const char* rp = kt::strmapget(inmap, "port");
int32_t port = rp ? kc::atoi(rp) : 0;
if (port < 1) port = kt::DEFPORT;
rp = kt::strmapget(inmap, "ts");
uint64_t ts = kc::UINT64MAX;
if (rp) {
if (!std::strcmp(rp, "now")) {
ts = kt::UpdateLogger::clock_pure();
} else {
ts = kc::atoi(rp);
}
}
rp = kt::strmapget(inmap, "iv");
double iv = rp ? kc::atof(rp) : -1;
char tsstr[kc::NUMBUFSIZ];
if (ts == kc::UINT64MAX) {
std::sprintf(tsstr, "*");
} else {
std::sprintf(tsstr, "%llu", (unsigned long long)ts);
}
char ivstr[kc::NUMBUFSIZ];
if (iv < 0) {
std::sprintf(ivstr, "*");
} else {
std::sprintf(ivstr, "%.6f", iv);
}
serv->log(Logger::SYSTEM, "replication setting was modified: host=%s port=%d ts=%s iv=%s",
host, port, tsstr, ivstr);
slave_->set_master(host, port, ts, iv);
slave_->restart();
return kt::RPCClient::RVSUCCESS;
}
// process the ulog_list procedure
RV do_ulog_list(kt::RPCServer* serv, kt::RPCServer::Session* sess,
const std::map& inmap,
std::map& outmap) {
if (!ulog_) {
set_message(outmap, "ERROR", "no update log allows no replication");
return kt::RPCClient::RVEINVALID;
}
std::vector files;
ulog_->list_files(&files);
std::vector::iterator it = files.begin();
std::vector::iterator itend = files.end();
while (it != itend) {
set_message(outmap, it->path.c_str(), "%llu:%llu",
(unsigned long long)it->size, (unsigned long long)it->ts);
++it;
}
return kt::RPCClient::RVSUCCESS;
}
// process the ulog_remove procedure
RV do_ulog_remove(kt::RPCServer* serv, kt::RPCServer::Session* sess,
const std::map& inmap,
std::map& outmap) {
if (!ulog_) {
set_message(outmap, "ERROR", "no update log allows no replication");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "ts");
uint64_t ts = kc::UINT64MAX;
if (rp) {
if (!std::strcmp(rp, "now")) {
ts = kt::UpdateLogger::clock_pure();
} else {
ts = kc::atoi(rp);
}
}
bool err = false;
std::vector files;
ulog_->list_files(&files);
std::vector::iterator it = files.begin();
std::vector::iterator itend = files.end();
if (it != itend) itend--;
while (it != itend) {
if (it->ts <= ts && !kc::File::remove(it->path)) {
set_message(outmap, "ERROR", "removing a file failed: %s", it->path.c_str());
serv->log(Logger::ERROR, "removing a file failed: %s", it->path.c_str());
err = true;
}
++it;
}
return err ? kt::RPCClient::RVEINTERNAL : kt::RPCClient::RVSUCCESS;
}
// process the status procedure
RV do_status(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTMISC]++;
std::map status;
if (db->status(&status)) {
rv = kt::RPCClient::RVSUCCESS;
outmap.insert(status.begin(), status.end());
} else {
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the clear procedure
RV do_clear(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTMISC]++;
if (db->clear()) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the synchronize procedure
RV do_synchronize(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "hard");
bool hard = rp ? true : false;
rp = kt::strmapget(inmap, "command");
std::string command = rp ? rp : "";
class Visitor : public kc::BasicDB::FileProcessor {
public:
Visitor(kt::RPCServer* serv, Worker* worker, const std::string& command) :
serv_(serv), worker_(worker), command_(command) {}
private:
bool process(const std::string& path, int64_t count, int64_t size) {
if (command_.size() < 1) return true;
const char* cmd = command_.c_str();
if (std::strchr(cmd, kc::File::PATHCHR) || !std::strcmp(cmd, kc::File::CDIRSTR) ||
!std::strcmp(cmd, kc::File::PDIRSTR)) {
serv_->log(Logger::INFO, "invalid command name: %s", cmd);
return false;
}
std::string cmdpath;
kc::strprintf(&cmdpath, "%s%c%s", worker_->cmdpath_, kc::File::PATHCHR, cmd);
std::vector args;
args.push_back(cmdpath);
args.push_back(path);
std::string tsstr;
uint64_t cc = worker_->ulog_ ? worker_->ulog_->clock() : kt::UpdateLogger::clock_pure();
if (!worker_->slave_->host().empty()) {
uint64_t rts = worker_->slave_->rts();
if (rts < cc) cc = rts;
}
kc::strprintf(&tsstr, "%020llu", (unsigned long long)cc);
args.push_back(tsstr);
serv_->log(Logger::SYSTEM, "executing: %s \"%s\"", cmd, path.c_str());
if (kt::executecommand(args) != 0) {
serv_->log(Logger::ERROR, "execution failed: %s \"%s\"", cmd, path.c_str());
return false;
}
return true;
}
kt::RPCServer* serv_;
Worker* worker_;
std::string command_;
};
Visitor visitor(serv, this, command);
RV rv;
opcounts_[thid][CNTMISC]++;
if (db->synchronize(hard, &visitor)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the set procedure
RV do_set(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
size_t vsiz;
const char* vbuf = kt::strmapget(inmap, "value", &vsiz);
if (!kbuf || !vbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
if (db->set(kbuf, ksiz, vbuf, vsiz, xt)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the add procedure
RV do_add(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
size_t vsiz;
const char* vbuf = kt::strmapget(inmap, "value", &vsiz);
if (!kbuf || !vbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
if (db->add(kbuf, ksiz, vbuf, vsiz, xt)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::DUPREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the replace procedure
RV do_replace(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
size_t vsiz;
const char* vbuf = kt::strmapget(inmap, "value", &vsiz);
if (!kbuf || !vbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
if (db->replace(kbuf, ksiz, vbuf, vsiz, xt)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the append procedure
RV do_append(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
size_t vsiz;
const char* vbuf = kt::strmapget(inmap, "value", &vsiz);
if (!kbuf || !vbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
if (db->append(kbuf, ksiz, vbuf, vsiz, xt)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the increment procedure
RV do_increment(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
const char* nstr = kt::strmapget(inmap, "num");
if (!kbuf || !nstr) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
int64_t num = kc::atoi(nstr);
const char* rp = kt::strmapget(inmap, "orig");
int64_t orig;
if (rp) {
if (!std::strcmp(rp, "try")) {
orig = kc::INT64MIN;
} else if (!std::strcmp(rp, "set")) {
orig = kc::INT64MAX;
} else {
orig = kc::atoi(rp);
}
} else {
orig = 0;
}
rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
num = db->increment(kbuf, ksiz, num, orig, xt);
if (num != kc::INT64MIN) {
rv = kt::RPCClient::RVSUCCESS;
set_message(outmap, "num", "%lld", (long long)num);
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::LOGIC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the increment_double procedure
RV do_increment_double(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
const char* nstr = kt::strmapget(inmap, "num");
if (!kbuf || !nstr) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
double num = kc::atof(nstr);
const char* rp = kt::strmapget(inmap, "orig");
double orig;
if (rp) {
if (!std::strcmp(rp, "try")) {
orig = -kc::inf();
} else if (!std::strcmp(rp, "set")) {
orig = kc::inf();
} else {
orig = kc::atof(rp);
}
} else {
orig = 0;
}
rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
num = db->increment_double(kbuf, ksiz, num, orig, xt);
if (!kc::chknan(num)) {
rv = kt::RPCClient::RVSUCCESS;
set_message(outmap, "num", "%f", num);
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::LOGIC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the cas procedure
RV do_cas(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
if (!kbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
size_t ovsiz;
const char* ovbuf = kt::strmapget(inmap, "oval", &ovsiz);
size_t nvsiz;
const char* nvbuf = kt::strmapget(inmap, "nval", &nvsiz);
const char* rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
if (db->cas(kbuf, ksiz, ovbuf, ovsiz, nvbuf, nvsiz, xt)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::LOGIC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the remove procedure
RV do_remove(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
if (!kbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTREMOVE]++;
if (db->remove(kbuf, ksiz)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTREMOVEMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the get procedure
RV do_get(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
if (!kbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTGET]++;
size_t vsiz;
int64_t xt;
const char* vbuf = db->get(kbuf, ksiz, &vsiz, &xt);
if (vbuf) {
outmap["value"] = std::string(vbuf, vsiz);
if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt);
delete[] vbuf;
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the check procedure
RV do_check(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
if (!kbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTGET]++;
int64_t xt;
int32_t vsiz = db->check(kbuf, ksiz, &xt);
if (vsiz >= 0) {
set_message(outmap, "vsiz", "%lld", (long long)vsiz);
if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt);
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the seize procedure
RV do_seize(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
if (!kbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTREMOVE]++;
opcounts_[thid][CNTGET]++;
size_t vsiz;
int64_t xt;
const char* vbuf = db->seize(kbuf, ksiz, &vsiz, &xt);
if (vbuf) {
outmap["value"] = std::string(vbuf, vsiz);
if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt);
delete[] vbuf;
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTREMOVEMISS]++;
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the set_bulk procedure
RV do_set_bulk(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
rp = kt::strmapget(inmap, "atomic");
bool atomic = rp ? true : false;
std::map recs;
std::map::const_iterator it = inmap.begin();
std::map::const_iterator itend = inmap.end();
while (it != itend) {
const char* kbuf = it->first.data();
size_t ksiz = it->first.size();
if (ksiz > 0 && *kbuf == '_') {
std::string key(kbuf + 1, ksiz - 1);
std::string value(it->second.data(), it->second.size());
recs[key] = value;
}
++it;
}
RV rv;
opcounts_[thid][CNTSET] += recs.size();
int64_t num = db->set_bulk(recs, xt, atomic);
if (num >= 0) {
opcounts_[thid][CNTSETMISS] += recs.size() - (size_t)num;
rv = kt::RPCClient::RVSUCCESS;
set_message(outmap, "num", "%lld", (long long)num);
} else {
opcounts_[thid][CNTSETMISS] += recs.size();
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the remove_bulk procedure
RV do_remove_bulk(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "atomic");
bool atomic = rp ? true : false;
std::vector keys;
keys.reserve(inmap.size());
std::map::const_iterator it = inmap.begin();
std::map::const_iterator itend = inmap.end();
while (it != itend) {
const char* kbuf = it->first.data();
size_t ksiz = it->first.size();
if (ksiz > 0 && *kbuf == '_') {
std::string key(kbuf + 1, ksiz - 1);
keys.push_back(key);
}
++it;
}
RV rv;
opcounts_[thid][CNTREMOVE] += keys.size();
int64_t num = db->remove_bulk(keys, atomic);
if (num >= 0) {
opcounts_[thid][CNTREMOVEMISS] += keys.size() - (size_t)num;
rv = kt::RPCClient::RVSUCCESS;
set_message(outmap, "num", "%lld", (long long)num);
} else {
opcounts_[thid][CNTREMOVEMISS] += keys.size();
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the get_bulk procedure
RV do_get_bulk(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "atomic");
bool atomic = rp ? true : false;
std::vector keys;
keys.reserve(inmap.size());
std::map::const_iterator it = inmap.begin();
std::map::const_iterator itend = inmap.end();
while (it != itend) {
const char* kbuf = it->first.data();
size_t ksiz = it->first.size();
if (ksiz > 0 && *kbuf == '_') {
std::string key(kbuf + 1, ksiz - 1);
keys.push_back(key);
}
++it;
}
RV rv;
opcounts_[thid][CNTGET] += keys.size();
std::map recs;
int64_t num = db->get_bulk(keys, &recs, atomic);
if (num >= 0) {
opcounts_[thid][CNTGETMISS] += keys.size() - (size_t)num;
rv = kt::RPCClient::RVSUCCESS;
std::map::iterator it = recs.begin();
std::map::iterator itend = recs.end();
while (it != itend) {
std::string key("_");
key.append(it->first);
outmap[key] = it->second;
++it;
}
set_message(outmap, "num", "%lld", (long long)num);
} else {
opcounts_[thid][CNTGETMISS] += keys.size();
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the vacuum procedure
RV do_vacuum(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "step");
int64_t step = rp ? kc::atoi(rp) : 0;
RV rv;
opcounts_[thid][CNTMISC]++;
if (db->vacuum(step)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the match_prefix procedure
RV do_match_prefix(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t psiz;
const char* pbuf = kt::strmapget(inmap, "prefix", &psiz);
if (!pbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "max");
int64_t max = rp ? kc::atoi(rp) : -1;
std::vector keys;
RV rv;
opcounts_[thid][CNTMISC]++;
int64_t num = db->match_prefix(std::string(pbuf, psiz), &keys, max);
if (num >= 0) {
std::vector::iterator it = keys.begin();
std::vector::iterator itend = keys.end();
int64_t cnt = 0;
while (it != itend) {
std::string key = "_";
key.append(*it);
outmap[key] = kc::strprintf("%lld", (long long)cnt);
++cnt;
++it;
}
set_message(outmap, "num", "%lld", (long long)num);
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
return rv;
}
// process the match_regex procedure
RV do_match_regex(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t psiz;
const char* pbuf = kt::strmapget(inmap, "regex", &psiz);
if (!pbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "max");
int64_t max = rp ? kc::atoi(rp) : -1;
std::vector keys;
RV rv;
opcounts_[thid][CNTMISC]++;
int64_t num = db->match_regex(std::string(pbuf, psiz), &keys, max);
if (num >= 0) {
std::vector::iterator it = keys.begin();
std::vector::iterator itend = keys.end();
int64_t cnt = 0;
while (it != itend) {
std::string key = "_";
key.append(*it);
outmap[key] = kc::strprintf("%lld", (long long)cnt);
++cnt;
++it;
}
set_message(outmap, "num", "%lld", (long long)num);
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::LOGIC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the match_similar procedure
RV do_match_similar(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB* db,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!db) {
set_message(outmap, "ERROR", "no such database");
return kt::RPCClient::RVEINVALID;
}
size_t osiz;
const char* obuf = kt::strmapget(inmap, "origin", &osiz);
if (!obuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "range");
int64_t range = rp ? kc::atoi(rp) : 1;
if (range < 0) range = 1;
rp = kt::strmapget(inmap, "utf");
bool utf = rp ? true : false;
rp = kt::strmapget(inmap, "max");
int64_t max = rp ? kc::atoi(rp) : -1;
std::vector keys;
RV rv;
opcounts_[thid][CNTMISC]++;
int64_t num = db->match_similar(std::string(obuf, osiz), range, utf, &keys, max);
if (num >= 0) {
std::vector::iterator it = keys.begin();
std::vector::iterator itend = keys.end();
int64_t cnt = 0;
while (it != itend) {
std::string key = "_";
key.append(*it);
outmap[key] = kc::strprintf("%lld", (long long)cnt);
++cnt;
++it;
}
set_message(outmap, "num", "%lld", (long long)num);
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = db->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::LOGIC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the cur_jump procedure
RV do_cur_jump(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
RV rv;
opcounts_[thid][CNTMISC]++;
if (kbuf) {
if (cur->jump(kbuf, ksiz)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
} else {
if (cur->jump()) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
}
return rv;
}
// process the cur_jump_back procedure
RV do_cur_jump_back(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
size_t ksiz;
const char* kbuf = kt::strmapget(inmap, "key", &ksiz);
RV rv;
opcounts_[thid][CNTMISC]++;
if (kbuf) {
if (cur->jump_back(kbuf, ksiz)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
switch (e.code()) {
case kc::BasicDB::Error::NOIMPL: {
rv = kt::RPCClient::RVENOIMPL;
break;
}
case kc::BasicDB::Error::NOREC: {
rv = kt::RPCClient::RVELOGIC;
break;
}
default: {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
break;
}
}
}
} else {
if (cur->jump_back()) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
switch (e.code()) {
case kc::BasicDB::Error::NOIMPL: {
rv = kt::RPCClient::RVENOIMPL;
break;
}
case kc::BasicDB::Error::NOREC: {
rv = kt::RPCClient::RVELOGIC;
break;
}
default: {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
break;
}
}
}
}
return rv;
}
// process the cur_step procedure
RV do_cur_step(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTMISC]++;
if (cur->step()) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the cur_step_back procedure
RV do_cur_step_back(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTMISC]++;
if (cur->step_back()) {
rv = kt::RPCClient::RVSUCCESS;
} else {
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
switch (e.code()) {
case kc::BasicDB::Error::NOIMPL: {
rv = kt::RPCClient::RVENOIMPL;
break;
}
case kc::BasicDB::Error::NOREC: {
rv = kt::RPCClient::RVELOGIC;
break;
}
default: {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
break;
}
}
}
return rv;
}
// process the cur_set_value procedure
RV do_cur_set_value(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
size_t vsiz;
const char* vbuf = kt::strmapget(inmap, "value", &vsiz);
if (!vbuf) {
set_message(outmap, "ERROR", "invalid parameters");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "step");
bool step = rp ? true : false;
rp = kt::strmapget(inmap, "xt");
int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX;
RV rv;
opcounts_[thid][CNTSET]++;
if (cur->set_value(vbuf, vsiz, xt, step)) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the remove procedure
RV do_cur_remove(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTREMOVE]++;
if (cur->remove()) {
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTREMOVEMISS]++;
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the cur_get_key procedure
RV do_cur_get_key(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "step");
bool step = rp ? true : false;
RV rv;
opcounts_[thid][CNTGET]++;
size_t ksiz;
char* kbuf = cur->get_key(&ksiz, step);
if (kbuf) {
outmap["key"] = std::string(kbuf, ksiz);
delete[] kbuf;
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the cur_get_value procedure
RV do_cur_get_value(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "step");
bool step = rp ? true : false;
RV rv;
opcounts_[thid][CNTGET]++;
size_t vsiz;
char* vbuf = cur->get_value(&vsiz, step);
if (vbuf) {
outmap["value"] = std::string(vbuf, vsiz);
delete[] vbuf;
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the cur_get procedure
RV do_cur_get(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
const char* rp = kt::strmapget(inmap, "step");
bool step = rp ? true : false;
RV rv;
opcounts_[thid][CNTGET]++;
size_t ksiz, vsiz;
const char* vbuf;
int64_t xt;
char* kbuf = cur->get(&ksiz, &vbuf, &vsiz, &xt, step);
if (kbuf) {
outmap["key"] = std::string(kbuf, ksiz);
outmap["value"] = std::string(vbuf, vsiz);
if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt);
delete[] kbuf;
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the cur_seize procedure
RV do_cur_seize(kt::RPCServer* serv, kt::RPCServer::Session* sess,
kt::TimedDB::Cursor* cur,
const std::map& inmap,
std::map& outmap) {
uint32_t thid = sess->thread_id();
if (!cur) {
set_message(outmap, "ERROR", "no such cursor");
return kt::RPCClient::RVEINVALID;
}
RV rv;
opcounts_[thid][CNTGET]++;
size_t ksiz, vsiz;
const char* vbuf;
int64_t xt;
char* kbuf = cur->seize(&ksiz, &vbuf, &vsiz, &xt);
if (kbuf) {
outmap["key"] = std::string(kbuf, ksiz);
outmap["value"] = std::string(vbuf, vsiz);
if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt);
delete[] kbuf;
rv = kt::RPCClient::RVSUCCESS;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = cur->error();
set_db_error(outmap, e);
if (e == kc::BasicDB::Error::NOREC) {
rv = kt::RPCClient::RVELOGIC;
} else {
log_db_error(serv, e);
rv = kt::RPCClient::RVEINTERNAL;
}
}
return rv;
}
// process the restful get command
int32_t do_rest_get(kt::HTTPServer* serv, kt::HTTPServer::Session* sess,
kt::TimedDB* db, const char* kbuf, size_t ksiz,
const std::map& reqheads,
const std::string& reqbody,
std::map& resheads,
std::string& resbody,
const std::map& misc) {
uint32_t thid = sess->thread_id();
int32_t code;
opcounts_[thid][CNTGET]++;
size_t vsiz;
int64_t xt;
const char* vbuf = db->get(kbuf, ksiz, &vsiz, &xt);
if (vbuf) {
resbody.append(vbuf, vsiz);
if (xt < kt::TimedDB::XTMAX) {
char buf[48];
kt::datestrhttp(xt, 0, buf);
resheads["x-kt-xt"] = buf;
}
delete[] vbuf;
code = 200;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = db->error();
kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message());
if (e == kc::BasicDB::Error::NOREC) {
code = 404;
} else {
log_db_error(serv, e);
code = 500;
}
}
return code;
}
// process the restful head command
int32_t do_rest_head(kt::HTTPServer* serv, kt::HTTPServer::Session* sess,
kt::TimedDB* db, const char* kbuf, size_t ksiz,
const std::map& reqheads,
const std::string& reqbody,
std::map& resheads,
std::string& resbody,
const std::map& misc) {
uint32_t thid = sess->thread_id();
int32_t code;
opcounts_[thid][CNTGET]++;
size_t vsiz;
int64_t xt;
const char* vbuf = db->get(kbuf, ksiz, &vsiz, &xt);
if (vbuf) {
if (xt < kt::TimedDB::XTMAX) {
char buf[48];
kt::datestrhttp(xt, 0, buf);
resheads["x-kt-xt"] = buf;
}
kc::strprintf(&resheads["content-length"], "%lld", (long long)vsiz);
delete[] vbuf;
code = 200;
} else {
opcounts_[thid][CNTGETMISS]++;
const kc::BasicDB::Error& e = db->error();
kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message());
resheads["content-length"] = "0";
if (e == kc::BasicDB::Error::NOREC) {
code = 404;
} else {
log_db_error(serv, e);
code = 500;
}
}
return code;
}
// process the restful put command
int32_t do_rest_put(kt::HTTPServer* serv, kt::HTTPServer::Session* sess,
kt::TimedDB* db, const char* kbuf, size_t ksiz,
const std::map& reqheads,
const std::string& reqbody,
std::map& resheads,
std::string& resbody,
const std::map& misc) {
uint32_t thid = sess->thread_id();
int32_t mode = 0;
const char* rp = kt::strmapget(reqheads, "x-kt-mode");
if (rp) {
if (!kc::stricmp(rp, "add")) {
mode = 1;
} else if (!kc::stricmp(rp, "replace")) {
mode = 2;
}
}
rp = kt::strmapget(reqheads, "x-kt-xt");
int64_t xt = rp ? kt::strmktime(rp) : -1;
xt = xt > 0 && xt < kt::TimedDB::XTMAX ? -xt : kc::INT64MAX;
int32_t code;
opcounts_[thid][CNTSET]++;
bool rv;
switch (mode) {
default: {
rv = db->set(kbuf, ksiz, reqbody.data(), reqbody.size(), xt);
break;
}
case 1: {
rv = db->add(kbuf, ksiz, reqbody.data(), reqbody.size(), xt);
break;
}
case 2: {
rv = db->replace(kbuf, ksiz, reqbody.data(), reqbody.size(), xt);
break;
}
}
if (rv) {
const char* url = kt::strmapget(misc, "url");
if (url) resheads["location"] = url;
code = 201;
} else {
opcounts_[thid][CNTSETMISS]++;
const kc::BasicDB::Error& e = db->error();
kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message());
if (e == kc::BasicDB::Error::DUPREC || e == kc::BasicDB::Error::NOREC) {
code = 450;
} else {
log_db_error(serv, e);
code = 500;
}
}
return code;
}
// process the restful delete command
int32_t do_rest_delete(kt::HTTPServer* serv, kt::HTTPServer::Session* sess,
kt::TimedDB* db, const char* kbuf, size_t ksiz,
const std::map& reqheads,
const std::string& reqbody,
std::map& resheads,
std::string& resbody,
const std::map& misc) {
uint32_t thid = sess->thread_id();
int32_t code;
opcounts_[thid][CNTREMOVE]++;
if (db->remove(kbuf, ksiz)) {
code = 204;
} else {
opcounts_[thid][CNTREMOVEMISS]++;
const kc::BasicDB::Error& e = db->error();
kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message());
if (e == kc::BasicDB::Error::NOREC) {
code = 404;
} else {
log_db_error(serv, e);
code = 500;
}
}
return code;
}
// process the binary replication command
bool do_bin_replication(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) {
char tbuf[sizeof(uint32_t)+sizeof(uint64_t)+sizeof(uint16_t)];
if (!sess->receive(tbuf, sizeof(tbuf))) return false;
const char* rp = tbuf;
uint32_t flags = kc::readfixnum(rp, sizeof(flags));
rp += sizeof(flags);
uint64_t ts = kc::readfixnum(rp, sizeof(ts));
rp += sizeof(ts);
uint16_t sid = kc::readfixnum(rp, sizeof(sid));
bool white = flags & kt::ReplicationClient::WHITESID;
bool err = false;
if (ulog_) {
kt::UpdateLogger::Reader ulrd;
if (ulrd.open(ulog_, ts)) {
char c = kt::RemoteDB::BMREPLICATION;
if (sess->send(&c, 1)) {
serv->log(kt::ThreadedServer::Logger::SYSTEM, "a slave was connected: ts=%llu sid=%u",
(unsigned long long)ts, sid);
char stack[kc::NUMBUFSIZ+RECBUFSIZ*4];
uint64_t rts = 0;
int32_t miss = 0;
while (!err && !serv->aborted()) {
size_t msiz;
uint64_t mts;
char* mbuf = ulrd.read(&msiz, &mts);
if (mbuf) {
size_t rsiz;
uint16_t rsid = 0;
uint16_t rdbid = 0;
const char* rbuf = DBUpdateLogger::parse(mbuf, msiz, &rsiz, &rsid, &rdbid);
if (white) {
if (rsid != sid) rbuf = NULL;
} else {
if (rsid == sid) rbuf = NULL;
}
if (rbuf) {
miss = 0;
size_t nsiz = 1 + sizeof(uint64_t) + sizeof(uint32_t) + msiz;
char* nbuf = nsiz > sizeof(stack) ? new char[nsiz] : stack;
char* wp = nbuf;
*(wp++) = kt::RemoteDB::BMREPLICATION;
kc::writefixnum(wp, mts, sizeof(uint64_t));
wp += sizeof(uint64_t);
kc::writefixnum(wp, msiz, sizeof(uint32_t));
wp += sizeof(uint32_t);
std::memcpy(wp, mbuf, msiz);
if (!sess->send(nbuf, nsiz)) err = true;
if (nbuf != stack) delete[] nbuf;
} else {
miss++;
if (miss >= Slave::DUMMYFREQ) {
char hbuf[1+sizeof(uint64_t)+sizeof(uint32_t)];
char* wp = hbuf;
*(wp++) = kt::RemoteDB::BMREPLICATION;
kc::writefixnum(wp, mts, sizeof(uint64_t));
wp += sizeof(uint64_t);
kc::writefixnum(wp, 0, sizeof(uint32_t));
if (!sess->send(hbuf, sizeof(hbuf))) err = true;
miss = 0;
}
}
if (mts > rts) rts = mts;
delete[] mbuf;
} else {
uint64_t cc = kt::UpdateLogger::clock_pure();
if (cc > 1000000000) cc -= 1000000000;
if (cc < rts) cc = rts;
char hbuf[1+sizeof(uint64_t)];
char* wp = hbuf;
*(wp++) = kt::RemoteDB::BMNOP;
kc::writefixnum(wp, cc, sizeof(uint64_t));
if (!sess->send(hbuf, sizeof(hbuf)) ||
sess->receive_byte() != kt::RemoteDB::BMREPLICATION)
err = true;
kc::Thread::sleep(0.1);
}
}
serv->log(kt::ThreadedServer::Logger::SYSTEM, "a slave was disconnected: sid=%u", sid);
if (!ulrd.close()) {
serv->log(kt::ThreadedServer::Logger::ERROR, "closing an update log reader failed");
err = true;
}
} else {
err = true;
}
} else {
serv->log(kt::ThreadedServer::Logger::ERROR, "opening an update log reader failed");
char c = kt::RemoteDB::BMERROR;
sess->send(&c, 1);
err = true;
}
} else {
char c = kt::RemoteDB::BMERROR;
sess->send(&c, 1);
serv->log(kt::ThreadedServer::Logger::INFO, "no update log allows no replication");
err = true;
}
return !err;
}
// process the binary play_script command
bool do_bin_play_script(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) {
uint32_t thid = sess->thread_id();
char tbuf[sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)];
if (!sess->receive(tbuf, sizeof(tbuf))) return false;
const char* rp = tbuf;
uint32_t flags = kc::readfixnum(rp, sizeof(flags));
rp += sizeof(flags);
uint32_t nsiz = kc::readfixnum(rp, sizeof(nsiz));
rp += sizeof(nsiz);
uint32_t rnum = kc::readfixnum(rp, sizeof(rnum));
rp += sizeof(rnum);
if (nsiz > kt::RemoteDB::DATAMAXSIZ) return false;
bool norep = flags & kt::RemoteDB::BONOREPLY;
bool err = false;
char nstack[kc::NUMBUFSIZ+RECBUFSIZ];
char* nbuf = nsiz + 1 > sizeof(nstack) ? new char[nsiz+1] : nstack;
if (sess->receive(nbuf, nsiz)) {
nbuf[nsiz] = '\0';
char stack[kc::NUMBUFSIZ+RECBUFSIZ*4];
std::map