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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// Copyright 2016-2017 Kai Strempel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use std::io::Read;

use hyper::header::Connection;
use hyper::status::StatusCode;

use datapoints::Datapoints;
use query::Query;
use result::{QueryResult, ResultMap};
use error::KairoError;
use helper::parse_metricnames_result;
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const _IMPL_DESERIALIZE_FOR_Version: () =
    {
        extern crate serde as _serde;
        #[automatically_derived]
        impl _serde::de::Deserialize for Version {
            fn deserialize<__D>(deserializer: &mut __D)
             -> ::std::result::Result<Version, __D::Error> where
             __D: _serde::de::Deserializer {
                #[allow(non_camel_case_types)]
                enum __Field { __field0, __ignore, }
                impl _serde::de::Deserialize for __Field {
                    #[inline]
                    fn deserialize<__D>(deserializer: &mut __D)
                     -> ::std::result::Result<__Field, __D::Error> where
                     __D: _serde::de::Deserializer {
                        struct __FieldVisitor;
                        impl _serde::de::Visitor for __FieldVisitor {
                            type
                            Value
                            =
                            __Field;
                            fn visit_usize<__E>(&mut self, value: usize)
                             ->
                                 ::std::result::Result<__Field, __E> where
                             __E: _serde::de::Error 
                             {
                                match value {
                                    0usize => { Ok(__Field::__field0) }
                                    _ => Ok(__Field::__ignore),
                                }
                            }
                            fn visit_str<__E>(&mut self, value: &str)
                             ->
                                 ::std::result::Result<

                                                       __Field, __E> where
                             __E: _serde::de::Error {
                                match value {
                                    "version" => { Ok(__Field::__field0) }
                                    _ => Ok(__Field::__ignore),
                                }
                            }
                            fn visit_bytes<__E>(&mut self, value: &[u8])
                             -> ::std::result::Result<__Field, __E> where
                             __E: _serde::de::Error {
                                match value {
                                    b"version" => { Ok(__Field::__field0) }
                                    _ => Ok(__Field::__ignore),
                                }
                            }
                        }
                        deserializer.deserialize_struct_field(

                                                              __FieldVisitor)
                    }
                }
                struct __Visitor;
                impl _serde::de::Visitor for __Visitor {
                    type
                    Value
                    =
                    Version;
                    #[inline]
                    fn visit_seq<__V>(&mut self, mut visitor: __V)
                     -> ::std::result::Result<Version, __V::Error> where
                     __V: _serde::de::SeqVisitor {
                        let __field0 =
                            match try!(visitor . visit :: < String > (  )) {
                                Some(value) => { value }
                                None => {
                                    try!(visitor . end (  ));
                                    return Err(_serde::de::Error::invalid_length(0usize));
                                }
                            };
                        try!(visitor . end (  ));
                        Ok(Version{version: __field0,})
                    }
                    #[inline]
                    fn visit_map<__V>(&mut self,
                                      mut visitor:
                                          __V)
                     -> ::std::result::Result<Version, __V::Error> where
                     __V: _serde::de::MapVisitor 
                     {
                        let mut __field0: Option<String> = None;
                        while let Some(key) =
                                  try!(visitor . visit_key :: < __Field > (
                                       )) {
                            match key {
                                __Field::__field0 => {
                                    if __field0.is_some() {
                                        return Err(<__V::Error as
                                                       _serde::de::Error>::duplicate_field("version"));
                                    }
                                    __field0 =
                                        Some(try!(visitor . visit_value :: <
                                                  String > (  )));
                                }
                                _ => {
                                    try!(visitor . visit_value :: < _serde ::
                                         de :: impls :: IgnoredAny > (  ));

                                }
                            }
                        }
                        try!(visitor . end (  ));
                        let __field0 =
                            match __field0 {
                                Some(__field0) => __field0,
                                None =>
                                try!(visitor . missing_field ( "version" )),
                            };
                        Ok(Version{version: __field0,})
                    }
                }
                const FIELDS: &'static [&'static str] = &["version"];
                deserializer.deserialize_struct("Version", FIELDS, __Visitor)
            }
        }
    };
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const _IMPL_SERIALIZE_FOR_Version: () =
    {
        extern crate serde as _serde;
        #[automatically_derived]
        impl _serde::ser::Serialize for Version {
            fn serialize<__S>(&self, _serializer: &mut __S)
             -> ::std::result::Result<(), __S::Error> where
             __S: _serde::ser::Serializer {
                let mut __serde_state =
                    try!(_serializer . serialize_struct ( "Version" , 0 + 1
                         ));
                try!(_serializer . serialize_struct_elt (
                     & mut __serde_state , "version" , & self . version ));
                _serializer.serialize_struct_end(__serde_state)
            }
        }
    };
