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
use crate::errors::{
    Error::{Other, API},
    Result,
};
use aws_sdk_cloudformation::{
    error::{DeleteStackError, DescribeStacksError},
    model::{Capability, OnFailure, Output, Parameter, StackStatus, Tag},
    types::SdkError,
    Client,
};
use aws_types::SdkConfig as AwsSdkConfig;
use tokio::time::{sleep, Duration, Instant};

/// Implements AWS CloudFormation manager.
#[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 fn client(&self) -> Client {
        self.cli.clone()
    }

    /// Creates a CloudFormation stack.
    /// The separate caller is expected to poll the status asynchronously.
    pub async fn create_stack(
        &self,
        stack_name: &str,
        capabilities: Option<Vec<Capability>>,
        on_failure: OnFailure,
        template_body: &str,
        tags: Option<Vec<Tag>>,
        parameters: Option<Vec<Parameter>>,
    ) -> Result<Stack> {
        log::info!("creating stack '{}'", stack_name);
        let ret = self
            .cli
            .create_stack()
            .stack_name(stack_name)
            .set_capabilities(capabilities)
            .on_failure(on_failure)
            .template_body(template_body)
            .set_tags(tags)
            .set_parameters(parameters)
            .send()
            .await;
        let resp = match ret {
            Ok(v) => v,
            Err(e) => {
                return Err(API {
                    message: format!("failed create_stack {:?}", e),
                    is_retryable: is_error_retryable(&e),
                });
            }
        };

        let stack_id = resp.stack_id().unwrap();
        log::info!("created stack '{}' with '{}'", stack_name, stack_id);
        Ok(Stack::new(
            stack_name,
            stack_id,
            StackStatus::CreateInProgress,
            None,
        ))
    }

    /// Deletes a CloudFormation stack.
    /// The separate caller is expected to poll the status asynchronously.
    pub async fn delete_stack(&self, stack_name: &str) -> Result<Stack> {
        log::info!("deleting stack '{}'", stack_name);
        let ret = self.cli.delete_stack().stack_name(stack_name).send().await;
        match ret {
            Ok(_) => {}
            Err(e) => {
                if !is_error_delete_stack_does_not_exist(&e) {
                    return Err(API {
                        message: format!("failed schedule_key_deletion {:?}", e),
                        is_retryable: is_error_retryable(&e),
                    });
                }
                log::warn!("stack already deleted so returning DeleteComplete status (original error '{}')", e);
                return Ok(Stack::new(
                    stack_name,
                    "",
                    StackStatus::DeleteComplete,
                    None,
                ));
            }
        };

        Ok(Stack::new(
            stack_name,
            "",
            StackStatus::DeleteInProgress,
            None,
        ))
    }

    /// Polls CloudFormation stack status.
    pub async fn poll_stack(
        &self,
        stack_name: &str,
        desired_status: StackStatus,
        timeout: Duration,
        interval: Duration,
    ) -> Result<Stack> {
        log::info!(
            "polling stack '{}' with desired status {:?} for timeout {:?} and interval {:?}",
            stack_name,
            desired_status,
            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 {
                    // first poll with no wait
                    Duration::from_secs(1)
                } else {
                    interval
                }
            };
            sleep(itv).await;

            let ret = self
                .cli
                .describe_stacks()
                .stack_name(stack_name)
                .send()
                .await;
            let stacks = match ret {
                Ok(v) => v.stacks,
                Err(e) => {
                    // CFN should fail for non-existing stack, instead of returning 0 stack
                    if is_error_describe_stacks_does_not_exist(&e)
                        && desired_status.eq(&StackStatus::DeleteComplete)
                    {
                        log::info!("stack already deleted as desired");
                        return Ok(Stack::new(stack_name, "", desired_status, None));
                    }
                    return Err(API {
                        message: format!("failed describe_stacks {:?}", e),
                        is_retryable: is_error_retryable(&e),
                    });
                }
            };
            let stacks = stacks.unwrap();
            if stacks.len() != 1 {
                // CFN should fail for non-existing stack, instead of returning 0 stack
                return Err(Other {
                    message: String::from("failed to find stack"),
                    is_retryable: false,
                });
            }

            let stack = stacks.get(0).unwrap();
            let current_id = stack.stack_id().unwrap();
            let current_stack_status = stack.stack_status().unwrap();
            log::info!(
                "poll (current stack status {:?}, elapsed {:?})",
                current_stack_status,
                elapsed
            );

            if desired_status.ne(&StackStatus::DeleteComplete)
                && current_stack_status.eq(&StackStatus::DeleteComplete)
            {
                return Err(Other {
                    message: String::from("stack create/update failed thus deleted"),
                    is_retryable: false,
                });
            }

            if desired_status.eq(&StackStatus::CreateComplete)
                && current_stack_status.eq(&StackStatus::CreateFailed)
            {
                return Err(Other {
                    message: String::from("stack create failed"),
                    is_retryable: false,
                });
            }

            if desired_status.eq(&StackStatus::DeleteComplete)
                && current_stack_status.eq(&StackStatus::DeleteFailed)
            {
                return Err(Other {
                    message: String::from("stack delete failed"),
                    is_retryable: false,
                });
            }

            if current_stack_status.eq(&desired_status) {
                let outputs = stack.outputs();
                let outputs = outputs.unwrap();
                let outputs = Vec::from(outputs);
                let current_stack = Stack::new(
                    stack_name,
                    current_id,
                    current_stack_status.clone(),
                    Some(outputs),
                );
                return Ok(current_stack);
            }

            cnt += 1;
        }

        Err(Other {
            message: format!("failed to poll stack {} in time", stack_name),
            is_retryable: true,
        })
    }
}

/// Represents the CloudFormation stack.
#[derive(Debug)]
pub struct Stack {
    pub name: String,
    pub id: String,
    pub status: StackStatus,
    pub outputs: Option<Vec<Output>>,
}

impl Stack {
    pub fn new(name: &str, id: &str, status: StackStatus, outputs: Option<Vec<Output>>) -> Self {
        // ref. https://doc.rust-lang.org/1.0.0/style/ownership/constructors.html
        Self {
            name: String::from(name),
            id: String::from(id),
            status,
            outputs,
        }
    }
}

#[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_stack_does_not_exist(e: &SdkError<DeleteStackError>) -> bool {
    match e {
        SdkError::ServiceError { err, .. } => {
            let msg = format!("{:?}", err);
            msg.contains("does not exist")
        }
        _ => false,
    }
}

#[inline]
fn is_error_describe_stacks_does_not_exist(e: &SdkError<DescribeStacksError>) -> bool {
    match e {
        SdkError::ServiceError { err, .. } => {
            let msg = format!("{:?}", err);
            msg.contains("does not exist")
        }
        _ => false,
    }
}