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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
use http;
use http::Method;
use http::Method::*;
use serde::de::DeserializeOwned;
use std::collections::HashMap;

/// Apache Livy REST API client
pub struct Client {
    url: String,
    gssnegotiate: Option<bool>,
    username: Option<String>,
}

impl Client {
    /// Constructs a new `Client`.
    ///
    /// # Examples
    /// ```
    /// use livy::v0_3_0::Client;
    ///
    /// let client = Client::new("http://example.com:8998", None, None);
    /// ```
    ///
    /// ```
    /// use livy::v0_3_0::Client;
    ///
    /// let client = Client::new("http://example.com:8998", Some(true), Some("username".to_string()));
    /// ```
    pub fn new(url: &str, gssnegotiate: Option<bool>, username: Option<String>) -> Client {
        Client {
            url: http::remove_trailing_slash(url),
            gssnegotiate,
            username,
        }
    }

    /// Sends an HTTP request and returns the result.
    fn send<T: DeserializeOwned>(&self, method: Method, path: &str) -> Result<T, String> {
        http::send(method,
                   format!("{}{}", self.url, path).as_str(),
                   self.gssnegotiate.as_ref(),
                   self.username.as_ref().map(String::as_ref))
    }

    /// Gets information of sessions and returns it.
    ///
    /// # HTTP Request
    /// GET /sessions
    pub fn get_sessions(&self, from: Option<i64>, size: Option<i64>) -> Result<Sessions, String> {
        let params = http::params(vec![
            http::param("from", from),
            http::param("size", size)
        ]);

        self.send(GET, format!("/sessions{}", params).as_str())
    }

    /// Gets information of a single session and returns it.
    ///
    /// # HTTP Request
    /// GET /sessions/{sessionId}
    pub fn get_session(&self, session_id: i64) -> Result<Session, String> {
        self.send(GET, format!("/sessions/{}", session_id).as_str())
    }

    /// Gets session state information of a single session and returns it.
    ///
    /// # HTTP Request
    /// GET /sessions/{sessionId}/state
    pub fn get_session_state(&self, session_id: i64) -> Result<SessionStateOnly, String> {
        self.send(GET, format!("/sessions/{}/state", session_id).as_str())
    }

    /// Deletes the session whose id is equal to `session_id`.
    ///
    /// # HTTP Request
    /// DELETE /sessions/{sessionId}
    pub fn delete_session(&self, session_id: i64) -> Result<SessionDeleteResult, String> {
        self.send(DELETE, format!("/sessions/{}", session_id).as_str())
    }

    /// Gets the log lines of a single session and returns them.
    ///
    /// # HTTP Request
    /// GET /sessions/{sessionId}/logs
    pub fn get_session_log(&self, session_id: i64, from: Option<i64>, size: Option<i64>)-> Result<SessionLog, String> {
        let params = http::params(vec![
            http::param("from", from),
            http::param("size", size)
        ]);

        self.send(GET, format!("/sessions/{}/log{}", session_id, params).as_str())
    }

    /// Gets the statements of a single session and returns them.
    ///
    /// # HTTP Request
    /// GET /sessions/{sessionId}/statements
    pub fn get_statements(&self, session_id: i64) -> Result<Statements, String> {
        self.send(GET, format!("/sessions/{}/statements", session_id).as_str())
    }

    /// Gets a single statement of a single session and returns it.
    ///
    /// # HTTP Request
    /// GET /sessions/{sessionId}/statements/{statementId}
    pub fn get_statement(&self, session_id: i64, statement_id: i64) -> Result<Statement, String> {
        self.send(GET, format!("/sessions/{}/statements/{}", session_id, statement_id).as_str())
    }

    /// Cancel a single statement.
    ///
    /// # HTTP Request
    /// POST /sessions/{sessionId}/statements/{statementId}/cancel
    pub fn cancel_statement(&self, session_id: i64, statement_id: i64) -> Result<StatementCancelResult, String> {
        self.send(POST, format!("/sessions/{}/statements/{}/cancel", session_id, statement_id).as_str())
    }
}

/// Active interactive sessions
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Sessions {
    from: Option<i64>,
    total: Option<i64>,
    sessions: Option<Vec<Session>>,
}

impl Sessions {
    /// Returns `from` of the sessions.
    pub fn from(&self) -> Option<i64> {
        self.from
    }

    /// Returns `total` of the sessions.
    pub fn total(&self) -> Option<i64> {
        self.total
    }

    /// Returns `sessions` of the sessions.
    pub fn sessions(&self) -> Option<&Vec<Session>> {
        self.sessions.as_ref()
    }
}

