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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use hyper::client::Client as hyper_client;
use hyper::client::RequestBuilder;
use hyper::client::Response;
use hyper::net::HttpsConnector;
use hyper::Url;
use hyper_native_tls::native_tls::TlsConnector;
use hyper_native_tls::NativeTlsClient;
use serde_json;
use serde_json::de::IoRead as SerdeIoRead;
use std::io::Read;
use std::iter::FromIterator;
use std::net::UdpSocket;
use std::net::{SocketAddr, ToSocketAddrs};
use std::time::Duration;
use {error, serialization, ChunkedQuery, Node, Point, Points, Precision, Query};

/// The client to influxdb
#[derive(Debug)]
pub struct Client {
    host: String,
    db: String,
    authentication: Option<(String, String)>,
    client: HttpClient,
}

unsafe impl Send for Client {}

impl Client {
    /// Create a new influxdb client with http
    pub fn new<T>(host: T, db: T) -> Self
    where
        T: ToString,
    {
        Client {
            host: host.to_string(),
            db: db.to_string(),
            authentication: None,
            client: HttpClient::default(),
        }
    }

    /// Create a new influxdb client with https
    pub fn new_with_option<T: ToString>(host: T, db: T, tls_option: Option<TLSOption>) -> Self {
        Client {
            host: host.to_string(),
            db: db.to_string(),
            authentication: None,
            client: HttpClient::new_with_option(tls_option),
        }
    }

    /// Set the read timeout value, unit "s"
    pub fn set_read_timeout(&mut self, timeout: u64) {
        self.client.set_read_timeout(Duration::from_secs(timeout));
    }

    /// Set the write timeout value, unit "s"
    pub fn set_write_timeout(&mut self, timeout: u64) {
        self.client.set_write_timeout(Duration::from_secs(timeout));
    }

    /// Change the client's database
    pub fn switch_database<T>(&mut self, database: T)
    where
        T: ToString,
    {
        self.db = database.to_string();
    }

    /// Change the client's user
    pub fn set_authentication<T>(mut self, user: T, passwd: T) -> Self
    where
        T: Into<String>,
    {
        self.authentication = Some((user.into(), passwd.into()));
        self
    }

    /// Change http to https, but don't leave the read write timeout setting
    pub fn set_tls(mut self, connector: Option<TLSOption>) -> Self {
        self.client = HttpClient::new_with_option(connector);
        self
    }

    /// View the current db name
    pub fn get_db(&self) -> String {
        self.db.to_owned()
    }

    /// Query whether the corresponding database exists, return bool
    pub fn ping(&self) -> bool {
        let url = self.build_url("ping", None);
        let res = self.client.get(url).send().unwrap();
        match res.status_raw().0 {
            204 => true,
            _ => false,
        }
    }

    /// Query the version of the database and return the version number
    pub fn get_version(&self) -> Option<String> {
        let url = self.build_url("ping", None);
        let res = self.client.get(url).send().unwrap();
        match res.status_raw().0 {
            204 => match res.headers.get_raw("X-Influxdb-Version") {
                Some(i) => Some(String::from_utf8(i[0].to_vec()).unwrap()),
                None => Some(String::from("Don't know")),
            },
            _ => None,
        }
    }

    /// Write a point to the database
    pub fn write_point(
        &self,
        point: Point,
        precision: Option<Precision>,
        rp: Option<&str>,
    ) -> Result<(), error::Error> {
        let points = Points::new(point);
        self.write_points(points, precision, rp)
    }

