livy 0.5.0

Apache Livy REST API Client
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
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
use http;
use http::Method;
use http::Method::*;
use serde::Serialize;
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::client::Client;
    ///
    /// let client = Client::new("http://example.com:8998", None, None);
    /// ```
    ///
    /// ```
    /// use livy::client::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, U: Serialize>(&self, method: Method, path: &str, data: Option<U>) -> Result<T, String> {
        http::send(method,
                   format!("{}{}", self.url, path).as_str(),
                   data,
                   self.gssnegotiate.as_ref(),
                   self.username.as_ref().map(String::as_ref))
    }

    /// Sends an HTTP GET request and returns the result.
    fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, String> {
        self.send(GET, path, None::<()>)
    }

    /// Sends an HTTP POST request and returns the result.
    fn post<T: DeserializeOwned, U: Serialize>(&self, path: &str, data: Option<U>) -> Result<T, String> {
        self.send(POST, path, data)
    }

    /// Sends an HTTP DELETE request and returns the result.
    fn delete<T: DeserializeOwned>(&self, path: &str) -> Result<T, String> {
        self.send(DELETE, path, None::<()>)
    }

    /// 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.get(format!("/sessions{}", params).as_str())
    }

    /// Creates a new session.
    ///
    /// # HTTP Request
    /// POST /sessions
    pub fn create_session(&self, new_session_request: NewSessionRequest) -> Result<Session, String> {
        self.post("/sessions", Some(new_session_request))
    }

    /// 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.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.get(format!("/sessions/{}/state", session_id).as_str())
    }

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

    /// Gets the log lines of a single session and returns them.
    ///
    /// # HTTP Request
    /// GET /sessions/{sessionId}/log
    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.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.get(format!("/sessions/{}/statements", session_id).as_str())
    }

    /// Runs a statement in a session.
    ///
    /// # HTTP Request
    /// POST /sessions/{sessionId}/statements
    pub fn run_statement(&self, session_id: i64, run_statement_request: RunStatementRequest) -> Result<Statement, String> {
        self.post(format!("/sessions/{}/statements", session_id).as_str(), Some(run_statement_request))
    }

    /// 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.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.post(format!("/sessions/{}/statements/{}/cancel", session_id, statement_id).as_str(), None::<()>)
    }

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

        self.get(format!("/batches{}", params).as_str())
    }

    /// Creates a new batch.
    ///
    /// # HTTP Request
    /// POST /batches
    pub fn create_batch(&self, new_batch_request: NewBatchRequest) -> Result<Batch, String> {
        self.post("/batches", Some(new_batch_request))
    }

    /// Gets a batch and returns it.
    ///
    /// # HTTP Request
    /// GET /batches/{batchId}
    pub fn get_batch(&self, batch_id: i64) -> Result<Batch, String> {
        self.get(format!("/batches/{}", batch_id).as_str())
    }

    /// Gets the state of batch session.
    ///
    /// # HTTP Request
    /// GET /batches/{batchId}/state
    pub fn get_batch_state(&self, batch_id: i64) -> Result<BatchStateOnly, String> {
        self.get(format!("/batches/{}/state", batch_id).as_str())
    }

    /// Kills the batch job.
    ///
    /// # HTTP Request
    /// DELETE /batches/{batchId}
    pub fn kill_batch(&self, batch_id: i64) -> Result<BatchKillResult, String> {
        self.delete(format!("/batches/{}", batch_id).as_str())
    }

    /// Gets the log lines from a batch and returns them.
    ///
    /// # HTTP Request
    /// GET /batches/{batchId}/log
    pub fn get_batch_log(&self, batch_id: i64, from: Option<i64>, size: Option<i64>) -> Result<BatchLog, String> {
        let params = http::params(vec![
            http::param("from", from),
            http::param("size", size)
        ]);

        self.get(format!("/batches/{}/log{}", batch_id, params).as_str())
    }
}

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

/// New session request information
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NewSessionRequest {
    pub kind: SessionKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy_user: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jars: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub py_files: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub driver_memory: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub driver_cores: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub executor_memory: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub executor_cores: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_executors: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archives: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conf: Option<HashMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub heartbeat_timeout_in_second: Option<i64>,
}

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

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

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

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

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

/// Run statement request
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct RunStatementRequest {
    pub code: String,
}

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

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

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

/// Batches information
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct Batches {
    pub from: Option<i64>,
    pub total: Option<i64>,
    pub sessions: Option<Vec<Batch>>,
}

/// Single batch information
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Batch {
    pub id: Option<i64>,
    pub app_id: Option<String>,
    pub app_info: Option<HashMap<String, Option<String>>>,
    pub log: Option<Vec<String>>,
    pub state: Option<String>,
}

/// New batch request information
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NewBatchRequest {
    pub file: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy_user: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub class_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jars: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub py_files: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub driver_memory: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub driver_cores: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub executor_memory: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub executor_cores: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_executors: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archives: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conf: Option<HashMap<String, String>>,
}

/// Batch information which has only its state information.
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct BatchStateOnly {
    pub id: Option<i64>,
    pub state: Option<String>,
}

/// Batch kill result
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct BatchKillResult {
    pub msg: Option<String>,
}

/// Batch log
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct BatchLog {
    pub id: Option<i64>,
    pub from: Option<i64>,
    pub total: Option<i64>,
    pub log: Option<Vec<String>>,
}

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

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

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

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

    #[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);
        }
    }
}