pipedash-plugin-jenkins 0.7.0

Jenkins plugin for Pipedash
Documentation
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
use std::collections::HashMap;
use std::time::Duration;

use chrono::Utc;
use pipedash_plugin_api::{
    check_response,
    map_send_error,
    AvailablePipeline,
    LogCursor,
    LogRead,
    LogSink,
    Pipeline,
    PluginError,
    PluginResult,
    RetryPolicy,
};
use reqwest::{
    Client,
    Url,
};
use serde::de::DeserializeOwned;

use crate::{
    config,
    mapper,
    types,
};

fn parse_url(url: &str) -> PluginResult<Url> {
    Url::parse(url).map_err(|e| PluginError::InvalidConfig(format!("Invalid Jenkins URL: {e}")))
}

pub(crate) struct JenkinsClient {
    http_client: std::sync::Arc<Client>,
    server_url: String,
    auth_header: String,
    pub(crate) retry_policy: RetryPolicy,
}

impl JenkinsClient {
    pub fn new(
        http_client: std::sync::Arc<Client>, server_url: String, auth_header: String,
    ) -> Self {
        Self {
            http_client,
            server_url,
            auth_header,
            retry_policy: RetryPolicy::default(),
        }
    }

    pub fn server_url(&self) -> &str {
        &self.server_url
    }

    async fn get_json<T: DeserializeOwned>(
        &self, url: &str, timeout: Option<Duration>,
    ) -> PluginResult<T> {
        let url = parse_url(url)?;

        self.retry_policy
            .retry(|| async {
                let mut request = self
                    .http_client
                    .get(url.clone())
                    .header(reqwest::header::AUTHORIZATION, &self.auth_header);
                if let Some(timeout) = timeout {
                    request = request.timeout(timeout);
                }
                let response = request.send().await.map_err(|e| map_send_error(e, &url))?;

                check_response(response)
                    .await?
                    .json()
                    .await
                    .map_err(|e| map_send_error(e, &url))
            })
            .await
    }

    pub async fn discover_all_jobs(&self) -> PluginResult<Vec<types::DiscoveredJob>> {
        let mut all_jobs = Vec::new();
        let mut queue = vec![String::new()];

        while let Some(path) = queue.pop() {
            let jobs = self.fetch_jobs_in_folder(&path).await?;

            for job in jobs {
                let full_path = if path.is_empty() {
                    job.name.clone()
                } else {
                    format!("{}/{}", path, job.name)
                };

                if job._class.contains("Folder")
                    || job._class.contains("WorkflowMultiBranchProject")
                {
                    queue.push(full_path);
                } else if job._class.contains("WorkflowJob")
                    || job._class.contains("FreeStyleProject")
                {
                    all_jobs.push(types::DiscoveredJob {
                        name: job.name,
                        full_path,
                        _class: job._class,
                    });
                }
            }
        }

        Ok(all_jobs)
    }

    async fn fetch_jobs_in_folder(&self, folder_path: &str) -> PluginResult<Vec<types::JobItem>> {
        let url = if folder_path.is_empty() {
            format!("{}/api/json?tree=jobs[name,url,_class]", self.server_url)
        } else {
            let encoded_path = config::encode_job_name(folder_path);
            format!(
                "{}/job/{}/api/json?tree=jobs[name,url,_class]",
                self.server_url, encoded_path
            )
        };

        let response: types::JobsResponse = self.get_json(&url, None).await?;

        Ok(response.jobs)
    }

    pub async fn fetch_job_details(&self, job_path: &str) -> PluginResult<types::Job> {
        let encoded_path = config::encode_job_name(job_path);
        let url = format!(
            "{}/job/{}/api/json?tree=name,lastBuild[number]",
            self.server_url, encoded_path
        );

        self.get_json(&url, Some(Duration::from_secs(10))).await
    }

    pub async fn fetch_build_details(
        &self, job_path: &str, build_number: i64,
    ) -> PluginResult<types::Build> {
        let encoded_path = config::encode_job_name(job_path);
        let url = format!(
            "{}/job/{}/{}/api/json?tree=number,result,building,timestamp,duration,url,fullDisplayName,actions[_class,causes[userName,shortDescription],lastBuiltRevision[SHA1,branch[SHA1,name]],parameters[name,value]]",
            self.server_url, encoded_path, build_number
        );

        tracing::debug!(job_path = %job_path, build_number = build_number, "Fetching Jenkins build details");

        let build: types::Build = self.get_json(&url, Some(Duration::from_secs(10))).await?;

        tracing::debug!(action_count = build.actions.len(), "Parsed Jenkins build");

        Ok(build)
    }