/// Session which represents an interactive shell
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Session {
    id: Option<i64>,
    app_id: Option<String>,
    owner: Option<String>,
    proxy_user: Option<String>,
    kind: Option<SessionKind>,
    log: Option<Vec<String>>,
    state: Option<SessionState>,
    app_info: Option<HashMap<String, Option<String>>>,
}

impl Session {
    /// Returns `id` of the session.
    pub fn id(&self) -> Option<i64> {
        self.id
    }

    /// Returns `app_id` of the session.
    pub fn app_id(&self) -> Option<&str> {
        self.app_id.as_ref().map(String::as_str)
    }

    /// Returns `owner` of the session.
    pub fn owner(&self) -> Option<&str> {
        self.owner.as_ref().map(String::as_str)
    }

    /// Returns `proxy_user` of the session.
    pub fn proxy_user(&self) -> Option<&str> {
        self.proxy_user.as_ref().map(String::as_str)
    }

    /// Returns `kind` of the session.
    pub fn kind(&self) -> Option<&SessionKind> {
        self.kind.as_ref()
    }

    /// Returns `log` of the session.
    pub fn log(&self) -> Option<&Vec<String>> {
        self.log.as_ref()
    }

    /// Returns `state` of the session.
    pub fn state(&self) -> Option<&SessionState> {
        self.state.as_ref()
    }

    /// Returns `app_info` of the session.
    pub fn app_info(&self) -> Option<&HashMap<String, Option<String>>> {
        self.app_info.as_ref()
    }
}

/// Session information which has only its state information
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SessionStateOnly {
    id: Option<i64>,
    state: Option<SessionState>,
}

impl SessionStateOnly {
    /// Returns `id` of the session.
    pub fn id(&self) -> Option<i64> {
        self.id
    }

    /// Returns `state` of the session.
    pub fn state(&self) -> Option<&SessionState> {
        self.state.as_ref()
    }
}

/// Session delete result
#[derive(Debug, Deserialize, PartialEq)]
pub struct SessionDeleteResult {
    msg: Option<String>,
}

impl SessionDeleteResult {
    /// Returns `msg` of the session delete result.
    pub fn msg(&self) -> Option<&str> {
        self.msg.as_ref().map(String::as_str)
    }
}

/// Session log
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SessionLog {
    id: Option<i64>,
    from: Option<i64>,
    total: Option<i64>,
    log: Option<Vec<String>>,
}

impl SessionLog {
    /// Returns `id` of the session.
    pub fn id(&self) -> Option<i64> {
        self.id
    }

    /// Returns `from` of the session log.
    pub fn from(&self) -> Option<i64> {
        self.from
    }

    /// Returns `total` of the session log.
    pub fn total(&self) -> Option<i64> {
        self.total
    }
    /// Returns `log` of the session log.
    pub fn log(&self) -> Option<&Vec<String>> {
        self.log.as_ref()
    }
}

/// Statements
#[derive(Debug, Deserialize, PartialEq)]
pub struct Statements {
    total_statements: Option<i64>,
    statements: Option<Vec<Statement>>,
}

impl Statements {
    /// Returns `total_statements` of the statements.
    pub fn total_statements(&self) -> Option<i64> {
        self.total_statements
    }

    /// Returns `statements` of the statements.
    pub fn statements(&self) -> Option<&Vec<Statement>> {
        self.statements.as_ref()
    }
}

/// Statement
#[derive(Debug, Deserialize, PartialEq)]
pub struct Statement {
    id: Option<i64>,
    state: Option<StatementState>,
    output: Option<StatementOutput>,
}

impl Statement {
    /// Returns `id` of the statement.
    pub fn id(&self) -> Option<i64> {
        self.id
    }

    /// Returns `state` of the statement.
    pub fn state(&self) -> Option<&StatementState> {
        self.state.as_ref()
    }

    /// Returns `output` of the statement.
    pub fn output(&self) -> Option<&StatementOutput> {
        self.output.as_ref()
    }
}

/// Statement output
#[derive(Debug, Deserialize, PartialEq)]
pub struct StatementOutput {
    status: Option<String>,
    execution_count: Option<i64>,
    data: Option<HashMap<String, Option<String>>>,
}

impl StatementOutput {
    /// Returns `status` of the statement output.
    pub fn status(&self) -> Option<&str> {
        self.status.as_ref().map(String::as_str)
    }

    /// Returns `execution_count` of the statement output.
    pub fn execution_count(&self) -> Option<i64> {
        self.execution_count
    }

    /// Returns `data` of the statement output.
    pub fn data(&self) -> Option<&HashMap<String, Option<String>>> {
        self.data.as_ref()
    }
}

/// Statement cancel result
#[derive(Debug, Deserialize, PartialEq)]
pub struct StatementCancelResult {
    msg: Option<String>,
}

impl StatementCancelResult {
    /// Returns `msg` of the statement cancel result.
    pub fn msg(&self) -> Option<&str> {
        self.msg.as_ref().map(String::as_str)
    }
}

