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
use crate::{
    build_request,
    error::{surf_to_tool_error, ToolError},
    settings::Core,
    workspace, BASE_URL,
};
use async_std::{
    sync::{Arc, Mutex, RwLock},
    task::{self, JoinHandle},
};
use log::{error, info};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
    fmt::{Display, Formatter},
    thread,
    time::Duration,
};
use surf::{http::Method, Client};
use url::Url;

// Statuses in Terraform Cloud that indicate a run is in a completed state
pub const COMPLETED_STATUSES: [Status; 2] =
    [Status::Applied, Status::PlannedAndFinished];

pub const NO_APPLY_END_STATUSES: [Status; 2] =
    [Status::Planned, Status::CostEstimated];

// Statuses in Terraform Cloud that indicate a run is in an error state
pub const ERROR_STATUSES: [Status; 8] = [
    Status::Canceled,
    Status::ForceCanceled,
    Status::Errored,
    Status::Discarded,
    Status::Failed,
    Status::Unreachable,
    Status::Unknown,
    Status::PolicySoftFailed,
];

// Statuses in Terraform Cloud
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Status {
    ApplyQueued,
    Pending,
    PlanQueued,
    Queuing,
    Queued,
    Fetching,
    CostEstimating,
    CostEstimated,
    FetchingCompleted,
    PrePlanRunning,
    PrePlanCompleted,
    ManagedQueued,
    Running,
    Passed,
    Failed,
    Applying,
    Planning,
    Planned,
    Applied,
    Canceled,
    Errored,
    Discarded,
    PlannedAndFinished,
    PlannedAndSaved,
    PolicyChecking,
    PolicyOverride,
    PolicySoftFailed,
    Unreachable,
    ForceCanceled,
    #[default]
    Unknown,
    Finished,
}

impl Display for Status {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Status::ApplyQueued => write!(f, "apply_queued"),
            Status::Pending => write!(f, "pending"),
            Status::PlanQueued => write!(f, "plan_queued"),
            Status::Queuing => write!(f, "queuing"),
            Status::Queued => write!(f, "queued"),
            Status::Fetching => write!(f, "fetching"),
            Status::CostEstimating => write!(f, "cost_estimating"),
            Status::CostEstimated => write!(f, "cost_estimated"),
            Status::FetchingCompleted => write!(f, "fetching_completed"),
            Status::PrePlanRunning => write!(f, "pre_plan_running"),
            Status::PrePlanCompleted => write!(f, "pre_plan_completed"),
            Status::ManagedQueued => write!(f, "managed_queued"),
            Status::Running => write!(f, "running"),
            Status::Passed => write!(f, "passed"),
            Status::Failed => write!(f, "failed"),
            Status::Applying => write!(f, "applying"),
            Status::Planning => write!(f, "planning"),
            Status::Planned => write!(f, "planned"),
            Status::Applied => write!(f, "applied"),
            Status::Canceled => write!(f, "canceled"),
            Status::Errored => write!(f, "errored"),
            Status::Discarded => write!(f, "discarded"),
            Status::PlannedAndFinished => write!(f, "planned_and_finished"),
            Status::PlannedAndSaved => write!(f, "planned_and_saved"),
            Status::PolicyChecking => write!(f, "policy_checking"),
            Status::PolicyOverride => write!(f, "policy_override"),
            Status::PolicySoftFailed => write!(f, "policy_soft_failed"),
            Status::Unreachable => write!(f, "unreachable"),
            Status::ForceCanceled => write!(f, "force_canceled"),
            Status::Unknown => write!(f, "unknown"),
            Status::Finished => write!(f, "finished"),
        }
    }
}