#[derive(Debug)]
struct Version {
    version: String,
}
/// The core of the kairosdb client, owns a HTTP connection.
#[derive(Debug)]
pub struct Client {
    base_url: String,
    http_client: hyper::Client,
}
impl Client {
    /// Constructs a new KairosDB Client
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// let client = Client::new("localhost", 8080);
    /// ```
    pub fn new(host: &str, port: u32) -> Client {
        info!("create new client host: {} port: {}" , host , port);
        Client{base_url: format!("http://{}:{}" , host , port),
               http_client: hyper::Client::new(),}
    }
    /// Returns the version string of the KairosDB Server
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// let client = Client::new("localhost", 8080);
    /// assert!(client.version().unwrap().starts_with("KairosDB"));
    /// ```
    pub fn version(&self) -> Result<String, KairoError> {
        let mut response =
            self.http_client.get(&format!("{}/api/v1/version" , self .
                                          base_url)).header(Connection::close()).send()?;
        let mut body = String::new();
        response.read_to_string(&mut body)?;
        let version: Version = serde_json::from_str(&body)?;
        info!("get server version {:?}" , version . version);
        Ok(version.version)
    }
    /// Returns the health status of the KairosDB Server
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// let client = Client::new("localhost", 8080);
    /// let response = client.health();
    /// ```
    pub fn health(&self) -> Result<Vec<String>, KairoError> {
        let mut response =
            self.http_client.get(&format!("{}/api/v1/health/status" , self .
                                          base_url)).header(Connection::close()).send()?;
        match response.status {
            StatusCode::Ok => {
                let mut body = String::new();
                response.read_to_string(&mut body)?;
                let health: Vec<String> = serde_json::from_str(&body)?;
                info!("get server health {:?}" , health);
                Ok(health)
            }
            _ => {
                let msg =
                    format!("Health endpoint returns with wrong status code: {:?}"
                            , response . status);
                Err(KairoError::Kairo(msg))
            }
        }
    }

    /// Method to add datapoints to the time series database
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// use kairosdb::datapoints::Datapoints;
    ///
    /// let client = Client::new("localhost", 8080);
    /// let mut datapoints = Datapoints::new("first", 0);
    /// datapoints.add_ms(1475513259000, 11.0);
    /// datapoints.add_ms(1475513259001, 12.0);
    /// datapoints.add_tag("test", "first");
    /// let result = client.add(&datapoints);
    /// assert!(result.is_ok())
    /// ```
    pub fn add(&self, datapoints: &Datapoints) -> Result<(), KairoError> {
        info!("Add datapoints {:?}" , datapoints);
        let body = serde_json::to_string(&vec!(datapoints))?;
        let response =
            self.http_client.post(&format!("{}/api/v1/datapoints" , self .
                                           base_url)).header(Connection::close()).body(&body).send()?;
        match response.status {
            StatusCode::NoContent => Ok(()),
            _ => {
                let msg =
                    format!("Add datapoints returns with bad response code: {:?}"
                            , response . status);
                Err(KairoError::Kairo(msg))
            }
        }
    }

    /// Runs a query on the database.
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// use kairosdb::query::{Query, Time, TimeUnit};
    ///
    /// let client = Client::new("localhost", 8080);
    /// let query = Query::new(
    ///    Time::Nanoseconds(1),
    ///    Time::Relative{value: 1, unit: TimeUnit::WEEKS});
    /// let result = client.query(&query);
    /// assert!(result.is_ok())
    /// ```
    pub fn query(&self, query: &Query) -> Result<ResultMap, KairoError> {
        match self.run_query(query, "query") {
            Ok(body) => self.parse_query_result(&body),
            Err(err) => Err(err),
        }
    }

    /// Runs a delete query on the database. View the query structure
    /// to understand more about.
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// use kairosdb::query::{Query, Time, TimeUnit};
    ///
    /// let client = Client::new("localhost", 8080);
    /// let query = Query::new(
    ///    Time::Nanoseconds(1),
    ///    Time::Relative{value: 1, unit: TimeUnit::WEEKS});
    /// let result = client.delete(&query);
    /// assert!(result.is_ok())
    /// ```
    pub fn delete(&self, query: &Query) -> Result<(), KairoError> {
        match self.run_query(query, "delete") {
            Ok(_) => Ok(()),
            Err(err) => Err(err),
        }
    }

