kalavara 0.3.0

A distributed persistent key value store that speaks http.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! # master server
//!
//! Master server stores index (key, url of volume server where the value is
//! stored) in rocksdb. Requests are redirected to curresponding volume server
//! after metadata is updated.
//!
//! to start the server, run
//!
//! ```sh
//! master -p 6000 -d /tmp/kalavadb -v http://volume1:6001 http://volume2:6002
//! ```
//!

use rand::{thread_rng, Rng};
use rocksdb::{IteratorMode, DB};

use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::io::Read;
use std::net::SocketAddr;
use std::str::{self, FromStr};
use std::sync::{Arc, RwLock};
use std::thread;
use tiny_http::{Method, Request, Server};

use crate::get_key;
use crate::{Respond, Service, ADMIN_PREFIX, STORE_PREFIX};

/// Master store
struct Master {
    db: Arc<DB>,
    volumes: Arc<RwLock<HashMap<String, u32>>>,
}

/// Types of responses that master generates
enum ResponseKind {
    /// Redirect to volume server, 301
    Redirect(String),

    /// 200
    Ok(String),

    /// Key not found, 404
    NotFound,

    /// Error occured, 500
    ServerError,

    /// Method not allowed, 405
    NotAllowed,

    /// Unavailable, 503
    Unavailable,
}

/// Admin service interfaces
trait AdminService: Sync + Send {
    /// add new volume server
    fn add_volume(&self, url: String) -> ResponseKind;

    /// dispatch request to admin service
    fn dispatch(&self, mut req: Request) {
        let path = get_key(req.url(), ADMIN_PREFIX);

        let resp = match (path.as_str(), req.method()) {
            ("add-volume", &Method::Post) => {
                let mut body = String::new();
                let _ = req.as_reader().read_to_string(&mut body);

                self.add_volume(body)
            }
            ("add-volume", _) => ResponseKind::NotAllowed,
            (_, _) => ResponseKind::NotFound,
        };

        resp.respond(req);
    }
}

impl Default for ResponseKind {
    fn default() -> Self {
        ResponseKind::NotAllowed
    }
}

impl Respond for ResponseKind {
    fn respond(self, req: Request) {
        use ResponseKind::*;

        let _ = match self {
            Redirect(url) => req.respond(redirect!(&format!("Location:{}", url))),
            Ok(txt) => req.respond(resp!(txt, 200)),
            NotFound => req.respond(resp!("Key not found", 404)),
            ServerError => req.respond(resp!("Server error", 500)),
            NotAllowed => req.respond(resp!("Method not allowd", 405)),
            Unavailable => req.respond(resp!("Service unavailable", 503)),
        };
    }
}

impl Service for Master {
    type Response = ResponseKind;

    fn get(&self, key: String) -> Self::Response {
        match self.db.get(key.as_bytes()) {
            Ok(Some(volume)) => {
                ResponseKind::Redirect(format!("{}/{}", volume.to_utf8().unwrap().to_string(), key))
            }
            Ok(None) => ResponseKind::NotFound,
            Err(_) => ResponseKind::ServerError,
        }
    }

    fn save(&self, key: String, _value: impl Read) -> Self::Response {
        if self.volumes.read().unwrap().is_empty() {
            ResponseKind::Unavailable
        } else {
            let volume_url = self.key_to_volume(&key);
            match self.db.put(key.as_bytes(), volume_url.as_bytes()) {
                Ok(_) => {
                    // increment count in map
                    self.increment_count(&volume_url);
                    ResponseKind::Redirect(format!("{}/{}", volume_url, key))
                }
                Err(_) => ResponseKind::ServerError,
            }
        }
    }

    fn delete(&self, key: String) -> Self::Response {
        match self.db.get(key.as_bytes()) {
            Ok(Some(volume)) => {
                let volume_url = volume.to_utf8().unwrap();

                // delete it from db
                if self.db.delete(key.as_bytes()).is_ok() {
                    // decrement count in map
                    self.decrement_count(&volume_url);
                    ResponseKind::Redirect(format!("{}/{}", volume_url, key))
                } else {
                    ResponseKind::ServerError
                }
            }
            Ok(None) => ResponseKind::NotFound,
            Err(_) => ResponseKind::ServerError,
        }
    }
}

impl AdminService for Master {
    fn add_volume(&self, volume: String) -> ResponseKind {
        let mut volumes_map = self.volumes.write().unwrap();

        let entry = (*volumes_map).entry(volume);
        match entry {
            Entry::Occupied(_) => ResponseKind::Ok("Skipping duplicate volume server".to_string()),
            Entry::Vacant(e) => {
                e.insert(0);
                ResponseKind::Ok("Volume added".to_string())
            }
        }
    }
}

impl Master {
    pub fn new(db: DB, volumes: Vec<String>) -> Master {
        // Create HashMap from url list
        let mut volumes_map = HashMap::<String, u32>::new();

        for url in volumes {
            volumes_map.insert(url, 0);
        }

        // update number of keys in each server from existing db
        let iter = db.iterator(IteratorMode::Start);
        for (_, url_bytes) in iter {
            if let Ok(url_raw) = str::from_utf8(&url_bytes) {
                println!("found {}", url_raw.to_owned());
                let count = volumes_map.entry(url_raw.to_owned()).or_default();
                *count += 1;
            }
        }

        Master {
            db: Arc::new(db),
            volumes: Arc::new(RwLock::new(volumes_map)),
        }
    }

