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
// Implement the CloudWatch Client
#![forbid(unsafe_code)]
#![deny(missing_docs)]
use anyhow::Result;
use chrono::prelude::*;
use chrono::Duration;
use crate::common::{
Bucket,
ClientConfig,
};
use log::debug;
use rusoto_cloudwatch::{
CloudWatch,
CloudWatchClient,
Dimension,
DimensionFilter,
GetMetricStatisticsInput,
GetMetricStatisticsOutput,
ListMetricsInput,
Metric,
};
/// A CloudWatch `Client`
pub struct Client {
/// The Rusoto `CloudWatchClient`.
pub client: CloudWatchClient,
/// Bucket name that was selected, if any.
pub bucket_name: Option<String>,
}
impl Client {
/// Return a new `Client` with the given `ClientConfig`.
pub fn new(config: ClientConfig) -> Self {
let bucket_name = config.bucket_name;
let region = config.region;
debug!("new: Creating CloudWatchClient in region '{}'", region.name());
let client = CloudWatchClient::new(region);
Self {
client: client,
bucket_name: bucket_name,
}
}
/// Returns a `Vec` of `GetMetricStatisticsOutput` for the given `Bucket`.
///
/// This returns a `Vec` because there is one `GetMetricStatisticsOutput`
/// for each S3 bucket storage type that CloudWatch has statistics for.
pub async fn get_metric_statistics(
&self,
bucket: &Bucket,
) -> Result<Vec<GetMetricStatisticsOutput>> {
debug!("get_metric_statistics: Processing {:?}", bucket);
let now: DateTime<Utc> = Utc::now();
let one_day = Duration::days(1);
let storage_types = match &bucket.storage_types {
Some(st) => st.to_owned(),
None => Vec::new(),
};
let inputs: Vec<GetMetricStatisticsInput> = storage_types
.iter()
.map(|storage_type| {
let dimensions = vec![
Dimension {
name: "BucketName".into(),
value: bucket.name.to_owned(),
},
Dimension {
name: "StorageType".into(),
value: storage_type.to_owned(),
},
];
GetMetricStatisticsInput {
dimensions: Some(dimensions),
end_time: self.iso8601(now),
metric_name: "BucketSizeBytes".into(),
namespace: "AWS/S3".into(),
period: one_day.num_seconds(),
start_time: self.iso8601(now - (one_day * 2)),
statistics: Some(vec!["Average".into()]),
unit: Some("Bytes".into()),
..Default::default()
}
})
.collect();
let mut outputs = Vec::new();
for input in inputs {
let output = self.client.get_metric_statistics(input).await?;
outputs.push(output);
}
Ok(outputs)
}
/// Return an ISO8601 formatted timestamp suitable for
/// `GetMetricsStatisticsInput`.
pub fn iso8601(&self, dt: DateTime<Utc>) -> String {
dt.to_rfc3339_opts(SecondsFormat::Secs, true)
}
/// Get list of buckets with `BucketSizeBytes` metrics.
///
/// An individual metric resembles the following:
/// ```rust
/// Metric {
/// metric_name: Some("BucketSizeBytes"),
/// namespace: Some("AWS/S3")
/// dimensions: Some([
/// Dimension {
/// name: "StorageType",
/// value: "StandardStorage"
/// },
/// Dimension {
/// name: "BucketName",
/// value: "some-bucket-name"
/// }
/// ]),
/// }
/// ```
pub async fn list_metrics(&self) -> Result<Vec<Metric>> {
debug!("list_metrics: Listing...");
let mut metrics = Vec::new();
let mut next_token = None;
// If we selected a bucket to list, filter for it here.
let dimensions = match self.bucket_name.as_ref() {
Some(bucket_name) => {
let filter = DimensionFilter {
name: "BucketName".into(),
value: Some(bucket_name.to_owned()),
};
Some(vec![filter])
},
None => None,
};
// We loop until we've processed everything.
loop {
// Input for CloudWatch API
let list_metrics_input = ListMetricsInput {
dimensions: dimensions.clone(),
metric_name: Some("BucketSizeBytes".into()),
namespace: Some("AWS/S3".into()),
next_token: next_token,
..Default::default()
};
// Call the API
let output = self.client.list_metrics(list_metrics_input).await?;
debug!("list_metrics: API returned: {:#?}", output);
// If we get any metrics, append them to our vec
if let Some(m) = output.metrics {
metrics.append(&mut m.clone());
}
// If there was a next token, use it, otherwise the loop is done.
match output.next_token {
Some(t) => next_token = Some(t),
None => break,
};
}
debug!("list_metrics: Metrics collection: {:#?}", metrics);
Ok(metrics)
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use rusoto_cloudwatch::{
Datapoint,
Dimension,
Metric,
};
use rusoto_mock::{
MockCredentialsProvider,
MockRequestDispatcher,
MockResponseReader,
ReadMockResponse,
};
// Create a mock CloudWatch client, returning the data from the specified
// data_file.
fn mock_client(
data_file: Option<&str>,
) -> Client {
let data = match data_file {
None => "".to_string(),
Some(d) => MockResponseReader::read_response("test-data", d.into()),
};
let client = CloudWatchClient::new_with(
MockRequestDispatcher::default().with_body(&data),
MockCredentialsProvider,
Default::default()
);
Client {
client: client,
bucket_name: None,
}
}
#[tokio::test]
async fn test_get_metric_statistics() {
let client = mock_client(
Some("cloudwatch-get-metric-statistics.xml"),
);
let storage_types = vec![
"StandardStorage".into(),
];
let bucket = Bucket {
name: "test-bucket".into(),
region: None,
storage_types: Some(storage_types),
};
let ret = Client::get_metric_statistics(&client, &bucket)
.await
.unwrap();
let datapoints = vec![
Datapoint {
average: Some(123456789.0),
timestamp: Some("2020-03-01T20:59:00Z".into()),
unit: Some("Bytes".into()),
..Default::default()
},
];
let expected = vec![
GetMetricStatisticsOutput {
datapoints: Some(datapoints),
label: Some("BucketSizeBytes".into()),
},
];
assert_eq!(ret, expected);
}
#[test]
fn test_iso8601() {
let dt = Utc.ymd(2020, 3, 1).and_hms(0, 16, 27);
let expected = "2020-03-01T00:16:27Z";
let client = mock_client(None);
let ret = Client::iso8601(&client, dt);
assert_eq!(ret, expected);
}
#[tokio::test]
async fn test_list_metrics() {
let mut client = mock_client(
Some("cloudwatch-list-metrics.xml"),
);
let ret = Client::list_metrics(&mut client).await.unwrap();
let expected = vec![
Metric {
metric_name: Some("BucketSizeBytes".into()),
namespace: Some("AWS/S3".into()),
dimensions: Some(vec![
Dimension {
name: "BucketName".into(),
value: "a-bucket-name".into(),
},
Dimension {
name: "StorageType".into(),
value: "StandardStorage".into(),
},
]),
},
Metric {
metric_name: Some("BucketSizeBytes".into()),
namespace: Some("AWS/S3".into()),
dimensions: Some(vec![
Dimension {
name: "BucketName".into(),
value: "a-bucket-name".into(),
},
Dimension {
name: "StorageType".into(),
value: "StandardIAStorage".into(),
},
]),
},
Metric {
metric_name: Some("BucketSizeBytes".into()),
namespace: Some("AWS/S3".into()),
dimensions: Some(vec![
Dimension {
name: "BucketName".into(),
value: "another-bucket-name".into(),
},
Dimension {
name: "StorageType".into(),
value: "StandardStorage".into(),
},
]),
},
];
assert_eq!(ret, expected);
}
}