    /// Write multiple points to the database
    pub fn write_points<T: Iterator<Item = Point>>(
        &self,
        points: T,
        precision: Option<Precision>,
        rp: Option<&str>,
    ) -> Result<(), error::Error> {
        let line = serialization::line_serialization(points);

        let mut param = vec![("db", self.db.as_str())];

        match precision {
            Some(ref t) => param.push(("precision", t.to_str())),
            None => param.push(("precision", "s")),
        };

        if let Some(t) = rp {
            param.push(("rp", t))
        }

        let url = self.build_url("write", Some(param));

        let mut res = self.client.post(url).body(&line).send()?;
        let mut err = String::new();
        let _ = res.read_to_string(&mut err);

        match res.status_raw().0 {
            204 => Ok(()),
            400 => Err(error::Error::SyntaxError(serialization::conversion(&err))),
            401 | 403 => Err(error::Error::InvalidCredentials(
                "Invalid authentication credentials.".to_string(),
            )),
            404 => Err(error::Error::DataBaseDoesNotExist(
                serialization::conversion(&err),
            )),
            500 => Err(error::Error::RetentionPolicyDoesNotExist(err)),
            _ => Err(error::Error::Unknow("There is something wrong".to_string())),
        }
    }

    /// Query and return data, the data type is `Option<Vec<Node>>`
    pub fn query(
        &self,
        q: &str,
        epoch: Option<Precision>,
    ) -> Result<Option<Vec<Node>>, error::Error> {
        match self.query_raw(q, epoch) {
            Ok(t) => Ok(t.results),
            Err(e) => Err(e),
        }
    }

    /// Query and return data, the data type is `Option<Vec<Node>>`
    pub fn query_chunked(
        &self,
        q: &str,
        epoch: Option<Precision>,
    ) -> Result<ChunkedQuery<SerdeIoRead<Response>>, error::Error> {
        self.query_raw_chunked(q, epoch)
    }

