1use std::collections::HashMap;
2
3use pipedash_plugin_api::config::{
4 credential,
5 insecure,
6 selected_items,
7};
8use pipedash_plugin_api::logs::tagged::{
9 TaggedLogDialect,
10 TAGGED_MARKERS,
11};
12use pipedash_plugin_api::support::{
13 client_options,
14 join_buffered,
15};
16use pipedash_plugin_api::*;
17use tracing::{
18 debug,
19 info,
20 warn,
21};
22
23use crate::{
24 client,
25 config,
26 mapper,
27 metadata,
28 sign_in,
29 types,
30};
31
32mod actions;
33mod catalog;
34mod logs;
35
36const DEFAULT_PAGE_SIZE: usize = 1000;
37const RESOURCE_TREE_CONCURRENCY: usize = 8;
38
39plugin_struct!(
40 ArgocdPlugin,
41 client::ArgocdClient,
42 metadata::create_metadata();
43 server_url: Option<String> = None,
44 status_source: Option<StatusSource> = None,
45 organizations_filter: Option<Vec<String>> = None
46);
47
48impl ArgocdPlugin {
49 fn get_server_url(&self) -> PluginResult<&str> {
50 self.server_url
51 .as_deref()
52 .ok_or_else(|| PluginError::Internal("Server URL not set".to_string()))
53 }
54
55 async fn pipeline_with_live_state(
56 client: &client::ArgocdClient, app: &types::Application, server_url: &str,
57 ) -> Pipeline {
58 let mut pipeline = mapper::map_application_to_pipeline(app, server_url);
59 if mapper::needs_resource_tree(app) {
60 match client.resource_tree(&app.metadata.name).await {
61 Ok(tree) => mapper::degrade_from_tree(&mut pipeline, &tree),
62 Err(error) => warn!(
63 app = %app.metadata.name,
64 %error,
65 "Resource tree unavailable, keeping provider-reported state"
66 ),
67 }
68 }
69 pipeline
70 }
71}
72
73plugin_impl!(ArgocdPlugin [
74 metadata,
75 status_source,
76 fetch_available_pipelines,
77 fetch_organizations,
78 fetch_available_pipelines_filtered,
79 fetch_log_nodes,
80 read_log,
81 trigger_pipeline,
82 fetch_workflow_parameters,
83] {
84 fn configured_repositories(&self, _config: &HashMap<String, String>) -> Vec<String> {
85 Vec::new()
86 }
87
88 fn pipeline_actions(&self, pipeline: &PipelineFacts<'_>) -> PipelineActionState {
89 let mut state = pipedash_plugin_api::plugin::defaults::pipeline_actions(
90 &self.metadata().capabilities,
91 pipeline,
92 );
93 let text = |key: &str| {
94 pipeline
95 .metadata
96 .get(key)
97 .and_then(serde_json::Value::as_str)
98 .map(str::trim)
99 .unwrap_or_default()
100 };
101 let value = [text("destination_cluster"), text("destination_namespace")]
102 .into_iter()
103 .filter(|part| !part.is_empty())
104 .collect::<Vec<_>>()
105 .join(" / ");
106 state.target = (!value.is_empty()).then(|| DisplayField {
107 label: "Destination".to_string(),
108 value,
109 });
110 state
111 }
112
113 fn client_options(&self, config: &HashMap<String, String>) -> ClientOptions {
114 client_options(
115 config::get_server_url(config).ok().as_deref(),
116 insecure(config),
117 )
118 }
119
120 fn initialize(
121 &mut self, _provider_id: i64, config: HashMap<String, String>,
122 http_client: Option<std::sync::Arc<reqwest::Client>>,
123 ) -> PluginResult<()> {
124 info!("Initializing ArgoCD plugin");
125 debug!(config_keys = ?config.keys().collect::<Vec<_>>());
126
127 let server_url = config::get_server_url(&config)?;
128 debug!(server_url, "Configured server URL");
129
130 let token = credential(&config, "token")?;
131 debug!(token_length = token.len(), "Retrieved authentication token");
132
133 let insecure = insecure(&config);
134 if insecure {
135 warn!("Insecure TLS mode enabled - certificate verification disabled");
136 }
137
138 let organizations_filter = config::parse_organizations_filter(&config);
139 debug!(?organizations_filter, "Organizations filter configured");
140
141 let status_source = custom_status_source(&config)?;
142
143 let http_client = require_client(http_client)?;
144 let client = client::ArgocdClient::new(http_client, &server_url, &token);
145 debug!("ArgoCD client created successfully");
146
147 self.client = Some(client);
148 self.server_url = Some(server_url);
149 self.status_source = status_source;
150 self.organizations_filter = organizations_filter;
151 self.config = config;
152
153 info!("ArgoCD plugin initialization complete");
154 Ok(())
155 }
156
157 async fn validate_credentials(&self) -> PluginResult<bool> {
158 debug!("Validating ArgoCD credentials");
159 let client = self.client()?;
160 match client.list_applications(None).await {
161 Ok(apps) => {
162 info!(app_count = apps.len(), "Credentials validated successfully");
163 Ok(true)
164 }
165 Err(e) => {
166 warn!(error = ?e, "Credential validation failed");
167 Err(e)
168 }
169 }
170 }
171
172 async fn fetch_pipelines(&self) -> PluginResult<Vec<Pipeline>> {
173 debug!("Fetching configured pipelines");
174 let client = self.client()?;
175 let server_url = self.get_server_url()?;
176 debug!(server_url, "Using configured server URL");
177
178 let mut apps = client.list_applications(None).await?;
179 debug!(total_apps = apps.len(), "Retrieved all applications");
180
181 if let Some(orgs_filter) = &self.organizations_filter {
182 debug!(?orgs_filter, "Applying organization filter");
183 apps.retain(|app| {
184 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
185 orgs_filter.contains(&git_org)
186 });
187 debug!(
188 filtered_apps = apps.len(),
189 "Applications after organization filter"
190 );
191 }
192
193 let filtered_apps = if let Some(selected_items) = selected_items(&self.config)
194 {
195 debug!(
196 selected_count = selected_items.len(),
197 "Applying user selection filter"
198 );
199 apps.into_iter()
200 .filter(|app| selected_items.contains(&app.metadata.name))
201 .collect()
202 } else {
203 debug!("No user selection - returning all applications");
204 apps
205 };
206
207 debug!(
208 final_apps = filtered_apps.len(),
209 "Applications after all filters"
210 );
211
212 let live_states: Vec<_> = filtered_apps
213 .iter()
214 .map(|app| Self::pipeline_with_live_state(client, app, server_url))
215 .collect();
216 let pipelines: Vec<Pipeline> = join_buffered(live_states, RESOURCE_TREE_CONCURRENCY).await;
217
218 debug!(
219 pipeline_count = pipelines.len(),
220 "Mapped applications to pipelines"
221 );
222 Ok(pipelines)
223 }
224
225 async fn fetch_run_history(
226 &self, pipeline_id: &str, limit: usize,
227 ) -> PluginResult<Vec<PipelineRun>> {
228 let (_namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
229 let client = self.client()?;
230 let server_url = self.get_server_url()?;
231
232 let app = client.get_application(&app_name).await?;
233
234 Ok(mapper::runs::map_runs(&app, server_url, limit))
235 }
236
237 async fn fetch_run_details(
238 &self, pipeline_id: &str, run_number: i64,
239 ) -> PluginResult<PipelineRun> {
240 let (_namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
241 let client = self.client()?;
242 let server_url = self.get_server_url()?;
243
244 let app = client.get_application(&app_name).await?;
245
246 if let Some(operation) = mapper::runs::map_operation_to_run(&app, server_url) {
247 if operation.run_number == run_number {
248 return Ok(operation);
249 }
250 }
251
252 let history = app.status.history.as_deref().unwrap_or(&[]);
253 let history_item = history
254 .iter()
255 .find(|h| h.deployed_at.timestamp() == run_number)
256 .ok_or_else(|| {
257 PluginError::PipelineNotFound(format!("Run {} not found", run_number))
258 })?;
259
260 Ok(mapper::runs::map_history_to_run(
261 history_item,
262 &app,
263 server_url,
264 ))
265 }
266
267 fn log_dialect(&self) -> &'static dyn LogDialect {
268 &TaggedLogDialect {
269 tags: TAGGED_MARKERS,
270 infer_errors: false,
271 }
272 }
273
274 async fn cancel_run(&self, pipeline_id: &str, _run_number: i64) -> PluginResult<()> {
275 let (_namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
276 let client = self.client()?;
277
278 client.terminate_operation(&app_name).await?;
279
280 Ok(())
281 }
282
283 async fn sign_in_client(
284 &self, config: &HashMap<String, String>, http_client: &reqwest::Client,
285 ) -> PluginResult<SignInClient> {
286 let server_url = config::get_server_url(config)?;
287 let settings = client::ArgocdClient::fetch_settings(http_client, &server_url).await?;
288 sign_in::client_for(&settings, &server_url)
289 }
290
291 fn sign_in_refresh_rejections(&self) -> &'static [SignInRefreshRejection] {
292 sign_in::REFRESH_REJECTIONS
293 }
294});
295
296#[cfg(test)]
297mod tests;