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
pub mod disk;
use std::{
fs::File,
io::prelude::*,
path::Path,
sync::Arc,
thread,
time::{Duration, Instant},
};
use crate::{
errors::{
Error::{Other, API},
Result,
},
utils::rfc3339,
};
use aws_sdk_ec2::{
error::DeleteKeyPairError,
model::{
Filter, Instance, InstanceState, InstanceStateName, Tag, Volume, VolumeAttachmentState,
},
types::SdkError,
Client,
};
use aws_types::SdkConfig as AwsSdkConfig;
use chrono::{DateTime, NaiveDateTime, Utc};
use hyper::{Body, Method, Request};
use log::{info, warn};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct Manager {
#[allow(dead_code)]
shared_config: AwsSdkConfig,
cli: Client,
}
impl Manager {
pub fn new(shared_config: &AwsSdkConfig) -> Self {
let cloned = shared_config.clone();
let cli = Client::new(shared_config);
Self {
shared_config: cloned,
cli,
}
}
pub async fn create_key_pair(&self, key_name: &str, key_path: &str) -> Result<()> {
let path = Path::new(key_path);
if path.exists() {
return Err(Other {
message: format!("key path {} already exists", key_path),
is_retryable: false,
});
}
info!("creating EC2 key-pair '{}'", key_name);
let ret = self.cli.create_key_pair().key_name(key_name).send().await;
let resp = match ret {
Ok(v) => v,
Err(e) => {
return Err(API {
message: format!("failed create_key_pair {:?}", e),
is_retryable: is_error_retryable(&e),
});
}
};
info!("saving EC2 key-pair '{}' to '{}'", key_name, key_path);
let key_material = resp.key_material().unwrap();
let mut f = match File::create(&path) {
Ok(f) => f,
Err(e) => {
return Err(Other {
message: format!("failed to create file {:?}", e),
is_retryable: false,
});
}
};
match f.write_all(key_material.as_bytes()) {
Ok(_) => {}
Err(e) => {
return Err(Other {
message: format!("failed to write file {:?}", e),
is_retryable: false,
});
}
}
Ok(())
}
pub async fn delete_key_pair(&self, key_name: &str) -> Result<()> {
info!("deleting EC2 key-pair '{}'", key_name);
let ret = self.cli.delete_key_pair().key_name(key_name).send().await;
match ret {
Ok(_) => {}
Err(e) => {
if !is_error_delete_key_pair_does_not_exist(&e) {
return Err(API {
message: format!("failed delete_key_pair {:?}", e),
is_retryable: is_error_retryable(&e),
});
}
warn!("key already deleted ({})", e);
}
};
Ok(())
}
pub async fn describe_volumes(
&self,
volume_id: Option<String>,
instance_id: Option<String>,
device_path: Option<String>,
) -> Result<Vec<Volume>> {
let mut filters: Vec<Filter> = vec![];
if let Some(vol_id) = volume_id {
info!("filtering volumes via volume Id {}", vol_id);
filters.push(
Filter::builder()
.set_name(Some(String::from("volume-id")))
.set_values(Some(vec![vol_id]))
.build(),
);
} else {
let inst_id = if let Some(inst_id) = instance_id {
inst_id
} else {
fetch_instance_id().await?
};
info!("filtering volumes via instance Id {}", inst_id);
filters.push(
Filter::builder()
.set_name(Some(String::from("attachment.instance-id")))
.set_values(Some(vec![inst_id.clone()]))
.build(),
);
if let Some(dpath) = device_path {
info!("filtering volumes via device {}", dpath);
filters.push(
Filter::builder()
.set_name(Some(String::from("attachment.device")))
.set_values(Some(vec![dpath]))
.build(),
);
}
}
let resp = match self
.cli
.describe_volumes()
.set_filters(Some(filters))
.send()
.await
{
Ok(r) => r,
Err(e) => {
return Err(API {
message: format!("failed describe_volumes {:?}", e),
is_retryable: is_error_retryable(&e),
});
}
};
let volumes = if let Some(vols) = resp.volumes {
vols
} else {
Vec::new()
};
info!("described {} volumes", volumes.len());
Ok(volumes)
}
pub async fn find_local_volume(
&self,
instance_id: Option<String>,
device_name: &str,
) -> Result<Volume> {
let inst_id = if let Some(inst_id) = instance_id {
inst_id
} else {
fetch_instance_id().await?
};
let device_path = if device_name.starts_with("/dev/") {
device_name.to_string()
} else {
format!("/dev/{}", device_name).to_string()
};
info!("fetching EBS volume for '{}' on '{}'", inst_id, device_path);
let volumes = self
.describe_volumes(None, Some(inst_id), Some(device_path.to_string()))
.await?;
if volumes.is_empty() {
return Err(API {
message: "no volume found".to_string(),
is_retryable: false,
});
}
if volumes.len() != 1 {
return Err(API {
message: format!("unexpected volume devices found {}", volumes.len()),
is_retryable: false,
});
}
let volume = volumes[0].clone();
return Ok(volume);
}
pub async fn poll_local_volume_attachment_state(
&self,
instance_id: Option<String>,
device_name: &str,
desired_attachment_state: VolumeAttachmentState,
timeout: Duration,
interval: Duration,
) -> Result<Volume> {
let inst_id = if let Some(inst_id) = instance_id {
inst_id
} else {
fetch_instance_id().await?
};
let device_path = if device_name.starts_with("/dev/") {
device_name.to_string()
} else {
format!("/dev/{}", device_name).to_string()
};
info!(
"polling volume attachment state '{}' '{}' with desired state {:?} for timeout {:?} and interval {:?}",
inst_id, device_path, desired_attachment_state, timeout, interval,
);
let start = Instant::now();
let mut cnt: u128 = 0;
loop {
let elapsed = start.elapsed();
if elapsed.gt(&timeout) {
break;
}
let itv = {
if cnt == 0 {
Duration::from_secs(1)
} else {
interval
}
};
thread::sleep(itv);
let volume = self
.find_local_volume(Some(inst_id.clone()), &device_path)
.await?;
if volume.attachments().is_none() {
warn!("no attachment found");
continue;
}
let attachments = volume.attachments().unwrap();
if attachments.is_empty() {
warn!("no attachment found");
continue;
}
if attachments.len() != 1 {
warn!("unexpected attachment found {}", attachments.len());
continue;
}
let current_attachment_state = attachments[0].state().unwrap();
info!(
"poll (current volume attachment state {:?}, elapsed {:?})",
current_attachment_state, elapsed
);
if current_attachment_state.eq(&desired_attachment_state) {
return Ok(volume);
}
cnt += 1;
}
return Err(Other {
message: format!("failed to poll volume state for '{}' in time", inst_id),
is_retryable: true,
});
}
pub async fn fetch_tags(&self, instance_id: Arc<String>) -> Result<Vec<Tag>> {
info!("fetching tags for '{}'", instance_id);
let ret = self
.cli
.describe_instances()
.instance_ids(instance_id.to_string())
.send()
.await;
let resp = match ret {
Ok(r) => r,
Err(e) => {
return Err(API {
message: format!("failed describe_instances {:?}", e),
is_retryable: is_error_retryable(&e),
});
}
};
let reservations = match resp.reservations {
Some(rvs) => rvs,
None => {
return Err(API {
message: String::from("empty reservation from describe_instances response"),
is_retryable: false,
});
}
};
if reservations.len() != 1 {
return Err(API {
message: format!(
"expected only 1 reservation from describe_instances response but got {}",
reservations.len()
),
is_retryable: false,
});
}
let rvs = reservations.get(0).unwrap();
let instances = rvs.instances.to_owned().unwrap();
if instances.len() != 1 {
return Err(API {
message: format!(
"expected only 1 instance from describe_instances response but got {}",
instances.len()
),
is_retryable: false,
});
}
let instance = instances.get(0).unwrap();
let tags = match instance.tags.to_owned() {
Some(ss) => ss,
None => {
return Err(API {
message: String::from("empty tags from describe_instances response"),
is_retryable: false,
});
}
};
info!("fetched {} tags for '{}'", tags.len(), instance_id);
Ok(tags)
}
pub async fn list_asg(&self, asg_name: &str) -> Result<Vec<Droplet>> {
let filter = Filter::builder()
.set_name(Some(String::from("tag:aws:autoscaling:groupName")))
.set_values(Some(vec![String::from(asg_name)]))
.build();
let resp = match self
.cli
.describe_instances()
.set_filters(Some(vec![filter]))
.send()
.await
{
Ok(r) => r,
Err(e) => {
return Err(API {
message: format!("failed describe_instances {:?}", e),
is_retryable: is_error_retryable(&e),
});
}
};
let reservations = match resp.reservations {
Some(rvs) => rvs,
None => {
warn!("empty reservation from describe_instances response");
return Ok(vec![]);
}
};
let mut droplets: Vec<Droplet> = Vec::new();
for rsv in reservations.iter() {
let instances = rsv.instances().unwrap();
for instance in instances {
let instance_id = instance.instance_id().unwrap();
info!("instance {}", instance_id);
droplets.push(Droplet::new(instance));
}
}
Ok(droplets)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct Droplet {
pub instance_id: String,
#[serde(with = "rfc3339::serde_format")]
pub launched_at_utc: DateTime<Utc>,
pub instance_state_code: i32,
pub instance_state_name: String,
pub availability_zone: String,
pub public_hostname: String,
pub public_ipv4: String,
}
impl Droplet {
pub fn new(inst: &Instance) -> Self {
let instance_id = match inst.instance_id.to_owned() {
Some(v) => v,
None => String::new(),
};
let launch_time = inst.launch_time().unwrap();
let native_dt = NaiveDateTime::from_timestamp(launch_time.secs(), 0);
let launched_at_utc = DateTime::<Utc>::from_utc(native_dt, Utc);
let instance_state = match inst.state.to_owned() {
Some(v) => v,
None => InstanceState::builder().build(),
};
let instance_state_code = instance_state.code.unwrap_or(0);
let instance_state_name = instance_state
.name
.unwrap_or_else(|| InstanceStateName::Unknown(String::from("unknown")));
let instance_state_name = instance_state_name.as_str().to_string();
let availability_zone = match inst.placement.to_owned() {
Some(v) => match v.availability_zone {
Some(v2) => v2,
None => String::new(),
},
None => String::new(),
};
let public_hostname = inst
.public_dns_name
.to_owned()
.unwrap_or_else(|| String::from(""));
let public_ipv4 = inst
.public_ip_address
.to_owned()
.unwrap_or_else(|| String::from(""));
Self {
instance_id,
launched_at_utc,
instance_state_code,
instance_state_name,
availability_zone,
public_hostname,
public_ipv4,
}
}
}
#[inline]
pub fn is_error_retryable<E>(e: &SdkError<E>) -> bool {
match e {
SdkError::TimeoutError(_) | SdkError::ResponseError { .. } => true,
SdkError::DispatchFailure(e) => e.is_timeout() || e.is_io(),
_ => false,
}
}
#[inline]
fn is_error_delete_key_pair_does_not_exist(e: &SdkError<DeleteKeyPairError>) -> bool {
match e {
SdkError::ServiceError { err, .. } => {
let msg = format!("{:?}", err);
msg.contains("does not exist")
}
_ => false,
}
}
pub async fn fetch_instance_id() -> Result<String> {
fetch_metadata("instance-id").await
}
pub async fn fetch_public_hostname() -> Result<String> {
fetch_metadata("public-hostname").await
}
pub async fn fetch_public_ipv4() -> Result<String> {
fetch_metadata("public-ipv4").await
}
pub async fn fetch_availability_zone() -> Result<String> {
fetch_metadata("placement/availability-zone").await
}
pub async fn fetch_region() -> Result<String> {
let mut az = fetch_availability_zone().await?;
az.truncate(az.len() - 1);
Ok(az)
}
async fn fetch_metadata(path: &str) -> Result<String> {
info!("fetching meta-data/{}", path);
let uri = format!("http://169.254.169.254/latest/meta-data/{}", path);
let token = fetch_token().await?;
let req = match Request::builder()
.method(Method::GET)
.uri(uri)
.header("X-aws-ec2-metadata-token", token)
.body(Body::empty())
{
Ok(r) => r,
Err(e) => {
return Err(API {
message: format!("failed to build GET meta-data/{} {:?}", path, e),
is_retryable: false,
});
}
};
let ret = http_manager::read_bytes(req, Duration::from_secs(5), false, true).await;
let rs = match ret {
Ok(bytes) => {
let s = match String::from_utf8(bytes.to_vec()) {
Ok(text) => text,
Err(e) => {
return Err(API {
message: format!(
"GET meta-data/{} returned unexpected bytes {:?} ({})",
path, bytes, e
),
is_retryable: false,
});
}
};
s
}
Err(e) => {
return Err(API {
message: format!("failed GET meta-data/{} {:?}", path, e),
is_retryable: false,
})
}
};
Ok(rs)
}
const IMDS_V2_SESSION_TOKEN_URI: &str = "http://169.254.169.254/latest/api/token";
async fn fetch_token() -> Result<String> {
info!("fetching IMDS v2 token");
let req = match Request::builder()
.method(Method::PUT)
.uri(IMDS_V2_SESSION_TOKEN_URI)
.header("X-aws-ec2-metadata-token-ttl-seconds", "21600")
.body(Body::empty())
{
Ok(r) => r,
Err(e) => {
return Err(API {
message: format!("failed to build PUT api/token {:?}", e),
is_retryable: false,
});
}
};
let ret = http_manager::read_bytes(req, Duration::from_secs(5), false, true).await;
let token = match ret {
Ok(bytes) => {
let s = match String::from_utf8(bytes.to_vec()) {
Ok(text) => text,
Err(e) => {
return Err(API {
message: format!(
"PUT api/token returned unexpected bytes {:?} ({})",
bytes, e
),
is_retryable: false,
});
}
};
s
}
Err(e) => {
return Err(API {
message: format!("failed PUT api/token {:?}", e),
is_retryable: false,
})
}
};
Ok(token)
}