impl From<String> for Status {
    fn from(item: String) -> Self {
        match item.as_str() {
            "apply_queued" => Status::ApplyQueued,
            "pending" => Status::Pending,
            "plan_queued" => Status::PlanQueued,
            "queuing" => Status::Queuing,
            "queued" => Status::Queued,
            "fetching" => Status::Fetching,
            "cost_estimating" => Status::CostEstimating,
            "cost_estimated" => Status::CostEstimated,
            "fetching_completed" => Status::FetchingCompleted,
            "pre_plan_running" => Status::PrePlanRunning,
            "pre_plan_completed" => Status::PrePlanCompleted,
            "managed_queued" => Status::ManagedQueued,
            "running" => Status::Running,
            "passed" => Status::Passed,
            "failed" => Status::Failed,
            "applying" => Status::Applying,
            "planning" => Status::Planning,
            "planned" => Status::Planned,
            "applied" => Status::Applied,
            "canceled" => Status::Canceled,
            "errored" => Status::Errored,
            "discarded" => Status::Discarded,
            "planned_and_finished" => Status::PlannedAndFinished,
            "planned_and_saved" => Status::PlannedAndSaved,
            "policy_checking" => Status::PolicyChecking,
            "policy_override" => Status::PolicyOverride,
            "policy_soft_failed" => Status::PolicySoftFailed,
            "unreachable" => Status::Unreachable,
            "force_canceled" => Status::ForceCanceled,
            "unknown" => Status::Unknown,
            "finished" => Status::Finished,
            _ => Status::Unknown,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Attributes {
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub terraform_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_only: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub save_plan: Option<bool>,
    pub target_addrs: Vec<String>,
    pub replace_addrs: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refresh: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refresh_only: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_apply: Option<bool>,
    pub allow_empty_apply: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_destroy: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<Status>,
}

impl Default for Attributes {
    fn default() -> Self {
        Self {
            message: "Run created by tfc-toolset".to_string(),
            terraform_version: None,
            plan_only: None,
            save_plan: None,
            target_addrs: Vec::new(),
            replace_addrs: Vec::new(),
            refresh: None,
            refresh_only: None,
            auto_apply: None,
            allow_empty_apply: false,
            is_destroy: None,
            created_at: None,
            status: None,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkspaceOuter {
    pub data: Workspace,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Workspace {
    #[serde(rename = "type")]
    pub relationship_type: String,
    pub id: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Relationships {
    pub workspace: WorkspaceOuter,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Run {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub attributes: Attributes,
    #[serde(rename = "type")]
    pub request_type: String,
    pub relationships: Relationships,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Links>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct RunOuter {
    pub data: Run,
}

impl RunOuter {
    fn new(workspace_id: &str, attributes: Option<Attributes>) -> Self {
        Self {
            data: Run {
                id: None,
                attributes: attributes.unwrap_or_default(),
                request_type: "runs".to_string(),
                relationships: Relationships {
                    workspace: WorkspaceOuter {
                        data: Workspace {
                            relationship_type: "workspaces".to_string(),
                            id: workspace_id.to_string(),
                        },
                    },
                },
                links: None,
            },
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Links {
    #[serde(rename = "self")]
    pub self_link: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct QueueOptions {
    pub max_concurrent: usize,
    pub max_iterations: usize,
    pub status_check_sleep_seconds: u64,
    pub cancel_on_timeout: bool,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct QueueResult {
    pub results: Vec<RunResult>,
    pub errors: Vec<RunResult>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RunResult {
    pub id: RunId,
    pub status: String,
    pub workspace_id: String,
}

pub type RunId = String;

pub async fn create(
    workspace_id: &str,
    attributes: Option<Attributes>,
    config: &Core,
    client: Client,
) -> Result<Run, ToolError> {
    info!("Creating run for workspace: {}", workspace_id);
    let url = Url::parse(&format!("{}/runs", BASE_URL))?;
    let req = build_request(
        Method::Post,
        url,
        config,
        Some(json!(RunOuter::new(workspace_id, attributes))),
    );
    match client.send(req).await {
        Ok(mut r) => {
            if r.status().is_success() {
                info!("Successfully created run!");
                let res = r.body_string().await.map_err(surf_to_tool_error)?;
                let run: RunOuter = serde_json::from_str(&res)?;
                Ok(run.data)
            } else {
                let error =
                    r.body_string().await.map_err(surf_to_tool_error)?;
                error!("Failed to create run: {}", error);
                Err(ToolError::General(anyhow::anyhow!(error)))
            }
        }
        Err(e) => Err(surf_to_tool_error(e)),
    }
}

pub async fn status(
    run_id: &str,
    config: &Core,
    client: Client,
) -> Result<Run, ToolError> {
    info!("Getting status for run: {}", run_id);
    let url = Url::parse(&format!("{}/runs/{}", BASE_URL, run_id))?;
    let req = build_request(Method::Get, url, config, None);
    match client.send(req).await {
        Ok(mut r) => {
            if r.status().is_success() {
                info!("Successfully retrieved run status!");
                let res = r.body_string().await.map_err(surf_to_tool_error)?;
                let run: RunOuter = serde_json::from_str(&res)?;
                Ok(run.data)
            } else {
                error!("Failed to retrieve run status :(");
                let error =
                    r.body_string().await.map_err(surf_to_tool_error)?;
                Err(ToolError::General(anyhow::anyhow!(error)))
            }
        }
        Err(e) => Err(surf_to_tool_error(e)),
    }
}

pub async fn cancel(
    run_id: &str,
    config: &Core,
    client: Client,
) -> Result<(), ToolError> {
    info!("Cancelling run: {}", run_id);
    let url =
        Url::parse(&format!("{}/runs/{}/actions/cancel", BASE_URL, run_id))?;
    let req = build_request(Method::Post, url, config, None);
    match client.send(req).await {
        Ok(mut r) => {
            if r.status().is_success() {
                info!("Successfully cancelled run!");
                Ok(())
            } else {
                error!("Failed to cancel run :(");
                let error =
                    r.body_string().await.map_err(surf_to_tool_error)?;
                Err(ToolError::General(anyhow::anyhow!(error)))
            }
        }
        Err(e) => Err(surf_to_tool_error(e)),
    }
}

pub async fn discard(
    run_id: &str,
    config: &Core,
    client: Client,
) -> Result<(), ToolError> {
    info!("Discarding run: {}", run_id);
    let url =
        Url::parse(&format!("{}/runs/{}/actions/discard", BASE_URL, run_id))?;
    let req = build_request(Method::Post, url, config, None);
    match client.send(req).await {
        Ok(mut r) => {
            if r.status().is_success() {
                info!("Successfully discarded run!");
                Ok(())
            } else {
                error!("Failed to discard run :(");
                let error =
                    r.body_string().await.map_err(surf_to_tool_error)?;
                Err(ToolError::General(anyhow::anyhow!(error)))
            }
        }
        Err(e) => Err(surf_to_tool_error(e)),
    }
}

fn run_has_ended(
    status: &Status,
    will_auto_apply: bool,
    will_save_plan: bool,
) -> bool {
    COMPLETED_STATUSES.contains(status)
        || ERROR_STATUSES.contains(status)
        || !will_auto_apply && NO_APPLY_END_STATUSES.contains(status)
        || will_save_plan && status == &Status::PlannedAndSaved
}

fn build_handle(
    id: String,
    options: QueueOptions,
    attributes: Attributes,
    core: Core,
    client: Client,
) -> JoinHandle<Result<RunResult, ToolError>> {
    task::spawn(async move {
        let will_auto_apply = attributes.auto_apply.unwrap_or(false);
        let will_save_plan = attributes.save_plan.unwrap_or(false);
        let mut iterations = 0;
        let mut run =
            create(&id.clone(), Some(attributes), &core, client.clone())
                .await?;
        let run_id = run.id.clone().unwrap();
        info!("Run {} created for workspace {}", &run_id, &id.clone());
        while !run_has_ended(
            &run.attributes.status.clone().unwrap_or(Status::Unknown),
            will_auto_apply,
            will_save_plan,
        ) {
            run = status(&run_id, &core, client.clone()).await?;
            let status =
                run.attributes.status.clone().unwrap_or(Status::Unknown);
            info!("Run {} status: {}", &run_id, &status);
            if run_has_ended(&status, will_auto_apply, will_save_plan) {
                break;
            }
            iterations += 1;
            if iterations >= options.max_iterations {
                error!(
                    "Run {} for workspace {} has been in status {} too long.",
                    &run_id,
                    &id.clone(),
                    &status.clone()
                );
                if status == Status::Pending {
                    error!(
                        "There is likely previous run pending. Please check the workspace in the UI."
                    );
                } else {
                    error!(
                        "This is likely some error. Please check the run in the UI."
                    );
                }
                if options.cancel_on_timeout
                    && (status == Status::Pending || status == Status::Applying)
                {
                    cancel(&run_id, &core, client.clone()).await?;
                }
                break;
            }
            async_std::task::sleep(Duration::from_secs(
                options.status_check_sleep_seconds,
            ))
            .await;
        }
        Ok(RunResult {
            id: run_id,
            status: run
                .attributes
                .status
                .unwrap_or(Status::Unknown)
                .to_string(),
            workspace_id: id,
        })
    })
}

pub async fn work_queue(
    workspaces: Vec<workspace::Workspace>,
    options: QueueOptions,
    attributes: Attributes,
    client: Client,
    core: &Core,
) -> Result<QueueResult, ToolError> {
    let queue: Arc<Mutex<Vec<workspace::Workspace>>> =
        Arc::new(Mutex::new(Vec::with_capacity(workspaces.len())));
    let results: Arc<Mutex<Vec<RunResult>>> =
        Arc::new(Mutex::new(Vec::with_capacity(workspaces.len())));
    let errors: Arc<Mutex<Vec<RunResult>>> = Arc::new(Mutex::new(Vec::new()));

    let max_concurrent = options.max_concurrent;

    let opts = Arc::new(RwLock::new(options));
    let attrs = Arc::new(RwLock::new(attributes));
    let c = Arc::new(RwLock::new(core.clone()));
    let cl = Arc::new(RwLock::new(client));

    for ws in workspaces {
        queue.lock().await.push(ws);
    }

    let mut handles = vec![];

    for _ in 0..max_concurrent {
        let queue_clone = Arc::clone(&queue);
        let results_clone = Arc::clone(&results);
        let errors_clone = Arc::clone(&errors);
        let opts_clone = Arc::clone(&opts);
        let attrs_clone = Arc::clone(&attrs);
        let core_clone = Arc::clone(&c);
        let client_clone = Arc::clone(&cl);

        let handle = thread::spawn(move || {
            task::block_on(async {
                loop {
                    let work = {
                        let mut queue = queue_clone.lock().await;
                        if queue.is_empty() {
                            None
                        } else {
                            Some(queue.pop().unwrap())
                        }
                    };

                    if let Some(work) = work {
                        let run_result = build_handle(
                            work.id.clone(),
                            opts_clone.read().await.clone(),
                            attrs_clone.read().await.clone(),
                            core_clone.read().await.clone(),
                            client_clone.read().await.clone(),
                        )
                        .await;
                        match run_result {
                            Ok(result) => {
                                results_clone.lock().await.push(result);
                            }
                            Err(e) => {
                                errors_clone.lock().await.push(RunResult {
                                    id: "unknown".to_string(),
                                    status: e.to_string(),
                                    workspace_id: work.id.clone(),
                                });
                                error!(
                                    "Error processing workspace {}: {}",
                                    work.id, e
                                );
                            }
                        }
                    } else {
                        info!("No more work to do, thread exiting.");
                        break;
                    }
                }
            });
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    let return_results = results.lock().await.clone();
    let return_errors = errors.lock().await.clone();

    Ok(QueueResult { results: return_results, errors: return_errors })
}