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
use reqwest::Client as ReqwestClient;
use serde_json::Value;
use thiserror::Error;

/// A `LogClient` can be used to send records to the Data Collector API.
pub struct LogClient {
    api_version: String,
    inner_client: ReqwestClient,
    key: String,
    url: url::Url,
    workspace_id: String,
}

impl LogClient {
    /// Creates a new `LogClient`.
    pub fn new(
        api_version: String,
        workspace_id: String,
        key: String,
        timeout_in_seconds: u64,
    ) -> Result<Self, NewLogClientError> {
        use std::time::Duration;

        let inner_client = ReqwestClient::builder()
            .timeout(Duration::from_secs(timeout_in_seconds))
            .build()?;

        let url = Self::create_url(&workspace_id, &api_version)?;
        Ok(Self {
            api_version,
            inner_client,
            key,
            url,
            workspace_id,
        })
    }

    /// The url this `LogClient` will send records to.
    pub fn url(&self) -> &url::Url {
        &self.url
    }

    /// The Data Collector API version being used by this `LogClient`.
    pub fn api_version(&self) -> &str {
        &self.api_version
    }

    /// The Azure workspace ID of this `LogClient`.
    pub fn workspace_id(&self) -> &str {
        &self.workspace_id
    }

    fn key(&self) -> &str {
        &self.key
    }

    fn create_url(
        workspace_id: &str,
        api_version: &str,
    ) -> Result<url::Url, url::ParseError> {
        let url = format!(
            "https://{wsid}.ods.opinsights.azure.com/api/logs?api-version={ver}",
            wsid = workspace_id,
            ver = api_version
        );
        url::Url::parse(&url)
    }

    fn build_log_request(
        &self,
        key: &str,
        workspace_id: &str,
        records: Records,
    ) -> Result<reqwest::Request, RequestBuildError> {
        let body = serde_json::to_string(&records.records)?;
        let content_length = body.as_bytes().len();

        let timestamp = rfc_1123_utc_now_timestamp();

        let auth_header_val =
            auth_header_value(key, workspace_id, content_length, &timestamp)?;

        let mut req_builder = self
            .inner_client
            .post(self.url().clone())
            .header("Authorization", auth_header_val)
            .header("Content-Type", "application/json")
            .header("Log-Type", records.log_type)
            .header("x-ms-date", timestamp)
            .body(body);

        if let Some(resource_id) = records.azure_resource_id {
            req_builder =
                req_builder.header("x-ms-AzureResourceId", resource_id);
        }

        if let Some(time_generated_field) = records.time_generated_field {
            req_builder = req_builder
                .header("time-generated-field", time_generated_field);
        }

        req_builder.build().map_err(|err| err.into())
    }

    /// Log the given records to the Data Collector API.
    pub async fn log(&self, records: Records) -> Result<(), LogError> {
        let req =
            self.build_log_request(self.key(), self.workspace_id(), records)?;
        let res = self.inner_client.execute(req).await?;
        check_response(res)
    }
}

/// If the HTTP response is a success response, return Ok. Otherwise
/// return an Err.
fn check_response(res: reqwest::Response) -> Result<(), LogError> {
    let status = res.status();

    if status.is_success() {
        Ok(())
    } else {
        use reqwest::StatusCode;
        match status {
            StatusCode::BAD_REQUEST => {
                Err(LogError::BadRequest { response: res })
            }
            StatusCode::FORBIDDEN => Err(LogError::Forbidden),
            StatusCode::NOT_FOUND => Err(LogError::NotFound),
            StatusCode::TOO_MANY_REQUESTS => Err(LogError::TooManyRequests),
            StatusCode::INTERNAL_SERVER_ERROR => {
                Err(LogError::InternalServerError)
            }
            StatusCode::SERVICE_UNAVAILABLE => {
                Err(LogError::ServiceUnavailable)
            }
            _ => Err(LogError::Other { response: res }),
        }
    }
}

/// Returns a string containing the current UTC time formatted according to
/// RFC1123.
fn rfc_1123_utc_now_timestamp() -> String {
    format!(
        "{}",
        chrono::offset::Utc::now().format("%a, %d %b %Y %H:%M:%S GMT")
    )
}