    pub async fn fetch_build_history(
        &self, job_path: &str, limit: usize,
    ) -> PluginResult<Vec<types::Build>> {
        let encoded_path = config::encode_job_name(job_path);
        let url = format!(
            "{}/job/{}/api/json?tree=builds[number,url,result,building,timestamp,duration,actions[_class,causes[userName,shortDescription],lastBuiltRevision[SHA1,branch[SHA1,name]],parameters[name,value]]]{{0,{limit}}}",
            self.server_url, encoded_path
        );

        let response: types::JobBuildsResponse = self.get_json(&url, None).await?;

        Ok(response.builds)
    }

    pub async fn fetch_job_parameters(
        &self, job_path: &str,
    ) -> PluginResult<types::JobWithParameters> {
        let encoded_path = config::encode_job_name(job_path);
        let url = format!(
            "{}/job/{}/api/json?tree=property[parameterDefinitions[name,description,type,defaultParameterValue[value],choices],_class]",
            self.server_url, encoded_path
        );

        tracing::debug!(job_path = %job_path, "Fetching Jenkins job parameters");

        self.get_json(&url, Some(Duration::from_secs(30))).await
    }

    pub async fn stream_console_log(
        &self, job_path: &str, build_number: i64, from: Option<&LogCursor>, sink: &mut LogSink,
    ) -> PluginResult<LogRead> {
        let resume = match from {
            None => None,
            Some(cursor) => {
                let known = cursor
                    .parse::<types::ConsoleCursor>()
                    .filter(|cursor| cursor.build == build_number);
                if known.is_none() {
                    sink.restart()?;
                }
                known.map(|cursor| cursor.offset)
            }
        };
        let encoded_path = config::encode_job_name(job_path);
        let url = parse_url(&format!(
            "{}/job/{}/{}/logText/progressiveText?start={}",
            self.server_url,
            encoded_path,
            build_number,
            resume.unwrap_or(0)
        ))?;

        let response = self
            .retry_policy
            .retry_unsent(&url, || {
                self.http_client
                    .get(url.clone())
                    .header(reqwest::header::AUTHORIZATION, &self.auth_header)
                    .timeout(Duration::from_secs(900))
                    .send()
            })
            .await?;

        if matches!(response.status().as_u16(), 404 | 410) {
            return Err(PluginError::PipelineNotFound(format!(
                "Console log of build #{build_number} is no longer available"
            )));
        }

        let response = check_response(response).await?;
        let size = response
            .headers()
            .get("X-Text-Size")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.trim().parse::<u64>().ok());
        match (resume, size) {
            (Some(_), None) => {
                return Err(PluginError::ApiError(
                    "Jenkins did not report the console text size".into(),
                ))
            }
            (Some(start), Some(size)) if size < start => sink.restart()?,
            _ => {}
        }

        sink.pipe(response).await?;

