1use crate::awsutils::{config, datetime_str, GlobalOpt};
2use crate::utils::{get_values, print_table, split, Tag};
3use aws_sdk_autoscaling::model::Instance;
4use aws_sdk_autoscaling::Client;
5use itertools::Itertools;
6use structopt::StructOpt;
7
8#[derive(Debug, StructOpt)]
9pub enum AutoScalingGroupOpt {
10 #[structopt(about = "display basic info")]
11 Info(SearchInfoQueryOpt),
12 #[structopt(visible_alias = "act", about = "display activities")]
13 Activities(SearchQueryOpt),
14 #[structopt(visible_alias = "inst", about = "display instances")]
15 Instances(SearchQueryOpt),
16}
17#[derive(Debug, StructOpt)]
18pub struct SearchQueryOpt {
19 #[structopt(
20 short = "q",
21 long,
22 help = "ambiguous search with asterisk on target group name or ALB arn. if set comma, search OR"
23 )]
24 query: Option<String>,
25}
26
27#[derive(Debug, StructOpt)]
28pub struct SearchInfoQueryOpt {
29 #[structopt(
30 short = "q",
31 long,
32 help = "ambiguous search with asterisk on target group name or ALB arn. if set comma, search OR"
33 )]
34 query: Option<String>,
35 #[structopt(
36 short = "T",
37 long,
38 help = "Accepts a comma separated list of tags that are going to be presented as columns.
39 Tags are case-sensitive."
40 )]
41 tag_columns: Option<String>,
42 #[structopt(long = "show-all-tags", help = "Show all tags.")]
43 show_all_tags: bool,
44}
45
46pub async fn matcher(global_opt: GlobalOpt, opt: AutoScalingGroupOpt) {
47 let cli = Client::new(&config(global_opt).await);
48 match opt {
49 AutoScalingGroupOpt::Info(opt) => info(&cli, opt).await,
50 AutoScalingGroupOpt::Activities(opt) => activities(&cli, opt).await,
51 AutoScalingGroupOpt::Instances(opt) => instances(&cli, opt).await,
52 }
53}
54async fn info(cli: &Client, opt: SearchInfoQueryOpt) {
55 let asg = get_autoscaling_groups(cli, &SearchQueryOpt { query: opt.query }).await;
56 let len = asg.len();
57
58 let tag_column: Vec<String> = if opt.show_all_tags {
59 asg.iter()
60 .flat_map(|t| t.tags.iter().map(|ot| ot.key.to_string()))
61 .unique()
62 .collect()
63 } else {
64 opt.tag_columns
65 .map(|t| split(&*t, true))
66 .unwrap_or_default()
67 };
68
69 let rows: Vec<Vec<String>> = asg
70 .into_iter()
71 .map(|t| {
72 let r = get_values(&t.tags, &tag_column);
73 vec![
74 t.name,
75 t.instances.len().to_string(),
76 t.desired_capacity
77 .map(|i| i.to_string())
78 .unwrap_or_default(),
79 t.min_capacity.map(|i| i.to_string()).unwrap_or_default(),
80 t.max_capacity.map(|i| i.to_string()).unwrap_or_default(),
81 ]
82 .into_iter()
83 .chain(r)
84 .collect()
85 })
86 .collect();
87 let header: Vec<String> = vec![
88 "Name".to_string(),
89 "Instances".to_string(),
90 "Desired".to_string(),
91 "Min".to_string(),
92 "Max".to_string(),
93 ]
94 .into_iter()
95 .chain(tag_column)
96 .collect();
97 print_table(header, rows);
98 println!("counts: {}", len);
99}
100async fn activities(cli: &Client, opt: SearchQueryOpt) {
101 let asg = get_autoscaling_groups(cli, &opt).await;
102 if asg.len() != 1 {
103 println!("need to be narrowed to 1");
104 return;
105 }
106 let a = get_activities(cli, asg.first().unwrap().name.clone()).await;
107 let len = a.len();
108 let rows: Vec<Vec<String>> = a
109 .into_iter()
110 .map(|t| vec![t.status, t.description, t.start_at, t.end_at])
111 .collect();
112 print_table(
113 vec![
114 "Status".to_string(),
115 "Desc".to_string(),
116 "StartTime".to_string(),
117 "EndTime".to_string(),
118 ],
119 rows,
120 );
121 println!("counts: {}", len);
122}
123
124async fn instances(cli: &Client, opt: SearchQueryOpt) {
125 let asg = get_autoscaling_groups(cli, &opt).await;
126 let rows: Vec<Vec<String>> = asg
127 .into_iter()
128 .flat_map(|a| {
129 let name = a.name;
130 a.instances
131 .into_iter()
132 .map(|i| {
133 vec![
134 name.clone(),
135 i.instance_id.unwrap_or_default(),
136 i.lifecycle_state
137 .map(|s| s.as_str().to_string())
138 .unwrap_or_default(),
139 i.instance_type.unwrap_or_default(),
140 i.availability_zone.unwrap_or_default(),
141 i.health_status.unwrap_or_default(),
142 ]
143 })
144 .collect::<Vec<_>>()
145 })
146 .collect();
147 print_table(
148 vec![
149 "ASG Name".to_string(),
150 "ID".to_string(),
151 "LifeCycle".to_string(),
152 "InstanceType".to_string(),
153 "AZ".to_string(),
154 "Status".to_string(),
155 ],
156 rows,
157 )
158}
159
160struct AutoScalingGroup {
161 name: String,
162 instances: Vec<Instance>,
163 min_capacity: Option<i32>,
164 max_capacity: Option<i32>,
165 desired_capacity: Option<i32>,
166 tags: Vec<Tag>,
167}
168
169async fn get_autoscaling_groups(cli: &Client, opt: &SearchQueryOpt) -> Vec<AutoScalingGroup> {
170 let mut m: Option<String> = None;
171 let mut vector: Vec<AutoScalingGroup> = vec![];
172 loop {
173 let (mut v, mark) = autoscaling_groups(cli, &m).await;
174 m = mark;
175 vector.append(&mut v);
176 if m.is_none() {
177 break;
178 }
179 }
180 vector
181 .into_iter()
182 .filter(|t| search_name(&opt.query, &t.name, &t.tags))
183 .collect()
184}
185
186async fn autoscaling_groups(
187 client: &Client,
188 marker: &Option<String>,
189) -> (Vec<AutoScalingGroup>, Option<String>) {
190 let resp = client
191 .describe_auto_scaling_groups()
192 .set_next_token(marker.clone())
193 .send();
194 match resp.await {
195 Ok(res) => {
196 let groups = res.auto_scaling_groups.unwrap_or_default();
197 (
198 groups
199 .into_iter()
200 .map(|t| AutoScalingGroup {
201 name: t.auto_scaling_group_name.unwrap_or_default(),
202 instances: t.instances.unwrap_or_default(),
203 min_capacity: t.min_size,
204 max_capacity: t.max_size,
205 desired_capacity: t.desired_capacity,
206 tags: t
207 .tags
208 .map(|ot| {
209 ot.into_iter()
210 .map(|t| Tag {
211 key: t.key.unwrap_or_default(),
212 value: t.value,
213 })
214 .collect()
215 })
216 .unwrap_or_default(),
217 })
218 .collect(),
219 res.next_token,
220 )
221 }
222 Err(err) => panic!("{}", err.to_string()),
223 }
224}
225
226fn search_name(query: &Option<String>, name: &str, tags: &[Tag]) -> bool {
227 if query.is_none() || name.is_empty() {
228 return true;
229 }
230 let tg: String = name.to_string();
231 let qu: String = query.as_ref().unwrap().clone();
232 for q in qu.split(',') {
233 if tg.contains(q) {
234 return true;
235 }
236 if tags
237 .iter()
238 .any(|t| t.key.contains(q) || t.value.as_ref().filter(|v| v.contains(q)).is_some())
239 {
240 return true;
241 }
242 }
243
244 false
245}
246#[test]
247fn test_search_name() {
248 assert_eq!(
249 search_name(&Some("api".to_string()), &"aa".to_string(), &vec![]),
250 false
251 );
252
253 assert_eq!(
254 search_name(
255 &Some("api,test".to_string()),
256 &"test-api".to_string(),
257 &vec![]
258 ),
259 true
260 );
261 assert_eq!(
262 search_name(&Some("api".to_string()), &"ap".to_string(), &vec![]),
263 false
264 );
265 assert_eq!(
266 search_name(
267 &Some("test".to_string()),
268 &"ap".to_string(),
269 &vec![Tag {
270 key: "test".to_string(),
271 value: None
272 }]
273 ),
274 true
275 );
276 assert_eq!(
277 search_name(
278 &Some("test".to_string()),
279 &"ap".to_string(),
280 &vec![Tag {
281 key: "tag".to_string(),
282 value: Some("test".to_string())
283 }]
284 ),
285 true
286 );
287}
288
289struct Activity {
290 status: String,
291 description: String,
292 start_at: String,
293 end_at: String,
294}
295async fn get_activities(cli: &Client, asg_name: String) -> Vec<Activity> {
296 match cli
297 .describe_scaling_activities()
298 .auto_scaling_group_name(asg_name)
299 .send()
300 .await
301 {
302 Ok(res) => res
303 .activities
304 .unwrap_or_default()
305 .into_iter()
306 .map(|a| Activity {
307 status: a
308 .status_code
309 .map(|c| c.as_str().to_string())
310 .unwrap_or_default(),
311 description: a.description.unwrap_or_default(),
312 start_at: a.start_time.map(datetime_str).unwrap_or_default(),
313 end_at: a.end_time.map(datetime_str).unwrap_or_default(),
314 })
315 .collect(),
316 Err(err) => panic!("{}", err.to_string()),
317 }
318}