fn auth_header_value(
    key: &str,
    workspace_id: &str,
    content_length: usize,
    x_ms_date: &str,
) -> Result<String, base64::DecodeError> {
    Ok(format!(
        "SharedKey {ws_id}:{sig}",
        ws_id = workspace_id,
        sig = signature(key, content_length, x_ms_date)?
    ))
}

fn signature(
    key: &str,
    content_length: usize,
    x_ms_date: &str,
) -> Result<String, base64::DecodeError> {
    use hmac::{Hmac, Mac};
    type HmacSha256 = Hmac<sha2::Sha256>;

    let str_to_sign = string_to_sign(content_length, x_ms_date);

    let decoded_key = base64::decode(key)?;
    let mut hmac = HmacSha256::new_varkey(&decoded_key)
        .expect("HMAC can take key of any size");

    hmac.input(str_to_sign.as_bytes());

    let result = hmac.result();
    // Get the underlying array using the `code()` method. Note that
    // incorrect use of the code value may permit timing attacks which defeat
    // the security provided by the `MacResult`:
    let hmac_bytes = result.code();

    let b64_str = base64::encode(&hmac_bytes);
    Ok(b64_str)
}

fn string_to_sign(content_length: usize, x_ms_date: &str) -> String {
    format!(
        "POST\n{content_length}\napplication/json\nx-ms-date:{date}\n/api/logs",
        content_length = content_length,
        date = x_ms_date
    )
}

/// Wraps a JSON value. The JSON value should contain an array of JSON objects,
/// which represent the individual records being sent to the Data Collector API.
///
/// The records in this struct will be sent in a single request to the service.
/// The number of records in this stuct should be limited such that the
/// request's size will not exceed the limits imposed by the service.
#[derive(Clone, Debug, PartialEq)]
pub struct Records {
    log_type: String,
    records: Value,
    azure_resource_id: Option<String>,
    time_generated_field: Option<String>,
}

impl Records {
    /// Construct a new `Records` struct.
    pub fn new(
        log_type: String,
        records: Value,
        azure_resource_id: Option<String>,
        time_generated_field: Option<String>,
    ) -> Result<Self, NewRecordsError> {
        Self::check_json_value(&records).map_err(NewRecordsError::new)?;
        Ok(Self {
            log_type,
            records,
            azure_resource_id,
            time_generated_field,
        })
    }

    fn check_json_value(val: &Value) -> Result<(), String> {
        if let Some(array) = val.as_array() {
            for elem in array {
                if !elem.is_object() {
                    return Err(
                        "Each element of the JSON array must be an object"
                            .into(),
                    );
                }
            }
            Ok(())
        } else {
            Err("JSON value must be an array".into())
        }
    }
}

/// Error that occur when constructing a new `Records` struct.
#[derive(Clone, Debug, Error)]
#[error("Could not create a valid `Records` struct: {msg}")]
pub struct NewRecordsError {
    msg: String,
}

impl NewRecordsError {
    fn new(msg: String) -> Self {
        Self { msg }
    }
}