/// Session state
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum SessionState {
    NotStarted,
    Starting,
    Idle,
    Busy,
    ShuttingDown,
    Error,
    Dead,
    Success,
}

/// Session kind
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum SessionKind {
    Spark,
    Pyspark,
    Pyspark3,
    Sparkr,
}

/// Statement state
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum StatementState {
    Waiting,
    Running,
    Available,
    Error,
    Cancelling,
    Cancelled,
}

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

    impl Sessions {
        fn some() -> Sessions {
            Sessions {
                from: Some(0),
                total: Some(1),
                sessions: Some(Vec::new()),
            }
        }

        fn none() -> Sessions {
            Sessions {
                from: None,
                total: None,
                sessions: None,
            }
        }
    }

    impl Session {
        fn some() -> Session {
            Session {
                id: Some(0),
                app_id: Some("app_id".to_string()),
                owner: Some("owner".to_string()),
                proxy_user: Some("proxy_user".to_string()),
                kind: Some(SessionKind::Spark),
                log: Some(Vec::new()),
                state: Some(SessionState::NotStarted),
                app_info: Some(HashMap::new()),
            }
        }

        fn none() -> Session {
            Session {
                id: None,
                app_id: None,
                owner: None,
                proxy_user: None,
                kind: None,
                log: None,
                state: None,
                app_info: None,
            }
        }
    }

    impl SessionStateOnly {
        fn some() -> SessionStateOnly {
            SessionStateOnly {
                id: Some(0),
                state: Some(SessionState::NotStarted),
            }
        }

        fn none() -> SessionStateOnly {
            SessionStateOnly {
                id: None,
                state: None,
            }
        }
    }

    impl SessionDeleteResult {
        fn some() -> SessionDeleteResult {
            SessionDeleteResult {
                msg: Some(String::new()),
            }
        }

        fn none() -> SessionDeleteResult {
            SessionDeleteResult {
                msg: None,
            }
        }
    }

    impl SessionLog {
        fn some() -> SessionLog {
            SessionLog {
                id: Some(0),
                from: Some(1),
                total: Some(2),
                log: Some(Vec::new()),
            }
        }

        fn none() -> SessionLog {
            SessionLog {
                id: None,
                from: None,
                total: None,
                log: None,
            }
        }
    }

    impl Statements {
        fn some() -> Statements {
            Statements {
                total_statements: Some(0),
                statements: Some(Vec::new()),
            }
        }

        fn none() -> Statements {
            Statements {
                total_statements: None,
                statements: None,
            }
        }
    }

    impl Statement {
        fn some() -> Statement {
            Statement {
                id: Some(0),
                state: Some(StatementState::Waiting),
                output: Some(StatementOutput::some()),
            }
        }

        fn none() -> Statement {
            Statement {
                id: None,
                state: None,
                output: None,
            }
        }
    }

    impl StatementOutput {
        fn some() -> StatementOutput {
            StatementOutput {
                status: Some("status".to_string()),
                execution_count: Some(0),
                data: Some(HashMap::new()),
            }
        }

        fn none() -> StatementOutput {
            StatementOutput {
                status: None,
                execution_count: None,
                data: None,
            }
        }
    }

    impl StatementCancelResult {
        fn some() -> StatementCancelResult {
            StatementCancelResult {
                msg: Some(String::new()),
            }
        }

        fn none() -> StatementCancelResult {
            StatementCancelResult {
                msg: None,
            }
        }
    }

    #[test]
    fn test_client_new() {
        struct TestCase {
            url: &'static str,
            expected_url: String,
            gssnegotiate: Option<bool>,
            username: Option<String>,
        }

        let test_cases = vec![
            TestCase {
                url: "http://example.com:8998",
                expected_url: "http://example.com:8998".to_string(),
                gssnegotiate: None,
                username: None,
            },
            TestCase {
                url: "http://example.com:8998/",
                expected_url: "http://example.com:8998".to_string(),
                gssnegotiate: Some(false),
                username: Some("".to_string()),
            },
            TestCase {
                url: "http://example.com:8998",
                expected_url: "http://example.com:8998".to_string(),
                gssnegotiate: Some(true),
                username: Some("user".to_string()),
            },
        ];

        for test_case in test_cases {
            let client = Client::new(test_case.url, test_case.gssnegotiate.clone(), test_case.username.clone());

            assert_eq!(test_case.expected_url, client.url);
            assert_eq!(test_case.gssnegotiate, client.gssnegotiate);
            assert_eq!(test_case.username, client.username);
        }
    }

    #[test]
    fn test_sessions_from() {
        for sessions in vec![Sessions::some(), Sessions::none()] {
            assert_eq!(sessions.from, sessions.from());
        }
    }

    #[test]
    fn test_sessions_total() {
        for sessions in vec![Sessions::some(), Sessions::none()] {
            assert_eq!(sessions.total, sessions.total());
        }
    }

    #[test]
    fn test_sessions_sessions() {
        for sessions in vec![Sessions::some(), Sessions::none()] {
            assert_eq!(sessions.sessions.as_ref(), sessions.sessions());
        }
    }

    #[test]
    fn test_session_id() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.id, session.id());
        }
    }

    #[test]
    fn test_session_app_id() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.app_id.as_ref().map(String::as_str), session.app_id());
        }
    }

    #[test]
    fn test_session_owner() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.owner.as_ref().map(String::as_str), session.owner());
        }
    }

    #[test]
    fn test_session_proxy_user() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.proxy_user.as_ref().map(String::as_str), session.proxy_user());
        }
    }

    #[test]
    fn test_session_kind() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.kind.as_ref(), session.kind());
        }
    }

    #[test]
    fn test_session_log() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.log.as_ref(), session.log());
        }
    }

    #[test]
    fn test_session_state() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.state.as_ref(), session.state());
        }
    }

    #[test]
    fn test_session_app_info() {
        for session in vec![Session::some(), Session::none()] {
            assert_eq!(session.app_info.as_ref(), session.app_info());
        }
    }

    #[test]
    fn test_session_state_only_id() {
        for session_state_only in vec![SessionStateOnly::some(), SessionStateOnly::none()] {
            assert_eq!(session_state_only.id, session_state_only.id());
        }
    }

    #[test]
    fn test_session_state_only_state() {
        for session_state_only in vec![SessionStateOnly::some(), SessionStateOnly::none()] {
            assert_eq!(session_state_only.state.as_ref(), session_state_only.state());
        }
    }

    #[test]
    fn test_session_delete_result_msg() {
        for session_delete_result in vec![SessionDeleteResult::some(), SessionDeleteResult::none()] {
            assert_eq!(session_delete_result.msg.as_ref().map(String::as_str), session_delete_result.msg());
        }
    }

    #[test]
    fn test_session_log_id() {
        for session_log in vec![SessionLog::some(), SessionLog::none()] {
            assert_eq!(session_log.id, session_log.id());
        }
    }

    #[test]
    fn test_session_log_from() {
        for session_log in vec![SessionLog::some(), SessionLog::none()] {
            assert_eq!(session_log.from, session_log.from());
        }
    }

    #[test]
    fn test_session_log_total() {
        for session_log in vec![SessionLog::some(), SessionLog::none()] {
            assert_eq!(session_log.total, session_log.total());
        }
    }

    #[test]
    fn test_session_log_log() {
        for session_log in vec![SessionLog::some(), SessionLog::none()] {
            assert_eq!(session_log.log.as_ref(), session_log.log());
        }
    }

    #[test]
    fn test_statements_total_statements() {
        for statements in vec![Statements::some(), Statements::none()] {
            assert_eq!(statements.total_statements, statements.total_statements());
        }
    }

    #[test]
    fn test_statements_statements() {
        for statements in vec![Statements::some(), Statements::none()] {
            assert_eq!(statements.statements.as_ref(), statements.statements());
        }
    }

    #[test]
    fn test_statement_id() {
        for statement in vec![Statement::some(), Statement::none()] {
            assert_eq!(statement.id, statement.id());
        }
    }

    #[test]
    fn test_statement_state() {
        for statement in vec![Statement::some(), Statement::none()] {
            assert_eq!(statement.state.as_ref(), statement.state());
        }
    }

    #[test]
    fn test_statement_output() {
        for statement in vec![Statement::some(), Statement::none()] {
            assert_eq!(statement.output.as_ref(), statement.output());
        }
    }

    #[test]
    fn test_statement_output_status() {
        for statement_output in vec![StatementOutput::some(), StatementOutput::none()] {
            assert_eq!(statement_output.status.as_ref().map(String::as_str), statement_output.status());
        }
    }

    #[test]
    fn test_statement_output_execution_count() {
        for statement_output in vec![StatementOutput::some(), StatementOutput::none()] {
            assert_eq!(statement_output.execution_count, statement_output.execution_count());
        }
    }

    #[test]
    fn test_statement_output_data() {
        for statement_output in vec![StatementOutput::some(), StatementOutput::none()] {
            assert_eq!(statement_output.data.as_ref(), statement_output.data());
        }
    }

    #[test]
    fn test_statement_cancel_result_msg() {
        for statement_cancel_result in vec![StatementCancelResult::some(), StatementCancelResult::none()] {
            assert_eq!(statement_cancel_result.msg.as_ref().map(String::as_str), statement_cancel_result.msg());
        }
    }
}