    /// Returns a list with all metric names
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// # use kairosdb::datapoints::Datapoints;
    /// let client = Client::new("localhost", 8080);
    /// # let mut datapoints = Datapoints::new("first", 0);
    /// # datapoints.add_ms(1475513259000, 11.0);
    /// # datapoints.add_tag("test", "first");
    /// # let result = client.add(&datapoints);
    ///
    /// let result = client.list_metrics();
    /// assert!(result.is_ok());
    /// assert!(result.unwrap().contains(&"first".to_string()));
    /// ```
    pub fn list_metrics(&self) -> Result<Vec<String>, KairoError> {
        info!("Get metricnames");
        let mut response =
            self.http_client.get(&format!("{}/api/v1/metricnames" , self .
                                          base_url)).header(Connection::close()).send()?;

        match response.status {
            StatusCode::Ok => {
                let mut result_body = String::new();
                response.read_to_string(&mut result_body)?;
                Ok(parse_metricnames_result(&result_body)?)
            }
            _ =>
            Err(KairoError::Kairo(format!("Bad response code: {:?}" , response
                                          . status))),
        }
    }

    /// Deleting a metric
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// # use kairosdb::datapoints::Datapoints;
    /// let client = Client::new("localhost", 8080);
    /// # let mut datapoints = Datapoints::new("first", 0);
    /// # datapoints.add_ms(1475513259000, 11.0);
    /// # let result = client.add(&datapoints);
    ///
    /// let result = client.delete_metric(&"first");
    /// assert!(result.is_ok());
    /// # let result = client.list_metrics();
    /// # assert!(result.is_ok());
    /// # assert!(!result.unwrap().contains(&"first".to_string()));
    /// ```
    pub fn delete_metric(&self, metric: &str) -> Result<(), KairoError> {
        let response =
            self.http_client.delete(&format!("{}/api/v1/metric/{}" , self .
                                             base_url ,
                                             metric)).header(Connection::close()).send()?;

        match response.status {
            StatusCode::NoContent => Ok(()),
            _ =>
            Err(KairoError::Kairo(format!("Bad response code: {:?}" , response
                                          . status))),
        }
    }

    /// Returns a list of all tagnames
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// # use kairosdb::datapoints::Datapoints;
    /// let client = Client::new("localhost", 8080);
    /// # let mut datapoints = Datapoints::new("first", 0);
    /// # datapoints.add_ms(1475513259000, 11.0);
    /// # datapoints.add_tag("test", "first");
    /// # let _ = client.add(&datapoints);
    ///
    /// let result = client.tagnames();
    /// assert!(result.is_ok());
    /// assert!(result.unwrap().contains(&"test".to_string()));
    /// ```
    pub fn tagnames(&self) -> Result<Vec<String>, KairoError> {
        info!("Get tagnames");
        let mut response =
            self.http_client.get(&format!("{}/api/v1/tagnames" , self .
                                          base_url)).header(Connection::close()).send()?;

        match response.status {
            StatusCode::Ok => {
                let mut result_body = String::new();
                response.read_to_string(&mut result_body)?;
                Ok(parse_metricnames_result(&result_body)?)
            }
            _ =>
            Err(KairoError::Kairo(format!("Bad response code: {:?}" , response
                                          . status))),
        }
    }

    /// Returns a list of all tagvalues
    ///
    /// # Example
    /// ```
    /// use kairosdb::Client;
    /// # use kairosdb::datapoints::Datapoints;
    /// let client = Client::new("localhost", 8080);
    /// # let mut datapoints = Datapoints::new("first", 0);
    /// # datapoints.add_ms(1475513259000, 11.0);
    /// # datapoints.add_tag("test", "first");
    /// # let _ = client.add(&datapoints);
    ///
    /// let result = client.tagvalues();
    /// assert!(result.is_ok());
    /// assert!(result.unwrap().contains(&"first".to_string()));
    /// ```
    pub fn tagvalues(&self) -> Result<Vec<String>, KairoError> {
        info!("Get tagnames");
        let mut response =
            self.http_client.get(&format!("{}/api/v1/tagvalues" , self .
                                          base_url)).header(Connection::close()).send()?;

        match response.status {
            StatusCode::Ok => {
                let mut result_body = String::new();
                response.read_to_string(&mut result_body)?;
                Ok(parse_metricnames_result(&result_body)?)
            }
            _ =>
            Err(KairoError::Kairo(format!("Bad response code: {:?}" , response
                                          . status))),
        }
    }

    fn run_query(&self, query: &Query, endpoint: &str)
     -> Result<String, KairoError> {
        let body = serde_json::to_string(query)?;
        info!("Run query {}" , body);
        let mut response =
            self.http_client.post(&format!("{}/api/v1/datapoints/{}" , self .
                                           base_url ,
                                           endpoint)).header(Connection::close()).body(&body).send()?;

        match response.status {
            StatusCode::Ok => {
                let mut result_body = String::new();
                response.read_to_string(&mut result_body)?;
                Ok(result_body)
            }
            StatusCode::NoContent => Ok("".to_string()),
            _ =>
            Err(KairoError::Kairo(format!("Bad response code: {:?}" , response
                                          . status))),
        }
    }


    fn parse_query_result(&self, body: &str)
     -> Result<ResultMap, KairoError> {
        let result = QueryResult::new();
        result.parse_result(body)
    }
}