        let cursor = size
            .map(|offset| {
                LogCursor::new(&types::ConsoleCursor {
                    build: build_number,
                    offset,
                })
            })
            .transpose()?;
        Ok(match cursor {
            Some(cursor) if resume.is_some() && !sink.restarted() => LogRead::append(cursor),
            cursor => LogRead::replace(cursor),
        })
    }

    pub async fn trigger_build(
        &self, job_path: &str, form_data: Vec<(String, String)>,
    ) -> PluginResult<()> {
        let encoded_path = config::encode_job_name(job_path);
        let endpoint = if form_data.is_empty() {
            "build"
        } else {
            "buildWithParameters"
        };
        let url = parse_url(&format!(
            "{}/job/{}/{endpoint}",
            self.server_url, encoded_path
        ))?;
        let parameter_names = form_data
            .iter()
            .map(|(name, _)| name.as_str())
            .collect::<Vec<_>>()
            .join(", ");

        tracing::debug!(job_path = %job_path, parameters = %parameter_names, "Triggering Jenkins build");

        let response = self
            .retry_policy
            .retry_unsent(&url, || {
                self.http_client
                    .post(url.clone())
                    .header(reqwest::header::AUTHORIZATION, &self.auth_header)
                    .form(&form_data)
                    .send()
            })
            .await?;
        check_response(response).await.inspect_err(|e| {
            tracing::error!(job_path = %job_path, parameters = %parameter_names, error = %e, "Jenkins trigger failed");
        })?;

        tracing::info!("Jenkins build triggered successfully");
        Ok(())
    }

    pub async fn fetch_pipeline(
        &self, provider_id: i64, job_path: String,
    ) -> PluginResult<Pipeline> {
        let pipeline_start = std::time::Instant::now();
        tracing::debug!(job_path = %job_path, "Fetching Jenkins pipeline");

        let job_start = std::time::Instant::now();
        let job = self.fetch_job_details(&job_path).await?;
        tracing::debug!(elapsed = ?job_start.elapsed(), "Fetched Jenkins job details");

        let (status, last_run) = if let Some(ref last_build) = job.last_build {
            let build_start = std::time::Instant::now();
            let build = self
                .fetch_build_details(&job_path, last_build.number)
                .await?;
            tracing::debug!(elapsed = ?build_start.elapsed(), "Fetched Jenkins build details");

            let build_status = mapper::build_status(&build);
            let build_time = chrono::DateTime::from_timestamp_millis(build.timestamp)
                .map(|dt| dt.with_timezone(&Utc));
            (build_status, build_time)
        } else {
            tracing::debug!("No last Jenkins build found");
            (pipedash_plugin_api::PipelineStatus::Pending, None)
        };

        let (org, repo) = config::split_job_path(&job_path);
        let repository_field = if job_path.contains('/') {
            job_path.clone()
        } else {
            format!("{org}/{repo}")
        };

        tracing::debug!(elapsed = ?pipeline_start.elapsed(), "Total Jenkins pipeline fetch time");

        Ok(Pipeline {
            id: format!("jenkins__{provider_id}__{job_path}"),
            provider_id,
            provider_type: "jenkins".to_string(),
            name: job.name,
            status,
            last_run,
            last_updated: Utc::now(),
            repository: repository_field,
            branch: None,
            workflow_file: None,
            resource_state: None,
            metadata: HashMap::new(),
        })
    }

    pub async fn cancel_build(&self, job_path: &str, build_number: i64) -> PluginResult<()> {
        let encoded_path = config::encode_job_name(job_path);
        let url = parse_url(&format!(
            "{}/job/{}/{}/stop",
            self.server_url, encoded_path, build_number
        ))?;

        tracing::info!(build_number = build_number, job_path = %job_path, "Cancelling Jenkins build");

        let response = self
            .retry_policy
            .retry_unsent(&url, || {
                self.http_client
                    .post(url.clone())
                    .header(reqwest::header::AUTHORIZATION, &self.auth_header)
                    .send()
            })
            .await?;
        check_response(response).await?;

        tracing::info!(
            build_number = build_number,
            "Jenkins build cancelled successfully"
        );
        Ok(())
    }

    pub fn discovered_jobs_to_available_pipelines(
        &self, all_jobs: Vec<types::DiscoveredJob>,
    ) -> Vec<AvailablePipeline> {
        all_jobs
            .into_iter()
            .map(|job| {
                let job_type = if job._class.contains("WorkflowJob") {
                    "Pipeline"
                } else if job._class.contains("FreeStyleProject") {
                    "Freestyle"
                } else {
                    "Job"
                };

                let (organization, repository) = config::split_job_path(&job.full_path);

                AvailablePipeline {
                    id: job.full_path.clone(),
                    name: job.name,
                    description: Some(format!("Type: {job_type}")),
                    organization: Some(organization),
                    repository: Some(repository),
                }
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{
        AtomicUsize,
        Ordering,
    };
    use std::sync::Arc;

    use super::*;
    use crate::test_support::{
        stub_server,
        Reply,
    };

    fn unauthorized(_: &str) -> Reply {
        Reply {
            status: "401 Unauthorized",
            headers: "Content-Type: text/html\r\n",
            body: "<html><body><h2>HTTP ERROR 401 Unauthorized</h2></body></html>",
        }
    }

    fn not_found(_: &str) -> Reply {
        Reply {
            status: "404 Not Found",
            headers: "",
            body: "<html><body><h2>HTTP ERROR 404 Not Found</h2></body></html>",
        }
    }

    fn rate_limited(_: &str) -> Reply {
        Reply {
            status: "429 Too Many Requests",
            headers: "Retry-After: 120\r\n",
            body: "slow down",
        }
    }

    fn unavailable(_: &str) -> Reply {
        Reply {
            status: "503 Service Unavailable",
            headers: "",
            body: "maintenance",
        }
    }

    fn created(_: &str) -> Reply {
        Reply {
            status: "201 Created",
            headers: "",
            body: "",
        }
    }

    async fn client_for(
        reply: fn(&str) -> Reply, delay: Duration,
    ) -> (JenkinsClient, Arc<AtomicUsize>) {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let requests = Arc::new(AtomicUsize::new(0));
        let server_url = stub_server(requests.clone(), delay, reply).await;
        let http_client = Client::builder()
            .timeout(Duration::from_millis(300))
            .build()
            .unwrap();
        let client = JenkinsClient::new(
            Arc::new(http_client),
            server_url,
            "Basic YWxpY2U6d3Jvbmc=".to_string(),
        );
        (client, requests)
    }

    #[tokio::test]
    async fn rejected_credentials_fail_as_auth_error_without_retry() {
        let (client, requests) = client_for(unauthorized, Duration::ZERO).await;

        let results = [
            client.discover_all_jobs().await.err(),
            client.fetch_job_details("build").await.err(),
            client.fetch_build_details("build", 1).await.err(),
            client.fetch_build_history("build", 10).await.err(),
            client.fetch_job_parameters("build").await.err(),
        ];

        for error in results {
            assert!(
                matches!(error, Some(PluginError::AuthenticationFailed(_))),
                "{error:?}"
            );
        }
        assert_eq!(requests.load(Ordering::SeqCst), 5);
    }

    #[tokio::test]
    async fn missing_job_is_pipeline_not_found() {
        let (client, requests) = client_for(not_found, Duration::ZERO).await;

        let error = client.fetch_job_details("gone").await.unwrap_err();

        assert!(
            matches!(error, PluginError::PipelineNotFound(_)),
            "{error:?}"
        );
        assert_eq!(requests.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn rate_limit_carries_retry_after_and_is_not_retried() {
        let (client, requests) = client_for(rate_limited, Duration::ZERO).await;

        let error = client.fetch_job_details("build").await.unwrap_err();

        assert!(
            matches!(error, PluginError::RateLimited { .. }),
            "{error:?}"
        );
        assert_eq!(error.retry_after(), Some(Duration::from_secs(120)));
        assert_eq!(requests.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn server_error_is_service_unavailable_and_retried() {
        let (client, requests) = client_for(unavailable, Duration::ZERO).await;

        let error = client.fetch_job_details("build").await.unwrap_err();

        assert!(
            matches!(error, PluginError::ServiceUnavailable { .. }),
            "{error:?}"
        );
        assert_eq!(requests.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn timed_out_mutations_are_not_sent_again() {
        let (client, requests) = client_for(created, Duration::from_secs(2)).await;

        let trigger = client
            .trigger_build("build", vec![("name".to_string(), "value".to_string())])
            .await
            .unwrap_err();
        let cancel = client.cancel_build("build", 7).await.unwrap_err();

        assert!(
            matches!(trigger, PluginError::NetworkError(_)),
            "{trigger:?}"
        );
        assert!(matches!(cancel, PluginError::NetworkError(_)), "{cancel:?}");
        assert_eq!(requests.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn failed_trigger_error_has_no_parameter_values() {
        let (client, requests) = client_for(unavailable, Duration::ZERO).await;
        let secret = "s3cr3t-".repeat(20);

        let error = client
            .trigger_build(
                "build",
                vec![
                    ("DEPLOY_TOKEN".to_string(), secret.clone()),
                    ("short".to_string(), "hunter2".to_string()),
                ],
            )
            .await
            .unwrap_err();

        assert!(
            matches!(error, PluginError::ServiceUnavailable { .. }),
            "{error:?}"
        );
        let text = error.to_string();
        assert!(
            !text.contains("s3cr3t") && !text.contains("hunter2"),
            "{text}"
        );
        assert_eq!(requests.load(Ordering::SeqCst), 1);
    }

    fn multibranch(path: &str) -> Reply {
        let body = if path.starts_with("/job/app/") {
            r#"{"_class":"org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject","jobs":[{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","name":"main","url":"x"},{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","name":"feature-x","url":"x"}]}"#
        } else {
            r#"{"_class":"hudson.model.Hudson","jobs":[{"_class":"org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject","name":"app","url":"x"}]}"#
        };
        Reply {
            status: "200 OK",
            headers: "Content-Type: application/json\r\n",
            body,
        }
    }

    #[tokio::test]
    async fn multibranch_pipeline_lists_its_branch_jobs() {
        let (client, requests) = client_for(multibranch, Duration::ZERO).await;

        let jobs = client.discover_all_jobs().await.unwrap();

        let mut paths: Vec<&str> = jobs.iter().map(|job| job.full_path.as_str()).collect();
        paths.sort_unstable();
        assert_eq!(paths, ["app/feature-x", "app/main"]);
        assert_eq!(requests.load(Ordering::SeqCst), 2);
    }
}