/// Errors that can occur when building a HTTP request.
#[derive(Debug, Error)]
pub enum RequestBuildError {
    /// Error occurred when decoding base64.
    #[error("Could not decode base64")]
    Base64Decode(#[from] base64::DecodeError),
    /// Error occurred in the underlying HTTP library.
    #[error("HTTP error")]
    Http(#[from] reqwest::Error),
    /// Could not convert a JSON value to a UTF-8 string.
    #[error("Could not convert JSON value to a UTF-8 string")]
    JsonToString(#[from] serde_json::Error),
}

/// Errors that can occur when creating a new `LogClient`.
#[derive(Debug, Error)]
pub enum NewLogClientError {
    #[error("HTTP Error")]
    Http(#[from] reqwest::Error),
    #[error("Could not create a valid URL for this client")]
    ParseUrl(#[from] url::ParseError),
}

/// Errors that can occur when logging data to the Data Collector API.
#[derive(Debug, Error)]
pub enum LogError {
    /// Error occurred in the underlying HTTP library.
    #[error("HTTP Error")]
    Http(#[from] reqwest::Error),
    /// Error occurred when building a HTTP request.
    #[error("Could not build a HTTP request")]
    RequestBuilder(#[from] RequestBuildError),
    /// The response indicated that the request was not valid.
    #[error("The HTTP request was not valid")]
    BadRequest { response: reqwest::Response },
    /// The service failed to authenticate the request. Verify
    /// that the workspace ID and connection key are valid.
    #[error("The service failed to authenticate the request")]
    Forbidden,
    /// Either the URL provided is incorrect, or the request is too large.
    #[error(
        "Either the URL provided is incorrect, or the request is too large"
    )]
    NotFound,
    /// The service is experiencing a high volume of data from your account.
    /// Please retry the request later.
    #[error(
        "The service is experiencing a high volume of data from your account"
    )]
    TooManyRequests,
    /// The service encountered an internal error. Please retry the request.
    #[error("The service encountered an internal error")]
    InternalServerError,
    /// The service currently is unavailable to receive requests.
    /// Please retry your request.
    #[error("The service currently is unavailable to receive requests")]
    ServiceUnavailable,
    /// The HTTP reponse had an unexpected status code.
    #[error("The HTTP reponse had an unexpected status code")]
    Other { response: reqwest::Response },
}

impl LogError {
    /// Returns true if the request which caused this error can be resent.
    /// If an error is retryable, it means that the Azure documentation
    /// has indicated that it is ok to resend the failed request.
    /// 
    /// If an error is not retryable, the request should not be resent, and
    /// that error must be handled appropriately.
    /// 
    /// This function does not consider potentially retryable errors which
    /// originate from the underlying HTTP library, for example timeout errors.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::TooManyRequests => true,
            Self::InternalServerError => true,
            Self::ServiceUnavailable => true,
            _ => false,
        }
    }
}

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

    const API_VERSION: &str = "2016-04-01";

    #[tokio::test]
    async fn log_works_with_some_records() {
        let client = client();
        let records = records_from_value(json!(
            [
                {
                    "slot_ID": 12345,
                    "ID": "5cdad72f-c848-4df0-8aaa-ffe033e75d57",
                    "availability_Value": 100,
                    "performance_Value": 6.954,
                    "measurement_Name": "last_one_hour",
                    "duration": 3600,
                    "warning_Threshold": 0,
                    "critical_Threshold": 0,
                    "IsActive": "true"
                },
                {
                    "slot_ID": 67890,
                    "ID": "b6bee458-fb65-492e-996d-61c4d7fbb942",
                    "availability_Value": 100,
                    "performance_Value": 3.379,
                    "measurement_Name": "last_one_hour",
                    "duration": 3600,
                    "warning_Threshold": 0,
                    "critical_Threshold": 0,
                    "IsActive": "false"
                }
            ]
        ));
        client.log(records).await.unwrap();
    }

    #[tokio::test]
    async fn log_works_with_no_records() {
        let client = client();
        let records = records_from_value(json!([]));
        client.log(records).await.unwrap();
    }

    #[test]
    fn string_to_sign() {
        assert_eq!(
            super::string_to_sign(1024, "Mon, 04 Apr 2016 08:00:00 GMT"),
            "POST\n1024\napplication/json\nx-ms-date:Mon, 04 Apr 2016 08:00:00 GMT\n/api/logs"
        )
    }

    fn records_from_value(val: serde_json::Value) -> Records {
        Records::new("testlog".into(), val, None, None).unwrap()
    }

    fn client() -> LogClient {
        let api_version = API_VERSION.into();
        let timeout = 60;
        LogClient::new(api_version, workspace_id(), key(), timeout).unwrap()
    }

    fn workspace_id() -> String {
        std::env::var("AZURE_LOG_ANALYTICS_WORKSPACES_WORKSPACE_ID").unwrap()
    }

    fn key() -> String {
        std::env::var("AZURE_LOG_ANALYTICS_WORKSPACES_PRIMARY_KEY").unwrap()
    }
}