Add proper per-file copyright notices/licenses and top-level license.
[bluesky.git] / kvstore / kvservice.cc
1 #include "kvservice.h"
2 #include <iostream>
3
4 extern "C" {
5 #include <time.h>
6 #include <sys/time.h>
7 }
8
9 using namespace std;
10
11 /* Timing and delay functionality.  We allow the get and put operations to have
12  * a specified minimum latency, and will sleep if the operation would have
13  * completed before that time.  This can be used in benchmarking to see the
14  * effect of increasing latency on an application.
15  *
16  * Call gettimeofday at the start of the operation to get the starting time,
17  * and then use minimum_delay to wait until at least the specified number of
18  * microseconds have elapsed. */
19 static void minimum_delay(const struct timeval *tv, unsigned int min_usec)
20 {
21     struct timeval now;
22     if (gettimeofday(&now, NULL) < 0)
23         return;
24
25     int64_t t1, t2;             /* Times converted to straight microseconds */
26     t1 = (int64_t)tv->tv_sec * 1000000 + tv->tv_usec;
27     t2 = (int64_t)now.tv_sec * 1000000 + now.tv_usec;
28
29     unsigned int elapsed = t2 - t1;
30     if (elapsed >= min_usec)
31         return;
32
33     struct timespec delay;
34     delay.tv_sec = (min_usec - elapsed) / 1000000;
35     delay.tv_nsec = ((min_usec - elapsed) % 1000000) * 1000;
36
37     while (nanosleep(&delay, &delay) != 0 && errno == EINTR)
38         ;
39 }
40
41 namespace kvstore
42 {
43
44 KeyValueRpcService::KeyValueRpcService(Backend *backend)
45     :_backend(backend)
46 {
47 }
48
49 KeyValueRpcService::~KeyValueRpcService()
50 {
51 }
52
53 void KeyValueRpcService::PutValue(
54                       ::google::protobuf::RpcController* /*controller*/,
55                       const ::kvrpc::Put* request,
56                       ::kvrpc::PutReply* response,
57                       ::google::protobuf::Closure* done)
58 {
59     struct timeval start;
60     gettimeofday(&start, NULL);
61
62     if (_backend->Put(request->key(), request->value()))
63     {
64         response->set_result(kvrpc::SUCCESS);
65     }
66     else
67     {
68         response->set_result(kvrpc::FAILURE);
69     }
70
71     //minimum_delay(&start, 1000000);
72     done->Run();
73 }
74
75 void KeyValueRpcService::GetValue(
76                       ::google::protobuf::RpcController* /*controller*/,
77                       const ::kvrpc::Get* request,
78                       ::kvrpc::GetReply* response,
79                       ::google::protobuf::Closure* done)
80 {
81     struct timeval start;
82     gettimeofday(&start, NULL);
83
84     string value;
85     if (_backend->Get(request->key(), &value))
86     {
87         response->set_result(kvrpc::SUCCESS);
88         response->set_value(value);
89     }
90     else
91     {
92         response->set_result(kvrpc::FAILURE);
93     }
94
95     //minimum_delay(&start, 1000000);
96     done->Run();
97 }
98
99 }; // namespace kvstore