    /// translate key to volume url
    /// volume server is selected based on the number of keys it holds.
    /// Server with lesser number of keys are more likely to get selected.
    fn key_to_volume(&self, _key: &str) -> String {
        let volumes_map = self.volumes.read().unwrap();
        let len = volumes_map.len();
        let mut vlms = Vec::<&String>::with_capacity(len);
        let mut counts = Vec::<f32>::with_capacity(len);

        let mut cumulative_count = 0.0f32;
        let mut max_count = 0;

        for (key, value) in volumes_map.iter() {
            vlms.push(key);

            let count = if *value == 0 { 1 } else { *value };

            if count > max_count {
                max_count = count;
            }

            cumulative_count += count as f32;
            counts.push(cumulative_count);
        }

        // invert-normalize counts
        for count in counts.iter_mut() {
            *count = max_count as f32 / *count;
        }

        let mut rng = thread_rng();
        let random = rng.gen_range(0.0, max_count as f32);

        for indx in 0..len {
            if random <= counts[indx] {
                return (*vlms[indx]).to_string();
            }
        }

        vlms[len - 1].to_string()
    }

    /// increment counter for url
    fn increment_count(&self, url: &str) {
        let mut volumes_map = self.volumes.write().unwrap();

        if let Some(count) = (*volumes_map).get_mut(url) {
            *count += 1;
        }
    }

    /// decrement counter for url
    fn decrement_count(&self, url: &str) {
        let mut volumes_map = self.volumes.write().unwrap();
        if let Some(count) = (*volumes_map).get_mut(url) {
            *count -= 1;
        }
    }

    fn dispatch(&self, req: Request) {
        let url = req.url();

        if url.starts_with(STORE_PREFIX) {
            Service::dispatch(self, req);
        } else if url.starts_with(ADMIN_PREFIX) {
            AdminService::dispatch(self, req);
        } else {
            let _ = req.respond(resp!("Path not found", 404));
        }
    }
}

/// starts a kalavara master server
/// # Arguments
///
/// * `port` - Port name to listen at
/// * `data_dir` - Database directory
/// * `threads` - Number of threads to spawn
/// * `volumes` - List of volume servers
///
pub fn start(port: u16, data_dir: &str, threads: u16, volumes: Vec<String>) {
    let db = match DB::open_default(data_dir) {
        Ok(db) => db,
        Err(e) => panic!("failed to open database: {:?}", e),
    };

    let addr: SocketAddr = ([0, 0, 0, 0], port).into();

    let server = match Server::http(addr) {
        Ok(server) => Arc::new(server),
        Err(e) => panic!("failed to start http server: {:?}", e),
    };

    let master = Arc::new(Master::new(db, volumes));

    let mut handles = Vec::new();

    for _ in 0..threads {
        let server = server.clone();
        let handler = master.clone();

        handles.push(thread::spawn(move || {
            for rq in server.incoming_requests() {
                handler.dispatch(rq);
            }
        }));
    }

    for h in handles {
        h.join().unwrap();
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_master_crud() {
        let data_dir = tempdir().unwrap();

        let db = match DB::open_default(data_dir) {
            Ok(db) => db,
            Err(e) => panic!("failed to open database: {:?}", e),
        };

        let master = Master::new(
            db,
            vec![
                "server1".to_owned(),
                "server2".to_owned(),
                "server3".to_owned(),
                "server4".to_owned(),
                "server5".to_owned(),
            ],
        );
        let key = "key".to_owned();
        let val = "val".to_owned();

        assert!(match master.get(key.clone()) {
            ResponseKind::NotFound => true,
            _ => false,
        });

        let mut url = String::new();

        assert!(match master.save(key.clone(), val.clone().as_bytes()) {
            ResponseKind::Redirect(to) => {
                url = to;
                true
            }
            _ => false,
        });

        // should redirect to the save volume server
        // in which the key got stored
        assert!(match master.get(key.clone()) {
            ResponseKind::Redirect(to) => to == url,
            _ => false,
        });

        assert_eq!(master.volumes.read().unwrap().get(&url[..7]), Some(&1));

        assert!(match master.delete(key.clone()) {
            ResponseKind::Redirect(to) => to == url,
            _ => false,
        });

        assert_eq!(master.volumes.read().unwrap().get(&url[..7]), Some(&0));
    }

    #[test]
    fn test_master_admin() {
        let data_dir = tempdir().unwrap();

        let db = match DB::open_default(data_dir) {
            Ok(db) => db,
            Err(e) => panic!("failed to open database: {:?}", e),
        };

        let master = Master::new(db, vec!["server1".to_owned(), "server2".to_owned()]);

        assert!(match master.add_volume("server3".to_owned()) {
            ResponseKind::Ok(resp) => resp == "Volume added".to_string(),
            _ => false,
        });

        assert_eq!(master.volumes.read().unwrap().len(), 3);

        assert!(match master.add_volume("server3".to_owned()) {
            ResponseKind::Ok(resp) => resp == "Skipping duplicate volume server".to_string(),
            _ => false,
        });

        assert_eq!(master.volumes.read().unwrap().len(), 3);
    }

    #[test]
    fn test_master_counter() {
        let data_dir = tempdir().unwrap();

        let db = match DB::open_default(data_dir) {
            Ok(db) => {
                db.put(b"key1", b"server1").unwrap();
                db.put(b"key2", b"server1").unwrap();
                db.put(b"key3", b"server2").unwrap();
                db.put(b"key4", b"server3").unwrap();
                db
            }
            Err(e) => panic!("failed to open database: {:?}", e),
        };

        let master = Master::new(db, vec!["server1".to_owned(), "server4".to_owned()]);
        assert_eq!(master.volumes.read().unwrap()["server1"], 2);
        assert_eq!(master.volumes.read().unwrap()["server2"], 1);
        assert_eq!(master.volumes.read().unwrap()["server3"], 1);
        assert_eq!(master.volumes.read().unwrap()["server4"], 0);
    }
}