    /// Drop measurement
    pub fn drop_measurement(&self, measurement: &str) -> Result<(), error::Error> {
        let sql = format!(
            "Drop measurement {}",
            serialization::quote_ident(measurement)
        );

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Create a new database in InfluxDB.
    pub fn create_database(&self, dbname: &str) -> Result<(), error::Error> {
        let sql = format!("Create database {}", serialization::quote_ident(dbname));

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Drop a database from InfluxDB.
    pub fn drop_database(&self, dbname: &str) -> Result<(), error::Error> {
        let sql = format!("Drop database {}", serialization::quote_ident(dbname));

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Create a new user in InfluxDB.
    pub fn create_user(&self, user: &str, passwd: &str, admin: bool) -> Result<(), error::Error> {
        let sql: String = {
            if admin {
                format!(
                    "Create user {0} with password {1} with all privileges",
                    serialization::quote_ident(user),
                    serialization::quote_literal(passwd)
                )
            } else {
                format!(
                    "Create user {0} WITH password {1}",
                    serialization::quote_ident(user),
                    serialization::quote_literal(passwd)
                )
            }
        };

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Drop a user from InfluxDB.
    pub fn drop_user(&self, user: &str) -> Result<(), error::Error> {
        let sql = format!("Drop user {}", serialization::quote_ident(user));

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Change the password of an existing user.
    pub fn set_user_password(&self, user: &str, passwd: &str) -> Result<(), error::Error> {
        let sql = format!(
            "Set password for {}={}",
            serialization::quote_ident(user),
            serialization::quote_literal(passwd)
        );

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Grant cluster administration privileges to a user.
    pub fn grant_admin_privileges(&self, user: &str) -> Result<(), error::Error> {
        let sql = format!(
            "Grant all privileges to {}",
            serialization::quote_ident(user)
        );

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Revoke cluster administration privileges from a user.
    pub fn revoke_admin_privileges(&self, user: &str) -> Result<(), error::Error> {
        let sql = format!(
            "Revoke all privileges from {}",
            serialization::quote_ident(user)
        );

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Grant a privilege on a database to a user.
    /// :param privilege: the privilege to grant, one of 'read', 'write'
    /// or 'all'. The string is case-insensitive
    pub fn grant_privilege(
        &self,
        user: &str,
        db: &str,
        privilege: &str,
    ) -> Result<(), error::Error> {
        let sql = format!(
            "Grant {} on {} to {}",
            privilege,
            serialization::quote_ident(db),
            serialization::quote_ident(user)
        );

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Revoke a privilege on a database from a user.
    /// :param privilege: the privilege to grant, one of 'read', 'write'
    /// or 'all'. The string is case-insensitive
    pub fn revoke_privilege(
        &self,
        user: &str,
        db: &str,
        privilege: &str,
    ) -> Result<(), error::Error> {
        let sql = format!(
            "Revoke {0} on {1} from {2}",
            privilege,
            serialization::quote_ident(db),
            serialization::quote_ident(user)
        );

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Create a retention policy for a database.
    /// :param duration: the duration of the new retention policy.
    ///  Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
    ///  and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
    ///  respectively. For infinite retention – meaning the data will
    ///  never be deleted – use 'INF' for duration.
    ///  The minimum retention period is 1 hour.
    pub fn create_retention_policy(
        &self,
        name: &str,
        duration: &str,
        replication: &str,
        default: bool,
        db: Option<&str>,
    ) -> Result<(), error::Error> {
        let database = {
            if let Some(t) = db {
                t
            } else {
                &self.db
            }
        };

        let sql: String = {
            if default {
                format!(
                    "Create retention policy {} on {} duration {} replication {} default",
                    serialization::quote_ident(name),
                    serialization::quote_ident(database),
                    duration,
                    replication
                )
            } else {
                format!(
                    "Create retention policy {} on {} duration {} replication {}",
                    serialization::quote_ident(name),
                    serialization::quote_ident(database),
                    duration,
                    replication
                )
            }
        };

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    /// Drop an existing retention policy for a database.
    pub fn drop_retention_policy(&self, name: &str, db: Option<&str>) -> Result<(), error::Error> {
        let database = {
            if let Some(t) = db {
                t
            } else {
                &self.db
            }
        };

        let sql = format!(
            "Drop retention policy {} on {}",
            serialization::quote_ident(name),
            serialization::quote_ident(database)
        );

        match self.query_raw(&sql, None) {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    fn send_request(
        &self,
        q: &str,
        epoch: Option<Precision>,
        chunked: bool,
    ) -> Result<Response, error::Error> {
        let mut param = vec![("db", self.db.as_str()), ("q", q)];

        if let Some(ref t) = epoch {
            param.push(("epoch", t.to_str()))
        }

        if chunked {
            param.push(("chunked", "true"));
        }

        let url = self.build_url("query", Some(param));

        let q_lower = q.to_lowercase();
        let mut res = {
            if q_lower.starts_with("select") && !q_lower.contains("into")
                || q_lower.starts_with("show")
            {
                self.client.get(url).send()?
            } else {
                self.client.post(url).send()?
            }
        };

        match res.status_raw().0 {
            200 => Ok(res),
            400 => {
                let mut context = String::new();
                let _ = res.read_to_string(&mut context);
                let json_data: Query = serde_json::from_str(&context).unwrap();

                Err(error::Error::SyntaxError(serialization::conversion(
                    &json_data.error.unwrap(),
                )))
            }
            401 | 403 => Err(error::Error::InvalidCredentials(
                "Invalid authentication credentials.".to_string(),
            )),
            _ => Err(error::Error::Unknow("There is something wrong".to_string())),
        }
    }

    /// Query and return to the native json structure
    fn query_raw(&self, q: &str, epoch: Option<Precision>) -> Result<Query, error::Error> {
        let mut response = self.send_request(q, epoch, false)?;

        let mut context = String::new();
        let _ = response.read_to_string(&mut context);

        let json_data: Query = serde_json::from_str(&context).unwrap();
        Ok(json_data)
    }

    /// Query and return to the native json structure
    fn query_raw_chunked(
        &self,
        q: &str,
        epoch: Option<Precision>,
    ) -> Result<ChunkedQuery<SerdeIoRead<Response>>, error::Error> {
        let response = self.send_request(q, epoch, true)?;
        let stream = serde_json::Deserializer::from_reader(response).into_iter::<Query>();
        Ok(stream)
    }

    /// Constructs the full URL for an API call.
    fn build_url(&self, key: &str, param: Option<Vec<(&str, &str)>>) -> Url {
        let url = Url::parse(&self.host).unwrap().join(key).unwrap();

        let mut authentication = Vec::new();

        if let Some(ref t) = self.authentication {
            authentication.push(("u", &t.0));
            authentication.push(("p", &t.1));
        }

        let url = Url::parse_with_params(url.as_str(), authentication).unwrap();

        if param.is_some() {
            Url::parse_with_params(url.as_str(), param.unwrap()).unwrap()
        } else {
            url
        }
    }
}

impl Default for Client {
    /// connecting for default database `test` and host `http://localhost:8086`
    fn default() -> Self {
        Client::new("http://localhost:8086", "test")
    }
}

/// Option for configuring the behavior of a `Client`.
#[derive(Default, Clone)]
pub struct TLSOption {
    /// A `native_tls::TlsConnector` configured as desired for HTTPS connections.
    pub connector: Option<TlsConnector>,
}

impl TLSOption {
    /// Create a new Tls_option
    pub fn new(connector: TlsConnector) -> Self {
        TLSOption {
            connector: Some(connector),
        }
    }

    fn get_connector(self) -> TlsConnector {
        self.connector.unwrap()
    }
}

#[derive(Debug)]
struct HttpClient {
    client: hyper_client,
}

impl HttpClient {
    /// Constructs a new `HttpClient`.
    fn new() -> Self {
        HttpClient {
            client: hyper_client::new(),
        }
    }

    /// Constructs a new `HttpClient` with option config.
    fn new_with_option(tls_option: Option<TLSOption>) -> Self {
        let connector = match tls_option {
            Some(tls_connector) => {
                let native_tls_client = NativeTlsClient::from(tls_connector.get_connector());
                HttpsConnector::new(native_tls_client)
            }
            None => {
                let ssl = NativeTlsClient::new().unwrap();
                HttpsConnector::new(ssl)
            }
        };

        HttpClient {
            client: hyper_client::with_connector(connector),
        }
    }

    /// Set the read timeout value for all requests.
    fn set_read_timeout(&mut self, timeout: Duration) {
        self.client.set_read_timeout(Some(timeout));
    }

    /// Set the write timeout value for all requests.
    fn set_write_timeout(&mut self, timeout: Duration) {
        self.client.set_write_timeout(Some(timeout));
    }

    /// Make a GET request to influxdb
    fn get(&self, url: Url) -> RequestBuilder {
        self.client.get(url)
    }

    /// Make a POST request to influxdb
    fn post(&self, url: Url) -> RequestBuilder {
        self.client.post(url)
    }
}

impl Default for HttpClient {
    /// Create a default `HttpClient`
    fn default() -> Self {
        HttpClient::new()
    }
}

/// Udp client
pub struct UdpClient {
    hosts: Vec<SocketAddr>,
}

impl UdpClient {
    /// Create a new udp client.
    /// panic when T can't convert to SocketAddr
    pub fn new<T: Into<String>>(address: T) -> Self {
        UdpClient {
            hosts: vec![address.into().to_socket_addrs().unwrap().next().unwrap()],
        }
    }

    /// add udp host.
    /// panic when T can't convert to SocketAddr
    pub fn add_host<T: Into<String>>(&mut self, address: T) {
        self.hosts
            .push(address.into().to_socket_addrs().unwrap().next().unwrap())
    }

    /// View current hosts
    pub fn get_host(&self) -> Vec<SocketAddr> {
        self.hosts.to_owned()
    }

    /// Send Points to influxdb.
    pub fn write_points(&self, points: Points) -> Result<(), error::Error> {
        let socket = UdpSocket::bind("0.0.0.0:0")?;

        let line = serialization::line_serialization(points);
        let line = line.as_bytes();
        socket.send_to(&line, self.hosts.as_slice())?;

        Ok(())
    }

    /// Send Point to influxdb.
    pub fn write_point(&self, point: Point) -> Result<(), error::Error> {
        let points = Points { point: vec![point] };
        self.write_points(points)
    }
}

impl FromIterator<SocketAddr> for UdpClient {
    /// Create udp client from iterator.
    fn from_iter<I: IntoIterator<Item = SocketAddr>>(iter: I) -> Self {
        let mut hosts = Vec::new();

        for i in iter {
            hosts.push(i);
        }

        UdpClient { hosts }
    }
}